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
110def _z3_check_cint_overflow(n, name):
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
158def _get_args_ast_list(args):
159 try:
160 if isinstance(args, (set, AstVector, tuple)):
161 return [arg for arg in args]
162 else:
163 return args
164 except Exception:
165 return args
166
167
168def _to_param_value(val):
169 if isinstance(val, bool):
170 return "true" if val else "false"
171 return str(val)
172
173
175 # Do nothing error handler, just avoid exit(0)
176 # The wrappers in z3core.py will raise a Z3Exception if an error is detected
177 return
178
179
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:
291 Z3_global_param_set(str(prev), _to_param_value(a))
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
511def _ctx_from_ast_args(*args):
512 return _ctx_from_ast_arg_list(args)
513
514
515def _to_func_decl_array(args):
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
523def _to_ast_array(args):
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
905def _to_func_decl_ref(a, ctx):
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
1183def _coerce_expr_merge(s, a):
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 s = None
1211 s = _coerce_expr_merge(s, a)
1212 s = _coerce_expr_merge(s, b)
1213 a = s.cast(a)
1214 b = s.cast(b)
1215 return (a, b)
1216
1217
1218def _reduce(func, sequence, initial):
1219 result = initial
1220 for element in sequence:
1221 result = func(result, element)
1222 return result
1223
1224
1225def _coerce_expr_list(alist, ctx=None):
1226 has_expr = False
1227 for a in alist:
1228 if is_expr(a):
1229 has_expr = True
1230 break
1231 if not has_expr:
1232 alist = [_py2expr(a, ctx) for a in alist]
1233 s = _reduce(_coerce_expr_merge, alist, None)
1234 return [s.cast(a) for a in alist]
1235
1236
1237def is_expr(a):
1238 """Return `True` if `a` is a Z3 expression.
1239
1240 >>> a = Int('a')
1241 >>> is_expr(a)
1242 True
1243 >>> is_expr(a + 1)
1244 True
1245 >>> is_expr(IntSort())
1246 False
1247 >>> is_expr(1)
1248 False
1249 >>> is_expr(IntVal(1))
1250 True
1251 >>> x = Int('x')
1252 >>> is_expr(ForAll(x, x >= 0))
1253 True
1254 >>> is_expr(FPVal(1.0))
1255 True
1256 """
1257 return isinstance(a, ExprRef)
1258
1259
1260def is_app(a):
1261 """Return `True` if `a` is a Z3 function application.
1262
1263 Note that, constants are function applications with 0 arguments.
1264
1265 >>> a = Int('a')
1266 >>> is_app(a)
1267 True
1268 >>> is_app(a + 1)
1269 True
1270 >>> is_app(IntSort())
1271 False
1272 >>> is_app(1)
1273 False
1274 >>> is_app(IntVal(1))
1275 True
1276 >>> x = Int('x')
1277 >>> is_app(ForAll(x, x >= 0))
1278 False
1279 """
1280 if not isinstance(a, ExprRef):
1281 return False
1282 k = _ast_kind(a.ctx, a)
1283 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1284
1285
1287 """Return `True` if `a` is Z3 constant/variable expression.
1288
1289 >>> a = Int('a')
1290 >>> is_const(a)
1291 True
1292 >>> is_const(a + 1)
1293 False
1294 >>> is_const(1)
1295 False
1296 >>> is_const(IntVal(1))
1297 True
1298 >>> x = Int('x')
1299 >>> is_const(ForAll(x, x >= 0))
1300 False
1301 """
1302 return is_app(a) and a.num_args() == 0
1303
1304
1305def is_var(a):
1306 """Return `True` if `a` is variable.
1307
1308 Z3 uses de-Bruijn indices for representing bound variables in
1309 quantifiers.
1310
1311 >>> x = Int('x')
1312 >>> is_var(x)
1313 False
1314 >>> is_const(x)
1315 True
1316 >>> f = Function('f', IntSort(), IntSort())
1317 >>> # Z3 replaces x with bound variables when ForAll is executed.
1318 >>> q = ForAll(x, f(x) == x)
1319 >>> b = q.body()
1320 >>> b
1321 f(Var(0)) == Var(0)
1322 >>> b.arg(1)
1323 Var(0)
1324 >>> is_var(b.arg(1))
1325 True
1326 """
1327 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1328
1329
1331 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1332
1333 >>> x = Int('x')
1334 >>> y = Int('y')
1335 >>> is_var(x)
1336 False
1337 >>> is_const(x)
1338 True
1339 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1340 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1341 >>> q = ForAll([x, y], f(x, y) == x + y)
1342 >>> q.body()
1343 f(Var(1), Var(0)) == Var(1) + Var(0)
1344 >>> b = q.body()
1345 >>> b.arg(0)
1346 f(Var(1), Var(0))
1347 >>> v1 = b.arg(0).arg(0)
1348 >>> v2 = b.arg(0).arg(1)
1349 >>> v1
1350 Var(1)
1351 >>> v2
1352 Var(0)
1353 >>> get_var_index(v1)
1354 1
1355 >>> get_var_index(v2)
1356 0
1357 """
1358 if z3_debug():
1359 _z3_assert(is_var(a), "Z3 bound variable expected")
1360 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1361
1362
1363def is_app_of(a, k):
1364 """Return `True` if `a` is an application of the given kind `k`.
1365
1366 >>> x = Int('x')
1367 >>> n = x + 1
1368 >>> is_app_of(n, Z3_OP_ADD)
1369 True
1370 >>> is_app_of(n, Z3_OP_MUL)
1371 False
1372 """
1373 return is_app(a) and a.decl().kind() == k
1374
1375
1376def If(a, b, c, ctx=None):
1377 """Create a Z3 if-then-else expression.
1378
1379 >>> x = Int('x')
1380 >>> y = Int('y')
1381 >>> max = If(x > y, x, y)
1382 >>> max
1383 If(x > y, x, y)
1384 >>> simplify(max)
1385 If(x <= y, y, x)
1386 """
1387 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1388 return Cond(a, b, c, ctx)
1389 else:
1390 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1391 s = BoolSort(ctx)
1392 a = s.cast(a)
1393 b, c = _coerce_exprs(b, c, ctx)
1394 if z3_debug():
1395 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1396 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1397
1398
1399def Distinct(*args):
1400 """Create a Z3 distinct expression.
1401
1402 >>> x = Int('x')
1403 >>> y = Int('y')
1404 >>> Distinct(x, y)
1405 x != y
1406 >>> z = Int('z')
1407 >>> Distinct(x, y, z)
1408 Distinct(x, y, z)
1409 >>> simplify(Distinct(x, y, z))
1410 Distinct(x, y, z)
1411 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1412 And(Not(x == y), Not(x == z), Not(y == z))
1413 """
1414 args = _get_args(args)
1415 ctx = _ctx_from_ast_arg_list(args)
1416 if z3_debug():
1417 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1418 args = _coerce_expr_list(args, ctx)
1419 _args, sz = _to_ast_array(args)
1420 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1421
1422
1423def _mk_bin(f, a, b):
1424 args = (Ast * 2)()
1425 if z3_debug():
1426 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1427 args[0] = a.as_ast()
1428 args[1] = b.as_ast()
1429 return f(a.ctx.ref(), 2, args)
1430
1431
1432def Const(name, sort):
1433 """Create a constant of the given sort.
1434
1435 >>> Const('x', IntSort())
1436 x
1437 """
1438 if z3_debug():
1439 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1440 ctx = sort.ctx
1441 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1442
1443
1444def Consts(names, sort):
1445 """Create several constants of the given sort.
1446
1447 `names` is a string containing the names of all constants to be created.
1448 Blank spaces separate the names of different constants.
1449
1450 >>> x, y, z = Consts('x y z', IntSort())
1451 >>> x + y + z
1452 x + y + z
1453 """
1454 if isinstance(names, str):
1455 names = names.split(" ")
1456 return [Const(name, sort) for name in names]
1457
1458
1459def FreshConst(sort, prefix="c"):
1460 """Create a fresh constant of a specified sort"""
1461 ctx = _get_ctx(sort.ctx)
1462 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1463
1464
1465def Var(idx, s):
1466 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1467
1468 >>> Var(0, IntSort())
1469 Var(0)
1470 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1471 False
1472 """
1473 if z3_debug():
1474 _z3_assert(is_sort(s), "Z3 sort expected")
1475 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1476
1477
1478def RealVar(idx, ctx=None):
1479 """
1480 Create a real free variable. Free variables are used to create quantified formulas.
1481 They are also used to create polynomials.
1482
1483 >>> RealVar(0)
1484 Var(0)
1485 """
1486 return Var(idx, RealSort(ctx))
1487
1488
1489def RealVarVector(n, ctx=None):
1490 """
1491 Create a list of Real free variables.
1492 The variables have ids: 0, 1, ..., n-1
1493
1494 >>> x0, x1, x2, x3 = RealVarVector(4)
1495 >>> x2
1496 Var(2)
1497 """
1498 return [RealVar(i, ctx) for i in range(n)]
1499
1500
1505
1506
1508 """Boolean sort."""
1509
1510 def cast(self, val):
1511 """Try to cast `val` as a Boolean.
1512
1513 >>> x = BoolSort().cast(True)
1514 >>> x
1515 True
1516 >>> is_expr(x)
1517 True
1518 >>> is_expr(True)
1519 False
1520 >>> x.sort()
1521 Bool
1522 """
1523 if isinstance(val, bool):
1524 return BoolVal(val, self.ctx)
1525 if z3_debug():
1526 if not is_expr(val):
1527 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1528 _z3_assert(is_expr(val), msg % (val, type(val)))
1529 if not self.eq(val.sort()):
1530 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1531 return val
1532
1533 def subsort(self, other):
1534 return isinstance(other, ArithSortRef)
1535
1536 def is_int(self):
1537 return True
1538
1539 def is_bool(self):
1540 return True
1541
1542
1544 """All Boolean expressions are instances of this class."""
1545
1546 def sort(self):
1547 return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1548
1549 def __rmul__(self, other):
1550 return self * other
1551
1552 def __mul__(self, other):
1553 """Create the Z3 expression `self * other`.
1554 """
1555 if other == 1:
1556 return self
1557 if other == 0:
1558 return 0
1559 return If(self, other, 0)
1560
1561
1562def is_bool(a):
1563 """Return `True` if `a` is a Z3 Boolean expression.
1564
1565 >>> p = Bool('p')
1566 >>> is_bool(p)
1567 True
1568 >>> q = Bool('q')
1569 >>> is_bool(And(p, q))
1570 True
1571 >>> x = Real('x')
1572 >>> is_bool(x)
1573 False
1574 >>> is_bool(x == 0)
1575 True
1576 """
1577 return isinstance(a, BoolRef)
1578
1579
1580def is_true(a):
1581 """Return `True` if `a` is the Z3 true expression.
1582
1583 >>> p = Bool('p')
1584 >>> is_true(p)
1585 False
1586 >>> is_true(simplify(p == p))
1587 True
1588 >>> x = Real('x')
1589 >>> is_true(x == 0)
1590 False
1591 >>> # True is a Python Boolean expression
1592 >>> is_true(True)
1593 False
1594 """
1595 return is_app_of(a, Z3_OP_TRUE)
1596
1597
1599 """Return `True` if `a` is the Z3 false expression.
1600
1601 >>> p = Bool('p')
1602 >>> is_false(p)
1603 False
1604 >>> is_false(False)
1605 False
1606 >>> is_false(BoolVal(False))
1607 True
1608 """
1609 return is_app_of(a, Z3_OP_FALSE)
1610
1611
1612def is_and(a):
1613 """Return `True` if `a` is a Z3 and expression.
1614
1615 >>> p, q = Bools('p q')
1616 >>> is_and(And(p, q))
1617 True
1618 >>> is_and(Or(p, q))
1619 False
1620 """
1621 return is_app_of(a, Z3_OP_AND)
1622
1623
1624def is_or(a):
1625 """Return `True` if `a` is a Z3 or expression.
1626
1627 >>> p, q = Bools('p q')
1628 >>> is_or(Or(p, q))
1629 True
1630 >>> is_or(And(p, q))
1631 False
1632 """
1633 return is_app_of(a, Z3_OP_OR)
1634
1635
1637 """Return `True` if `a` is a Z3 implication expression.
1638
1639 >>> p, q = Bools('p q')
1640 >>> is_implies(Implies(p, q))
1641 True
1642 >>> is_implies(And(p, q))
1643 False
1644 """
1645 return is_app_of(a, Z3_OP_IMPLIES)
1646
1647
1648def is_not(a):
1649 """Return `True` if `a` is a Z3 not expression.
1650
1651 >>> p = Bool('p')
1652 >>> is_not(p)
1653 False
1654 >>> is_not(Not(p))
1655 True
1656 """
1657 return is_app_of(a, Z3_OP_NOT)
1658
1659
1660def is_eq(a):
1661 """Return `True` if `a` is a Z3 equality expression.
1662
1663 >>> x, y = Ints('x y')
1664 >>> is_eq(x == y)
1665 True
1666 """
1667 return is_app_of(a, Z3_OP_EQ)
1668
1669
1671 """Return `True` if `a` is a Z3 distinct expression.
1672
1673 >>> x, y, z = Ints('x y z')
1674 >>> is_distinct(x == y)
1675 False
1676 >>> is_distinct(Distinct(x, y, z))
1677 True
1678 """
1679 return is_app_of(a, Z3_OP_DISTINCT)
1680
1681
1682def BoolSort(ctx=None):
1683 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1684
1685 >>> BoolSort()
1686 Bool
1687 >>> p = Const('p', BoolSort())
1688 >>> is_bool(p)
1689 True
1690 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1691 >>> r(0, 1)
1692 r(0, 1)
1693 >>> is_bool(r(0, 1))
1694 True
1695 """
1696 ctx = _get_ctx(ctx)
1697 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1698
1699
1700def BoolVal(val, ctx=None):
1701 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1702
1703 >>> BoolVal(True)
1704 True
1705 >>> is_true(BoolVal(True))
1706 True
1707 >>> is_true(True)
1708 False
1709 >>> is_false(BoolVal(False))
1710 True
1711 """
1712 ctx = _get_ctx(ctx)
1713 if val:
1714 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1715 else:
1716 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1717
1718
1719def Bool(name, ctx=None):
1720 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1721
1722 >>> p = Bool('p')
1723 >>> q = Bool('q')
1724 >>> And(p, q)
1725 And(p, q)
1726 """
1727 ctx = _get_ctx(ctx)
1728 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1729
1730
1731def Bools(names, ctx=None):
1732 """Return a tuple of Boolean constants.
1733
1734 `names` is a single string containing all names separated by blank spaces.
1735 If `ctx=None`, then the global context is used.
1736
1737 >>> p, q, r = Bools('p q r')
1738 >>> And(p, Or(q, r))
1739 And(p, Or(q, r))
1740 """
1741 ctx = _get_ctx(ctx)
1742 if isinstance(names, str):
1743 names = names.split(" ")
1744 return [Bool(name, ctx) for name in names]
1745
1746
1747def BoolVector(prefix, sz, ctx=None):
1748 """Return a list of Boolean constants of size `sz`.
1749
1750 The constants are named using the given prefix.
1751 If `ctx=None`, then the global context is used.
1752
1753 >>> P = BoolVector('p', 3)
1754 >>> P
1755 [p__0, p__1, p__2]
1756 >>> And(P)
1757 And(p__0, p__1, p__2)
1758 """
1759 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1760
1761
1762def FreshBool(prefix="b", ctx=None):
1763 """Return a fresh Boolean constant in the given context using the given prefix.
1764
1765 If `ctx=None`, then the global context is used.
1766
1767 >>> b1 = FreshBool()
1768 >>> b2 = FreshBool()
1769 >>> eq(b1, b2)
1770 False
1771 """
1772 ctx = _get_ctx(ctx)
1773 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1774
1775
1776def Implies(a, b, ctx=None):
1777 """Create a Z3 implies expression.
1778
1779 >>> p, q = Bools('p q')
1780 >>> Implies(p, q)
1781 Implies(p, q)
1782 """
1783 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1784 s = BoolSort(ctx)
1785 a = s.cast(a)
1786 b = s.cast(b)
1787 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1788
1789
1790def Xor(a, b, ctx=None):
1791 """Create a Z3 Xor expression.
1792
1793 >>> p, q = Bools('p q')
1794 >>> Xor(p, q)
1795 Xor(p, q)
1796 >>> simplify(Xor(p, q))
1797 Not(p == q)
1798 """
1799 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1800 s = BoolSort(ctx)
1801 a = s.cast(a)
1802 b = s.cast(b)
1803 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1804
1805
1806def Not(a, ctx=None):
1807 """Create a Z3 not expression or probe.
1808
1809 >>> p = Bool('p')
1810 >>> Not(Not(p))
1811 Not(Not(p))
1812 >>> simplify(Not(Not(p)))
1813 p
1814 """
1815 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1816 if is_probe(a):
1817 # Not is also used to build probes
1818 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1819 else:
1820 s = BoolSort(ctx)
1821 a = s.cast(a)
1822 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1823
1824
1825def mk_not(a):
1826 if is_not(a):
1827 return a.arg(0)
1828 else:
1829 return Not(a)
1830
1831
1832def _has_probe(args):
1833 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1834 for arg in args:
1835 if is_probe(arg):
1836 return True
1837 return False
1838
1839
1840def And(*args):
1841 """Create a Z3 and-expression or and-probe.
1842
1843 >>> p, q, r = Bools('p q r')
1844 >>> And(p, q, r)
1845 And(p, q, r)
1846 >>> P = BoolVector('p', 5)
1847 >>> And(P)
1848 And(p__0, p__1, p__2, p__3, p__4)
1849 """
1850 last_arg = None
1851 if len(args) > 0:
1852 last_arg = args[len(args) - 1]
1853 if isinstance(last_arg, Context):
1854 ctx = args[len(args) - 1]
1855 args = args[:len(args) - 1]
1856 elif len(args) == 1 and isinstance(args[0], AstVector):
1857 ctx = args[0].ctx
1858 args = [a for a in args[0]]
1859 else:
1860 ctx = None
1861 args = _get_args(args)
1862 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1863 if z3_debug():
1864 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1865 if _has_probe(args):
1866 return _probe_and(args, ctx)
1867 else:
1868 args = _coerce_expr_list(args, ctx)
1869 _args, sz = _to_ast_array(args)
1870 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1871
1872
1873def Or(*args):
1874 """Create a Z3 or-expression or or-probe.
1875
1876 >>> p, q, r = Bools('p q r')
1877 >>> Or(p, q, r)
1878 Or(p, q, r)
1879 >>> P = BoolVector('p', 5)
1880 >>> Or(P)
1881 Or(p__0, p__1, p__2, p__3, p__4)
1882 """
1883 last_arg = None
1884 if len(args) > 0:
1885 last_arg = args[len(args) - 1]
1886 if isinstance(last_arg, Context):
1887 ctx = args[len(args) - 1]
1888 args = args[:len(args) - 1]
1889 elif len(args) == 1 and isinstance(args[0], AstVector):
1890 ctx = args[0].ctx
1891 args = [a for a in args[0]]
1892 else:
1893 ctx = None
1894 args = _get_args(args)
1895 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
1896 if z3_debug():
1897 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1898 if _has_probe(args):
1899 return _probe_or(args, ctx)
1900 else:
1901 args = _coerce_expr_list(args, ctx)
1902 _args, sz = _to_ast_array(args)
1903 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1904
1905
1910
1911
1913 """Patterns are hints for quantifier instantiation.
1914
1915 """
1916
1917 def as_ast(self):
1918 return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1919
1920 def get_id(self):
1921 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1922
1923
1925 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1926
1927 >>> f = Function('f', IntSort(), IntSort())
1928 >>> x = Int('x')
1929 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1930 >>> q
1931 ForAll(x, f(x) == 0)
1932 >>> q.num_patterns()
1933 1
1934 >>> is_pattern(q.pattern(0))
1935 True
1936 >>> q.pattern(0)
1937 f(Var(0))
1938 """
1939 return isinstance(a, PatternRef)
1940
1941
1942def MultiPattern(*args):
1943 """Create a Z3 multi-pattern using the given expressions `*args`
1944
1945 >>> f = Function('f', IntSort(), IntSort())
1946 >>> g = Function('g', IntSort(), IntSort())
1947 >>> x = Int('x')
1948 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1949 >>> q
1950 ForAll(x, f(x) != g(x))
1951 >>> q.num_patterns()
1952 1
1953 >>> is_pattern(q.pattern(0))
1954 True
1955 >>> q.pattern(0)
1956 MultiPattern(f(Var(0)), g(Var(0)))
1957 """
1958 if z3_debug():
1959 _z3_assert(len(args) > 0, "At least one argument expected")
1960 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
1961 ctx = args[0].ctx
1962 args, sz = _to_ast_array(args)
1963 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1964
1965
1966def _to_pattern(arg):
1967 if is_pattern(arg):
1968 return arg
1969 else:
1970 return MultiPattern(arg)
1971
1972
1977
1978
1980 """Universally and Existentially quantified formulas."""
1981
1982 def as_ast(self):
1983 return self.ast
1984
1985 def get_id(self):
1986 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1987
1988 def sort(self):
1989 """Return the Boolean sort or sort of Lambda."""
1990 if self.is_lambda():
1991 return _sort(self.ctx, self.as_astas_astas_ast())
1992 return BoolSort(self.ctx)
1993
1994 def is_forall(self):
1995 """Return `True` if `self` is a universal quantifier.
1996
1997 >>> f = Function('f', IntSort(), IntSort())
1998 >>> x = Int('x')
1999 >>> q = ForAll(x, f(x) == 0)
2000 >>> q.is_forall()
2001 True
2002 >>> q = Exists(x, f(x) != 0)
2003 >>> q.is_forall()
2004 False
2005 """
2006 return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
2007
2008 def is_exists(self):
2009 """Return `True` if `self` is an existential quantifier.
2010
2011 >>> f = Function('f', IntSort(), IntSort())
2012 >>> x = Int('x')
2013 >>> q = ForAll(x, f(x) == 0)
2014 >>> q.is_exists()
2015 False
2016 >>> q = Exists(x, f(x) != 0)
2017 >>> q.is_exists()
2018 True
2019 """
2020 return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
2021
2022 def is_lambda(self):
2023 """Return `True` if `self` is a lambda expression.
2024
2025 >>> f = Function('f', IntSort(), IntSort())
2026 >>> x = Int('x')
2027 >>> q = Lambda(x, f(x))
2028 >>> q.is_lambda()
2029 True
2030 >>> q = Exists(x, f(x) != 0)
2031 >>> q.is_lambda()
2032 False
2033 """
2034 return Z3_is_lambda(self.ctx_ref(), self.ast)
2035
2036 def __getitem__(self, arg):
2037 """Return the Z3 expression `self[arg]`.
2038 """
2039 if z3_debug():
2040 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2041 return _array_select(self, arg)
2042
2043 def weight(self):
2044 """Return the weight annotation of `self`.
2045
2046 >>> f = Function('f', IntSort(), IntSort())
2047 >>> x = Int('x')
2048 >>> q = ForAll(x, f(x) == 0)
2049 >>> q.weight()
2050 1
2051 >>> q = ForAll(x, f(x) == 0, weight=10)
2052 >>> q.weight()
2053 10
2054 """
2055 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
2056
2057 def num_patterns(self):
2058 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2059
2060 >>> f = Function('f', IntSort(), IntSort())
2061 >>> g = Function('g', IntSort(), IntSort())
2062 >>> x = Int('x')
2063 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2064 >>> q.num_patterns()
2065 2
2066 """
2067 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
2068
2069 def pattern(self, idx):
2070 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2071
2072 >>> f = Function('f', IntSort(), IntSort())
2073 >>> g = Function('g', IntSort(), IntSort())
2074 >>> x = Int('x')
2075 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2076 >>> q.num_patterns()
2077 2
2078 >>> q.pattern(0)
2079 f(Var(0))
2080 >>> q.pattern(1)
2081 g(Var(0))
2082 """
2083 if z3_debug():
2084 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2085 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2086
2088 """Return the number of no-patterns."""
2089 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
2090
2091 def no_pattern(self, idx):
2092 """Return a no-pattern."""
2093 if z3_debug():
2094 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2095 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2096
2097 def body(self):
2098 """Return the expression being quantified.
2099
2100 >>> f = Function('f', IntSort(), IntSort())
2101 >>> x = Int('x')
2102 >>> q = ForAll(x, f(x) == 0)
2103 >>> q.body()
2104 f(Var(0)) == 0
2105 """
2106 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
2107
2108 def num_vars(self):
2109 """Return the number of variables bounded by this quantifier.
2110
2111 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2112 >>> x = Int('x')
2113 >>> y = Int('y')
2114 >>> q = ForAll([x, y], f(x, y) >= x)
2115 >>> q.num_vars()
2116 2
2117 """
2118 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
2119
2120 def var_name(self, idx):
2121 """Return a string representing a name used when displaying the quantifier.
2122
2123 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2124 >>> x = Int('x')
2125 >>> y = Int('y')
2126 >>> q = ForAll([x, y], f(x, y) >= x)
2127 >>> q.var_name(0)
2128 'x'
2129 >>> q.var_name(1)
2130 'y'
2131 """
2132 if z3_debug():
2133 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2134 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
2135
2136 def var_sort(self, idx):
2137 """Return the sort of a bound variable.
2138
2139 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2140 >>> x = Int('x')
2141 >>> y = Real('y')
2142 >>> q = ForAll([x, y], f(x, y) >= x)
2143 >>> q.var_sort(0)
2144 Int
2145 >>> q.var_sort(1)
2146 Real
2147 """
2148 if z3_debug():
2149 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2150 return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
2151
2152 def children(self):
2153 """Return a list containing a single element self.body()
2154
2155 >>> f = Function('f', IntSort(), IntSort())
2156 >>> x = Int('x')
2157 >>> q = ForAll(x, f(x) == 0)
2158 >>> q.children()
2159 [f(Var(0)) == 0]
2160 """
2161 return [self.body()]
2162
2163
2165 """Return `True` if `a` is a Z3 quantifier.
2166
2167 >>> f = Function('f', IntSort(), IntSort())
2168 >>> x = Int('x')
2169 >>> q = ForAll(x, f(x) == 0)
2170 >>> is_quantifier(q)
2171 True
2172 >>> is_quantifier(f(x))
2173 False
2174 """
2175 return isinstance(a, QuantifierRef)
2176
2177
2178def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2179 if z3_debug():
2180 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2181 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2182 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2183 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2184 if is_app(vs):
2185 ctx = vs.ctx
2186 vs = [vs]
2187 else:
2188 ctx = vs[0].ctx
2189 if not is_expr(body):
2190 body = BoolVal(body, ctx)
2191 num_vars = len(vs)
2192 if num_vars == 0:
2193 return body
2194 _vs = (Ast * num_vars)()
2195 for i in range(num_vars):
2196 # TODO: Check if is constant
2197 _vs[i] = vs[i].as_ast()
2198 patterns = [_to_pattern(p) for p in patterns]
2199 num_pats = len(patterns)
2200 _pats = (Pattern * num_pats)()
2201 for i in range(num_pats):
2202 _pats[i] = patterns[i].ast
2203 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2204 qid = to_symbol(qid, ctx)
2205 skid = to_symbol(skid, ctx)
2206 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2207 num_vars, _vs,
2208 num_pats, _pats,
2209 num_no_pats, _no_pats,
2210 body.as_ast()), ctx)
2211
2212
2213def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2214 """Create a Z3 forall formula.
2215
2216 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2217
2218 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2219 >>> x = Int('x')
2220 >>> y = Int('y')
2221 >>> ForAll([x, y], f(x, y) >= x)
2222 ForAll([x, y], f(x, y) >= x)
2223 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2224 ForAll([x, y], f(x, y) >= x)
2225 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2226 ForAll([x, y], f(x, y) >= x)
2227 """
2228 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2229
2230
2231def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2232 """Create a Z3 exists formula.
2233
2234 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2235
2236
2237 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2238 >>> x = Int('x')
2239 >>> y = Int('y')
2240 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2241 >>> q
2242 Exists([x, y], f(x, y) >= x)
2243 >>> is_quantifier(q)
2244 True
2245 >>> r = Tactic('nnf')(q).as_expr()
2246 >>> is_quantifier(r)
2247 False
2248 """
2249 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2250
2251
2252def Lambda(vs, body):
2253 """Create a Z3 lambda expression.
2254
2255 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2256 >>> mem0 = Array('mem0', IntSort(), IntSort())
2257 >>> lo, hi, e, i = Ints('lo hi e i')
2258 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2259 >>> mem1
2260 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2261 """
2262 ctx = body.ctx
2263 if is_app(vs):
2264 vs = [vs]
2265 num_vars = len(vs)
2266 _vs = (Ast * num_vars)()
2267 for i in range(num_vars):
2268 # TODO: Check if is constant
2269 _vs[i] = vs[i].as_ast()
2270 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2271
2272
2277
2278
2280 """Real and Integer sorts."""
2281
2282 def is_real(self):
2283 """Return `True` if `self` is of the sort Real.
2284
2285 >>> x = Real('x')
2286 >>> x.is_real()
2287 True
2288 >>> (x + 1).is_real()
2289 True
2290 >>> x = Int('x')
2291 >>> x.is_real()
2292 False
2293 """
2294 return self.kind() == Z3_REAL_SORT
2295
2296 def is_int(self):
2297 """Return `True` if `self` is of the sort Integer.
2298
2299 >>> x = Int('x')
2300 >>> x.is_int()
2301 True
2302 >>> (x + 1).is_int()
2303 True
2304 >>> x = Real('x')
2305 >>> x.is_int()
2306 False
2307 """
2308 return self.kind() == Z3_INT_SORT
2309
2310 def is_bool(self):
2311 return False
2312
2313 def subsort(self, other):
2314 """Return `True` if `self` is a subsort of `other`."""
2315 return self.is_int() and is_arith_sort(other) and other.is_real()
2316
2317 def cast(self, val):
2318 """Try to cast `val` as an Integer or Real.
2319
2320 >>> IntSort().cast(10)
2321 10
2322 >>> is_int(IntSort().cast(10))
2323 True
2324 >>> is_int(10)
2325 False
2326 >>> RealSort().cast(10)
2327 10
2328 >>> is_real(RealSort().cast(10))
2329 True
2330 """
2331 if is_expr(val):
2332 if z3_debug():
2333 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
2334 val_s = val.sort()
2335 if self.eq(val_s):
2336 return val
2337 if val_s.is_int() and self.is_real():
2338 return ToReal(val)
2339 if val_s.is_bool() and self.is_int():
2340 return If(val, 1, 0)
2341 if val_s.is_bool() and self.is_real():
2342 return ToReal(If(val, 1, 0))
2343 if z3_debug():
2344 _z3_assert(False, "Z3 Integer/Real expression expected")
2345 else:
2346 if self.is_int():
2347 return IntVal(val, self.ctxctx)
2348 if self.is_real():
2349 return RealVal(val, self.ctxctx)
2350 if z3_debug():
2351 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2352 _z3_assert(False, msg % self)
2353
2354
2356 """Return `True` if s is an arithmetical sort (type).
2357
2358 >>> is_arith_sort(IntSort())
2359 True
2360 >>> is_arith_sort(RealSort())
2361 True
2362 >>> is_arith_sort(BoolSort())
2363 False
2364 >>> n = Int('x') + 1
2365 >>> is_arith_sort(n.sort())
2366 True
2367 """
2368 return isinstance(s, ArithSortRef)
2369
2370
2372 """Integer and Real expressions."""
2373
2374 def sort(self):
2375 """Return the sort (type) of the arithmetical expression `self`.
2376
2377 >>> Int('x').sort()
2378 Int
2379 >>> (Real('x') + 1).sort()
2380 Real
2381 """
2382 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2383
2384 def is_int(self):
2385 """Return `True` if `self` is an integer expression.
2386
2387 >>> x = Int('x')
2388 >>> x.is_int()
2389 True
2390 >>> (x + 1).is_int()
2391 True
2392 >>> y = Real('y')
2393 >>> (x + y).is_int()
2394 False
2395 """
2396 return self.sortsort().is_int()
2397
2398 def is_real(self):
2399 """Return `True` if `self` is an real expression.
2400
2401 >>> x = Real('x')
2402 >>> x.is_real()
2403 True
2404 >>> (x + 1).is_real()
2405 True
2406 """
2407 return self.sortsort().is_real()
2408
2409 def __add__(self, other):
2410 """Create the Z3 expression `self + other`.
2411
2412 >>> x = Int('x')
2413 >>> y = Int('y')
2414 >>> x + y
2415 x + y
2416 >>> (x + y).sort()
2417 Int
2418 """
2419 a, b = _coerce_exprs(self, other)
2420 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2421
2422 def __radd__(self, other):
2423 """Create the Z3 expression `other + self`.
2424
2425 >>> x = Int('x')
2426 >>> 10 + x
2427 10 + x
2428 """
2429 a, b = _coerce_exprs(self, other)
2430 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2431
2432 def __mul__(self, other):
2433 """Create the Z3 expression `self * other`.
2434
2435 >>> x = Real('x')
2436 >>> y = Real('y')
2437 >>> x * y
2438 x*y
2439 >>> (x * y).sort()
2440 Real
2441 """
2442 if isinstance(other, BoolRef):
2443 return If(other, self, 0)
2444 a, b = _coerce_exprs(self, other)
2445 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2446
2447 def __rmul__(self, other):
2448 """Create the Z3 expression `other * self`.
2449
2450 >>> x = Real('x')
2451 >>> 10 * x
2452 10*x
2453 """
2454 a, b = _coerce_exprs(self, other)
2455 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2456
2457 def __sub__(self, other):
2458 """Create the Z3 expression `self - other`.
2459
2460 >>> x = Int('x')
2461 >>> y = Int('y')
2462 >>> x - y
2463 x - y
2464 >>> (x - y).sort()
2465 Int
2466 """
2467 a, b = _coerce_exprs(self, other)
2468 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2469
2470 def __rsub__(self, other):
2471 """Create the Z3 expression `other - self`.
2472
2473 >>> x = Int('x')
2474 >>> 10 - x
2475 10 - x
2476 """
2477 a, b = _coerce_exprs(self, other)
2478 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2479
2480 def __pow__(self, other):
2481 """Create the Z3 expression `self**other` (** is the power operator).
2482
2483 >>> x = Real('x')
2484 >>> x**3
2485 x**3
2486 >>> (x**3).sort()
2487 Real
2488 >>> simplify(IntVal(2)**8)
2489 256
2490 """
2491 a, b = _coerce_exprs(self, other)
2492 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2493
2494 def __rpow__(self, other):
2495 """Create the Z3 expression `other**self` (** is the power operator).
2496
2497 >>> x = Real('x')
2498 >>> 2**x
2499 2**x
2500 >>> (2**x).sort()
2501 Real
2502 >>> simplify(2**IntVal(8))
2503 256
2504 """
2505 a, b = _coerce_exprs(self, other)
2506 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2507
2508 def __div__(self, other):
2509 """Create the Z3 expression `other/self`.
2510
2511 >>> x = Int('x')
2512 >>> y = Int('y')
2513 >>> x/y
2514 x/y
2515 >>> (x/y).sort()
2516 Int
2517 >>> (x/y).sexpr()
2518 '(div x y)'
2519 >>> x = Real('x')
2520 >>> y = Real('y')
2521 >>> x/y
2522 x/y
2523 >>> (x/y).sort()
2524 Real
2525 >>> (x/y).sexpr()
2526 '(/ x y)'
2527 """
2528 a, b = _coerce_exprs(self, other)
2529 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2530
2531 def __truediv__(self, other):
2532 """Create the Z3 expression `other/self`."""
2533 return self.__div__(other)
2534
2535 def __rdiv__(self, other):
2536 """Create the Z3 expression `other/self`.
2537
2538 >>> x = Int('x')
2539 >>> 10/x
2540 10/x
2541 >>> (10/x).sexpr()
2542 '(div 10 x)'
2543 >>> x = Real('x')
2544 >>> 10/x
2545 10/x
2546 >>> (10/x).sexpr()
2547 '(/ 10.0 x)'
2548 """
2549 a, b = _coerce_exprs(self, other)
2550 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2551
2552 def __rtruediv__(self, other):
2553 """Create the Z3 expression `other/self`."""
2554 return self.__rdiv__(other)
2555
2556 def __mod__(self, other):
2557 """Create the Z3 expression `other%self`.
2558
2559 >>> x = Int('x')
2560 >>> y = Int('y')
2561 >>> x % y
2562 x%y
2563 >>> simplify(IntVal(10) % IntVal(3))
2564 1
2565 """
2566 a, b = _coerce_exprs(self, other)
2567 if z3_debug():
2568 _z3_assert(a.is_int(), "Z3 integer expression expected")
2569 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2570
2571 def __rmod__(self, other):
2572 """Create the Z3 expression `other%self`.
2573
2574 >>> x = Int('x')
2575 >>> 10 % x
2576 10%x
2577 """
2578 a, b = _coerce_exprs(self, other)
2579 if z3_debug():
2580 _z3_assert(a.is_int(), "Z3 integer expression expected")
2581 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2582
2583 def __neg__(self):
2584 """Return an expression representing `-self`.
2585
2586 >>> x = Int('x')
2587 >>> -x
2588 -x
2589 >>> simplify(-(-x))
2590 x
2591 """
2592 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2593
2594 def __pos__(self):
2595 """Return `self`.
2596
2597 >>> x = Int('x')
2598 >>> +x
2599 x
2600 """
2601 return self
2602
2603 def __le__(self, other):
2604 """Create the Z3 expression `other <= self`.
2605
2606 >>> x, y = Ints('x y')
2607 >>> x <= y
2608 x <= y
2609 >>> y = Real('y')
2610 >>> x <= y
2611 ToReal(x) <= y
2612 """
2613 a, b = _coerce_exprs(self, other)
2614 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2615
2616 def __lt__(self, other):
2617 """Create the Z3 expression `other < self`.
2618
2619 >>> x, y = Ints('x y')
2620 >>> x < y
2621 x < y
2622 >>> y = Real('y')
2623 >>> x < y
2624 ToReal(x) < y
2625 """
2626 a, b = _coerce_exprs(self, other)
2627 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2628
2629 def __gt__(self, other):
2630 """Create the Z3 expression `other > self`.
2631
2632 >>> x, y = Ints('x y')
2633 >>> x > y
2634 x > y
2635 >>> y = Real('y')
2636 >>> x > y
2637 ToReal(x) > y
2638 """
2639 a, b = _coerce_exprs(self, other)
2640 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2641
2642 def __ge__(self, other):
2643 """Create the Z3 expression `other >= self`.
2644
2645 >>> x, y = Ints('x y')
2646 >>> x >= y
2647 x >= y
2648 >>> y = Real('y')
2649 >>> x >= y
2650 ToReal(x) >= y
2651 """
2652 a, b = _coerce_exprs(self, other)
2653 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2654
2655
2657 """Return `True` if `a` is an arithmetical expression.
2658
2659 >>> x = Int('x')
2660 >>> is_arith(x)
2661 True
2662 >>> is_arith(x + 1)
2663 True
2664 >>> is_arith(1)
2665 False
2666 >>> is_arith(IntVal(1))
2667 True
2668 >>> y = Real('y')
2669 >>> is_arith(y)
2670 True
2671 >>> is_arith(y + 1)
2672 True
2673 """
2674 return isinstance(a, ArithRef)
2675
2676
2677def is_int(a):
2678 """Return `True` if `a` is an integer expression.
2679
2680 >>> x = Int('x')
2681 >>> is_int(x + 1)
2682 True
2683 >>> is_int(1)
2684 False
2685 >>> is_int(IntVal(1))
2686 True
2687 >>> y = Real('y')
2688 >>> is_int(y)
2689 False
2690 >>> is_int(y + 1)
2691 False
2692 """
2693 return is_arith(a) and a.is_int()
2694
2695
2696def is_real(a):
2697 """Return `True` if `a` is a real expression.
2698
2699 >>> x = Int('x')
2700 >>> is_real(x + 1)
2701 False
2702 >>> y = Real('y')
2703 >>> is_real(y)
2704 True
2705 >>> is_real(y + 1)
2706 True
2707 >>> is_real(1)
2708 False
2709 >>> is_real(RealVal(1))
2710 True
2711 """
2712 return is_arith(a) and a.is_real()
2713
2714
2715def _is_numeral(ctx, a):
2716 return Z3_is_numeral_ast(ctx.ref(), a)
2717
2718
2719def _is_algebraic(ctx, a):
2720 return Z3_is_algebraic_number(ctx.ref(), a)
2721
2722
2724 """Return `True` if `a` is an integer value of sort Int.
2725
2726 >>> is_int_value(IntVal(1))
2727 True
2728 >>> is_int_value(1)
2729 False
2730 >>> is_int_value(Int('x'))
2731 False
2732 >>> n = Int('x') + 1
2733 >>> n
2734 x + 1
2735 >>> n.arg(1)
2736 1
2737 >>> is_int_value(n.arg(1))
2738 True
2739 >>> is_int_value(RealVal("1/3"))
2740 False
2741 >>> is_int_value(RealVal(1))
2742 False
2743 """
2744 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2745
2746
2748 """Return `True` if `a` is rational value of sort Real.
2749
2751 True
2752 >>> is_rational_value(RealVal("3/5"))
2753 True
2755 False
2756 >>> is_rational_value(1)
2757 False
2758 >>> n = Real('x') + 1
2759 >>> n.arg(1)
2760 1
2761 >>> is_rational_value(n.arg(1))
2762 True
2763 >>> is_rational_value(Real('x'))
2764 False
2765 """
2766 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2767
2768
2770 """Return `True` if `a` is an algebraic value of sort Real.
2771
2772 >>> is_algebraic_value(RealVal("3/5"))
2773 False
2774 >>> n = simplify(Sqrt(2))
2775 >>> n
2776 1.4142135623?
2777 >>> is_algebraic_value(n)
2778 True
2779 """
2780 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2781
2782
2783def is_add(a):
2784 """Return `True` if `a` is an expression of the form b + c.
2785
2786 >>> x, y = Ints('x y')
2787 >>> is_add(x + y)
2788 True
2789 >>> is_add(x - y)
2790 False
2791 """
2792 return is_app_of(a, Z3_OP_ADD)
2793
2794
2795def is_mul(a):
2796 """Return `True` if `a` is an expression of the form b * c.
2797
2798 >>> x, y = Ints('x y')
2799 >>> is_mul(x * y)
2800 True
2801 >>> is_mul(x - y)
2802 False
2803 """
2804 return is_app_of(a, Z3_OP_MUL)
2805
2806
2807def is_sub(a):
2808 """Return `True` if `a` is an expression of the form b - c.
2809
2810 >>> x, y = Ints('x y')
2811 >>> is_sub(x - y)
2812 True
2813 >>> is_sub(x + y)
2814 False
2815 """
2816 return is_app_of(a, Z3_OP_SUB)
2817
2818
2819def is_div(a):
2820 """Return `True` if `a` is an expression of the form b / c.
2821
2822 >>> x, y = Reals('x y')
2823 >>> is_div(x / y)
2824 True
2825 >>> is_div(x + y)
2826 False
2827 >>> x, y = Ints('x y')
2828 >>> is_div(x / y)
2829 False
2830 >>> is_idiv(x / y)
2831 True
2832 """
2833 return is_app_of(a, Z3_OP_DIV)
2834
2835
2836def is_idiv(a):
2837 """Return `True` if `a` is an expression of the form b div c.
2838
2839 >>> x, y = Ints('x y')
2840 >>> is_idiv(x / y)
2841 True
2842 >>> is_idiv(x + y)
2843 False
2844 """
2845 return is_app_of(a, Z3_OP_IDIV)
2846
2847
2848def is_mod(a):
2849 """Return `True` if `a` is an expression of the form b % c.
2850
2851 >>> x, y = Ints('x y')
2852 >>> is_mod(x % y)
2853 True
2854 >>> is_mod(x + y)
2855 False
2856 """
2857 return is_app_of(a, Z3_OP_MOD)
2858
2859
2860def is_le(a):
2861 """Return `True` if `a` is an expression of the form b <= c.
2862
2863 >>> x, y = Ints('x y')
2864 >>> is_le(x <= y)
2865 True
2866 >>> is_le(x < y)
2867 False
2868 """
2869 return is_app_of(a, Z3_OP_LE)
2870
2871
2872def is_lt(a):
2873 """Return `True` if `a` is an expression of the form b < c.
2874
2875 >>> x, y = Ints('x y')
2876 >>> is_lt(x < y)
2877 True
2878 >>> is_lt(x == y)
2879 False
2880 """
2881 return is_app_of(a, Z3_OP_LT)
2882
2883
2884def is_ge(a):
2885 """Return `True` if `a` is an expression of the form b >= c.
2886
2887 >>> x, y = Ints('x y')
2888 >>> is_ge(x >= y)
2889 True
2890 >>> is_ge(x == y)
2891 False
2892 """
2893 return is_app_of(a, Z3_OP_GE)
2894
2895
2896def is_gt(a):
2897 """Return `True` if `a` is an expression of the form b > c.
2898
2899 >>> x, y = Ints('x y')
2900 >>> is_gt(x > y)
2901 True
2902 >>> is_gt(x == y)
2903 False
2904 """
2905 return is_app_of(a, Z3_OP_GT)
2906
2907
2909 """Return `True` if `a` is an expression of the form IsInt(b).
2910
2911 >>> x = Real('x')
2912 >>> is_is_int(IsInt(x))
2913 True
2914 >>> is_is_int(x)
2915 False
2916 """
2917 return is_app_of(a, Z3_OP_IS_INT)
2918
2919
2921 """Return `True` if `a` is an expression of the form ToReal(b).
2922
2923 >>> x = Int('x')
2924 >>> n = ToReal(x)
2925 >>> n
2926 ToReal(x)
2927 >>> is_to_real(n)
2928 True
2929 >>> is_to_real(x)
2930 False
2931 """
2932 return is_app_of(a, Z3_OP_TO_REAL)
2933
2934
2936 """Return `True` if `a` is an expression of the form ToInt(b).
2937
2938 >>> x = Real('x')
2939 >>> n = ToInt(x)
2940 >>> n
2941 ToInt(x)
2942 >>> is_to_int(n)
2943 True
2944 >>> is_to_int(x)
2945 False
2946 """
2947 return is_app_of(a, Z3_OP_TO_INT)
2948
2949
2951 """Integer values."""
2952
2953 def as_long(self):
2954 """Return a Z3 integer numeral as a Python long (bignum) numeral.
2955
2956 >>> v = IntVal(1)
2957 >>> v + 1
2958 1 + 1
2959 >>> v.as_long() + 1
2960 2
2961 """
2962 if z3_debug():
2963 _z3_assert(self.is_int(), "Integer value expected")
2964 return int(self.as_string())
2965
2966 def as_string(self):
2967 """Return a Z3 integer numeral as a Python string.
2968 >>> v = IntVal(100)
2969 >>> v.as_string()
2970 '100'
2971 """
2972 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
2973
2975 """Return a Z3 integer numeral as a Python binary string.
2976 >>> v = IntVal(10)
2977 >>> v.as_binary_string()
2978 '1010'
2979 """
2981
2982
2984 """Rational values."""
2985
2986 def numerator(self):
2987 """ Return the numerator of a Z3 rational numeral.
2988
2989 >>> is_rational_value(RealVal("3/5"))
2990 True
2991 >>> n = RealVal("3/5")
2992 >>> n.numerator()
2993 3
2994 >>> is_rational_value(Q(3,5))
2995 True
2996 >>> Q(3,5).numerator()
2997 3
2998 """
2999 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3000
3001 def denominator(self):
3002 """ Return the denominator of a Z3 rational numeral.
3003
3004 >>> is_rational_value(Q(3,5))
3005 True
3006 >>> n = Q(3,5)
3007 >>> n.denominator()
3008 5
3009 """
3010 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3011
3013 """ Return the numerator as a Python long.
3014
3015 >>> v = RealVal(10000000000)
3016 >>> v
3017 10000000000
3018 >>> v + 1
3019 10000000000 + 1
3020 >>> v.numerator_as_long() + 1 == 10000000001
3021 True
3022 """
3023 return self.numerator().as_long()
3024
3026 """ Return the denominator as a Python long.
3027
3028 >>> v = RealVal("1/3")
3029 >>> v
3030 1/3
3031 >>> v.denominator_as_long()
3032 3
3033 """
3034 return self.denominator().as_long()
3035
3036 def is_int(self):
3037 return False
3038
3039 def is_real(self):
3040 return True
3041
3042 def is_int_value(self):
3043 return self.denominator().is_int() and self.denominator_as_long() == 1
3044
3045 def as_long(self):
3046 _z3_assert(self.is_int_value(), "Expected integer fraction")
3047 return self.numerator_as_long()
3048
3049 def as_decimal(self, prec):
3050 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3051
3052 >>> v = RealVal("1/5")
3053 >>> v.as_decimal(3)
3054 '0.2'
3055 >>> v = RealVal("1/3")
3056 >>> v.as_decimal(3)
3057 '0.333?'
3058 """
3059 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3060
3061 def as_string(self):
3062 """Return a Z3 rational numeral as a Python string.
3063
3064 >>> v = Q(3,6)
3065 >>> v.as_string()
3066 '1/2'
3067 """
3068 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3069
3070 def as_fraction(self):
3071 """Return a Z3 rational as a Python Fraction object.
3072
3073 >>> v = RealVal("1/5")
3074 >>> v.as_fraction()
3075 Fraction(1, 5)
3076 """
3077 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3078
3079
3081 """Algebraic irrational values."""
3082
3083 def approx(self, precision=10):
3084 """Return a Z3 rational number that approximates the algebraic number `self`.
3085 The result `r` is such that |r - self| <= 1/10^precision
3086
3087 >>> x = simplify(Sqrt(2))
3088 >>> x.approx(20)
3089 6838717160008073720548335/4835703278458516698824704
3090 >>> x.approx(5)
3091 2965821/2097152
3092 """
3093 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_astas_ast(), precision), self.ctx)
3094
3095 def as_decimal(self, prec):
3096 """Return a string representation of the algebraic number `self` in decimal notation
3097 using `prec` decimal places.
3098
3099 >>> x = simplify(Sqrt(2))
3100 >>> x.as_decimal(10)
3101 '1.4142135623?'
3102 >>> x.as_decimal(20)
3103 '1.41421356237309504880?'
3104 """
3105 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3106
3107 def poly(self):
3108 return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3109
3110 def index(self):
3111 return Z3_algebraic_get_i(self.ctx_ref(), self.as_astas_ast())
3112
3113
3114def _py2expr(a, ctx=None):
3115 if isinstance(a, bool):
3116 return BoolVal(a, ctx)
3117 if _is_int(a):
3118 return IntVal(a, ctx)
3119 if isinstance(a, float):
3120 return RealVal(a, ctx)
3121 if isinstance(a, str):
3122 return StringVal(a, ctx)
3123 if is_expr(a):
3124 return a
3125 if z3_debug():
3126 _z3_assert(False, "Python bool, int, long or float expected")
3127
3128
3129def IntSort(ctx=None):
3130 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3131
3132 >>> IntSort()
3133 Int
3134 >>> x = Const('x', IntSort())
3135 >>> is_int(x)
3136 True
3137 >>> x.sort() == IntSort()
3138 True
3139 >>> x.sort() == BoolSort()
3140 False
3141 """
3142 ctx = _get_ctx(ctx)
3143 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3144
3145
3146def RealSort(ctx=None):
3147 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3148
3149 >>> RealSort()
3150 Real
3151 >>> x = Const('x', RealSort())
3152 >>> is_real(x)
3153 True
3154 >>> is_int(x)
3155 False
3156 >>> x.sort() == RealSort()
3157 True
3158 """
3159 ctx = _get_ctx(ctx)
3160 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3161
3162
3163def _to_int_str(val):
3164 if isinstance(val, float):
3165 return str(int(val))
3166 elif isinstance(val, bool):
3167 if val:
3168 return "1"
3169 else:
3170 return "0"
3171 elif _is_int(val):
3172 return str(val)
3173 elif isinstance(val, str):
3174 return val
3175 if z3_debug():
3176 _z3_assert(False, "Python value cannot be used as a Z3 integer")
3177
3178
3179def IntVal(val, ctx=None):
3180 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3181
3182 >>> IntVal(1)
3183 1
3184 >>> IntVal("100")
3185 100
3186 """
3187 ctx = _get_ctx(ctx)
3188 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3189
3190
3191def RealVal(val, ctx=None):
3192 """Return a Z3 real value.
3193
3194 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3195 If `ctx=None`, then the global context is used.
3196
3197 >>> RealVal(1)
3198 1
3199 >>> RealVal(1).sort()
3200 Real
3201 >>> RealVal("3/5")
3202 3/5
3203 >>> RealVal("1.5")
3204 3/2
3205 """
3206 ctx = _get_ctx(ctx)
3207 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3208
3209
3210def RatVal(a, b, ctx=None):
3211 """Return a Z3 rational a/b.
3212
3213 If `ctx=None`, then the global context is used.
3214
3215 >>> RatVal(3,5)
3216 3/5
3217 >>> RatVal(3,5).sort()
3218 Real
3219 """
3220 if z3_debug():
3221 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3222 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3223 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3224
3225
3226def Q(a, b, ctx=None):
3227 """Return a Z3 rational a/b.
3228
3229 If `ctx=None`, then the global context is used.
3230
3231 >>> Q(3,5)
3232 3/5
3233 >>> Q(3,5).sort()
3234 Real
3235 """
3236 return simplify(RatVal(a, b, ctx=ctx))
3237
3238
3239def Int(name, ctx=None):
3240 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3241
3242 >>> x = Int('x')
3243 >>> is_int(x)
3244 True
3245 >>> is_int(x + 1)
3246 True
3247 """
3248 ctx = _get_ctx(ctx)
3249 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3250
3251
3252def Ints(names, ctx=None):
3253 """Return a tuple of Integer constants.
3254
3255 >>> x, y, z = Ints('x y z')
3256 >>> Sum(x, y, z)
3257 x + y + z
3258 """
3259 ctx = _get_ctx(ctx)
3260 if isinstance(names, str):
3261 names = names.split(" ")
3262 return [Int(name, ctx) for name in names]
3263
3264
3265def IntVector(prefix, sz, ctx=None):
3266 """Return a list of integer constants of size `sz`.
3267
3268 >>> X = IntVector('x', 3)
3269 >>> X
3270 [x__0, x__1, x__2]
3271 >>> Sum(X)
3272 x__0 + x__1 + x__2
3273 """
3274 ctx = _get_ctx(ctx)
3275 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3276
3277
3278def FreshInt(prefix="x", ctx=None):
3279 """Return a fresh integer constant in the given context using the given prefix.
3280
3281 >>> x = FreshInt()
3282 >>> y = FreshInt()
3283 >>> eq(x, y)
3284 False
3285 >>> x.sort()
3286 Int
3287 """
3288 ctx = _get_ctx(ctx)
3289 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3290
3291
3292def Real(name, ctx=None):
3293 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3294
3295 >>> x = Real('x')
3296 >>> is_real(x)
3297 True
3298 >>> is_real(x + 1)
3299 True
3300 """
3301 ctx = _get_ctx(ctx)
3302 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3303
3304
3305def Reals(names, ctx=None):
3306 """Return a tuple of real constants.
3307
3308 >>> x, y, z = Reals('x y z')
3309 >>> Sum(x, y, z)
3310 x + y + z
3311 >>> Sum(x, y, z).sort()
3312 Real
3313 """
3314 ctx = _get_ctx(ctx)
3315 if isinstance(names, str):
3316 names = names.split(" ")
3317 return [Real(name, ctx) for name in names]
3318
3319
3320def RealVector(prefix, sz, ctx=None):
3321 """Return a list of real constants of size `sz`.
3322
3323 >>> X = RealVector('x', 3)
3324 >>> X
3325 [x__0, x__1, x__2]
3326 >>> Sum(X)
3327 x__0 + x__1 + x__2
3328 >>> Sum(X).sort()
3329 Real
3330 """
3331 ctx = _get_ctx(ctx)
3332 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3333
3334
3335def FreshReal(prefix="b", ctx=None):
3336 """Return a fresh real constant in the given context using the given prefix.
3337
3338 >>> x = FreshReal()
3339 >>> y = FreshReal()
3340 >>> eq(x, y)
3341 False
3342 >>> x.sort()
3343 Real
3344 """
3345 ctx = _get_ctx(ctx)
3346 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3347
3348
3349def ToReal(a):
3350 """ Return the Z3 expression ToReal(a).
3351
3352 >>> x = Int('x')
3353 >>> x.sort()
3354 Int
3355 >>> n = ToReal(x)
3356 >>> n
3357 ToReal(x)
3358 >>> n.sort()
3359 Real
3360 """
3361 if z3_debug():
3362 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3363 ctx = a.ctx
3364 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3365
3366
3367def ToInt(a):
3368 """ Return the Z3 expression ToInt(a).
3369
3370 >>> x = Real('x')
3371 >>> x.sort()
3372 Real
3373 >>> n = ToInt(x)
3374 >>> n
3375 ToInt(x)
3376 >>> n.sort()
3377 Int
3378 """
3379 if z3_debug():
3380 _z3_assert(a.is_real(), "Z3 real expression expected.")
3381 ctx = a.ctx
3382 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3383
3384
3385def IsInt(a):
3386 """ Return the Z3 predicate IsInt(a).
3387
3388 >>> x = Real('x')
3389 >>> IsInt(x + "1/2")
3390 IsInt(x + 1/2)
3391 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3392 [x = 1/2]
3393 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3394 no solution
3395 """
3396 if z3_debug():
3397 _z3_assert(a.is_real(), "Z3 real expression expected.")
3398 ctx = a.ctx
3399 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3400
3401
3402def Sqrt(a, ctx=None):
3403 """ Return a Z3 expression which represents the square root of a.
3404
3405 >>> x = Real('x')
3406 >>> Sqrt(x)
3407 x**(1/2)
3408 """
3409 if not is_expr(a):
3410 ctx = _get_ctx(ctx)
3411 a = RealVal(a, ctx)
3412 return a ** "1/2"
3413
3414
3415def Cbrt(a, ctx=None):
3416 """ Return a Z3 expression which represents the cubic root of a.
3417
3418 >>> x = Real('x')
3419 >>> Cbrt(x)
3420 x**(1/3)
3421 """
3422 if not is_expr(a):
3423 ctx = _get_ctx(ctx)
3424 a = RealVal(a, ctx)
3425 return a ** "1/3"
3426
3427
3432
3433
3435 """Bit-vector sort."""
3436
3437 def size(self):
3438 """Return the size (number of bits) of the bit-vector sort `self`.
3439
3440 >>> b = BitVecSort(32)
3441 >>> b.size()
3442 32
3443 """
3444 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3445
3446 def subsort(self, other):
3447 return is_bv_sort(other) and self.size() < other.size()
3448
3449 def cast(self, val):
3450 """Try to cast `val` as a Bit-Vector.
3451
3452 >>> b = BitVecSort(32)
3453 >>> b.cast(10)
3454 10
3455 >>> b.cast(10).sexpr()
3456 '#x0000000a'
3457 """
3458 if is_expr(val):
3459 if z3_debug():
3460 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
3461 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3462 return val
3463 else:
3464 return BitVecVal(val, self)
3465
3466
3468 """Return True if `s` is a Z3 bit-vector sort.
3469
3470 >>> is_bv_sort(BitVecSort(32))
3471 True
3472 >>> is_bv_sort(IntSort())
3473 False
3474 """
3475 return isinstance(s, BitVecSortRef)
3476
3477
3479 """Bit-vector expressions."""
3480
3481 def sort(self):
3482 """Return the sort of the bit-vector expression `self`.
3483
3484 >>> x = BitVec('x', 32)
3485 >>> x.sort()
3486 BitVec(32)
3487 >>> x.sort() == BitVecSort(32)
3488 True
3489 """
3490 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3491
3492 def size(self):
3493 """Return the number of bits of the bit-vector expression `self`.
3494
3495 >>> x = BitVec('x', 32)
3496 >>> (x + 1).size()
3497 32
3498 >>> Concat(x, x).size()
3499 64
3500 """
3501 return self.sortsort().size()
3502
3503 def __add__(self, other):
3504 """Create the Z3 expression `self + other`.
3505
3506 >>> x = BitVec('x', 32)
3507 >>> y = BitVec('y', 32)
3508 >>> x + y
3509 x + y
3510 >>> (x + y).sort()
3511 BitVec(32)
3512 """
3513 a, b = _coerce_exprs(self, other)
3514 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3515
3516 def __radd__(self, other):
3517 """Create the Z3 expression `other + self`.
3518
3519 >>> x = BitVec('x', 32)
3520 >>> 10 + x
3521 10 + x
3522 """
3523 a, b = _coerce_exprs(self, other)
3524 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3525
3526 def __mul__(self, other):
3527 """Create the Z3 expression `self * other`.
3528
3529 >>> x = BitVec('x', 32)
3530 >>> y = BitVec('y', 32)
3531 >>> x * y
3532 x*y
3533 >>> (x * y).sort()
3534 BitVec(32)
3535 """
3536 a, b = _coerce_exprs(self, other)
3537 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3538
3539 def __rmul__(self, other):
3540 """Create the Z3 expression `other * self`.
3541
3542 >>> x = BitVec('x', 32)
3543 >>> 10 * x
3544 10*x
3545 """
3546 a, b = _coerce_exprs(self, other)
3547 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3548
3549 def __sub__(self, other):
3550 """Create the Z3 expression `self - other`.
3551
3552 >>> x = BitVec('x', 32)
3553 >>> y = BitVec('y', 32)
3554 >>> x - y
3555 x - y
3556 >>> (x - y).sort()
3557 BitVec(32)
3558 """
3559 a, b = _coerce_exprs(self, other)
3560 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3561
3562 def __rsub__(self, other):
3563 """Create the Z3 expression `other - self`.
3564
3565 >>> x = BitVec('x', 32)
3566 >>> 10 - x
3567 10 - x
3568 """
3569 a, b = _coerce_exprs(self, other)
3570 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3571
3572 def __or__(self, other):
3573 """Create the Z3 expression bitwise-or `self | other`.
3574
3575 >>> x = BitVec('x', 32)
3576 >>> y = BitVec('y', 32)
3577 >>> x | y
3578 x | y
3579 >>> (x | y).sort()
3580 BitVec(32)
3581 """
3582 a, b = _coerce_exprs(self, other)
3583 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3584
3585 def __ror__(self, other):
3586 """Create the Z3 expression bitwise-or `other | self`.
3587
3588 >>> x = BitVec('x', 32)
3589 >>> 10 | x
3590 10 | x
3591 """
3592 a, b = _coerce_exprs(self, other)
3593 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3594
3595 def __and__(self, other):
3596 """Create the Z3 expression bitwise-and `self & other`.
3597
3598 >>> x = BitVec('x', 32)
3599 >>> y = BitVec('y', 32)
3600 >>> x & y
3601 x & y
3602 >>> (x & y).sort()
3603 BitVec(32)
3604 """
3605 a, b = _coerce_exprs(self, other)
3606 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3607
3608 def __rand__(self, other):
3609 """Create the Z3 expression bitwise-or `other & self`.
3610
3611 >>> x = BitVec('x', 32)
3612 >>> 10 & x
3613 10 & x
3614 """
3615 a, b = _coerce_exprs(self, other)
3616 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3617
3618 def __xor__(self, other):
3619 """Create the Z3 expression bitwise-xor `self ^ other`.
3620
3621 >>> x = BitVec('x', 32)
3622 >>> y = BitVec('y', 32)
3623 >>> x ^ y
3624 x ^ y
3625 >>> (x ^ y).sort()
3626 BitVec(32)
3627 """
3628 a, b = _coerce_exprs(self, other)
3629 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3630
3631 def __rxor__(self, other):
3632 """Create the Z3 expression bitwise-xor `other ^ self`.
3633
3634 >>> x = BitVec('x', 32)
3635 >>> 10 ^ x
3636 10 ^ x
3637 """
3638 a, b = _coerce_exprs(self, other)
3639 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3640
3641 def __pos__(self):
3642 """Return `self`.
3643
3644 >>> x = BitVec('x', 32)
3645 >>> +x
3646 x
3647 """
3648 return self
3649
3650 def __neg__(self):
3651 """Return an expression representing `-self`.
3652
3653 >>> x = BitVec('x', 32)
3654 >>> -x
3655 -x
3656 >>> simplify(-(-x))
3657 x
3658 """
3659 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3660
3661 def __invert__(self):
3662 """Create the Z3 expression bitwise-not `~self`.
3663
3664 >>> x = BitVec('x', 32)
3665 >>> ~x
3666 ~x
3667 >>> simplify(~(~x))
3668 x
3669 """
3670 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3671
3672 def __div__(self, other):
3673 """Create the Z3 expression (signed) division `self / other`.
3674
3675 Use the function UDiv() for unsigned division.
3676
3677 >>> x = BitVec('x', 32)
3678 >>> y = BitVec('y', 32)
3679 >>> x / y
3680 x/y
3681 >>> (x / y).sort()
3682 BitVec(32)
3683 >>> (x / y).sexpr()
3684 '(bvsdiv x y)'
3685 >>> UDiv(x, y).sexpr()
3686 '(bvudiv x y)'
3687 """
3688 a, b = _coerce_exprs(self, other)
3689 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3690
3691 def __truediv__(self, other):
3692 """Create the Z3 expression (signed) division `self / other`."""
3693 return self.__div__(other)
3694
3695 def __rdiv__(self, other):
3696 """Create the Z3 expression (signed) division `other / self`.
3697
3698 Use the function UDiv() for unsigned division.
3699
3700 >>> x = BitVec('x', 32)
3701 >>> 10 / x
3702 10/x
3703 >>> (10 / x).sexpr()
3704 '(bvsdiv #x0000000a x)'
3705 >>> UDiv(10, x).sexpr()
3706 '(bvudiv #x0000000a x)'
3707 """
3708 a, b = _coerce_exprs(self, other)
3709 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3710
3711 def __rtruediv__(self, other):
3712 """Create the Z3 expression (signed) division `other / self`."""
3713 return self.__rdiv__(other)
3714
3715 def __mod__(self, other):
3716 """Create the Z3 expression (signed) mod `self % other`.
3717
3718 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3719
3720 >>> x = BitVec('x', 32)
3721 >>> y = BitVec('y', 32)
3722 >>> x % y
3723 x%y
3724 >>> (x % y).sort()
3725 BitVec(32)
3726 >>> (x % y).sexpr()
3727 '(bvsmod x y)'
3728 >>> URem(x, y).sexpr()
3729 '(bvurem x y)'
3730 >>> SRem(x, y).sexpr()
3731 '(bvsrem x y)'
3732 """
3733 a, b = _coerce_exprs(self, other)
3734 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3735
3736 def __rmod__(self, other):
3737 """Create the Z3 expression (signed) mod `other % self`.
3738
3739 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3740
3741 >>> x = BitVec('x', 32)
3742 >>> 10 % x
3743 10%x
3744 >>> (10 % x).sexpr()
3745 '(bvsmod #x0000000a x)'
3746 >>> URem(10, x).sexpr()
3747 '(bvurem #x0000000a x)'
3748 >>> SRem(10, x).sexpr()
3749 '(bvsrem #x0000000a x)'
3750 """
3751 a, b = _coerce_exprs(self, other)
3752 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3753
3754 def __le__(self, other):
3755 """Create the Z3 expression (signed) `other <= self`.
3756
3757 Use the function ULE() for unsigned less than or equal to.
3758
3759 >>> x, y = BitVecs('x y', 32)
3760 >>> x <= y
3761 x <= y
3762 >>> (x <= y).sexpr()
3763 '(bvsle x y)'
3764 >>> ULE(x, y).sexpr()
3765 '(bvule x y)'
3766 """
3767 a, b = _coerce_exprs(self, other)
3768 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3769
3770 def __lt__(self, other):
3771 """Create the Z3 expression (signed) `other < self`.
3772
3773 Use the function ULT() for unsigned less than.
3774
3775 >>> x, y = BitVecs('x y', 32)
3776 >>> x < y
3777 x < y
3778 >>> (x < y).sexpr()
3779 '(bvslt x y)'
3780 >>> ULT(x, y).sexpr()
3781 '(bvult x y)'
3782 """
3783 a, b = _coerce_exprs(self, other)
3784 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3785
3786 def __gt__(self, other):
3787 """Create the Z3 expression (signed) `other > self`.
3788
3789 Use the function UGT() for unsigned greater than.
3790
3791 >>> x, y = BitVecs('x y', 32)
3792 >>> x > y
3793 x > y
3794 >>> (x > y).sexpr()
3795 '(bvsgt x y)'
3796 >>> UGT(x, y).sexpr()
3797 '(bvugt x y)'
3798 """
3799 a, b = _coerce_exprs(self, other)
3800 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3801
3802 def __ge__(self, other):
3803 """Create the Z3 expression (signed) `other >= self`.
3804
3805 Use the function UGE() for unsigned greater than or equal to.
3806
3807 >>> x, y = BitVecs('x y', 32)
3808 >>> x >= y
3809 x >= y
3810 >>> (x >= y).sexpr()
3811 '(bvsge x y)'
3812 >>> UGE(x, y).sexpr()
3813 '(bvuge x y)'
3814 """
3815 a, b = _coerce_exprs(self, other)
3816 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3817
3818 def __rshift__(self, other):
3819 """Create the Z3 expression (arithmetical) right shift `self >> other`
3820
3821 Use the function LShR() for the right logical shift
3822
3823 >>> x, y = BitVecs('x y', 32)
3824 >>> x >> y
3825 x >> y
3826 >>> (x >> y).sexpr()
3827 '(bvashr x y)'
3828 >>> LShR(x, y).sexpr()
3829 '(bvlshr x y)'
3830 >>> BitVecVal(4, 3)
3831 4
3832 >>> BitVecVal(4, 3).as_signed_long()
3833 -4
3834 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3835 -2
3836 >>> simplify(BitVecVal(4, 3) >> 1)
3837 6
3838 >>> simplify(LShR(BitVecVal(4, 3), 1))
3839 2
3840 >>> simplify(BitVecVal(2, 3) >> 1)
3841 1
3842 >>> simplify(LShR(BitVecVal(2, 3), 1))
3843 1
3844 """
3845 a, b = _coerce_exprs(self, other)
3846 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3847
3848 def __lshift__(self, other):
3849 """Create the Z3 expression left shift `self << other`
3850
3851 >>> x, y = BitVecs('x y', 32)
3852 >>> x << y
3853 x << y
3854 >>> (x << y).sexpr()
3855 '(bvshl x y)'
3856 >>> simplify(BitVecVal(2, 3) << 1)
3857 4
3858 """
3859 a, b = _coerce_exprs(self, other)
3860 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3861
3862 def __rrshift__(self, other):
3863 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3864
3865 Use the function LShR() for the right logical shift
3866
3867 >>> x = BitVec('x', 32)
3868 >>> 10 >> x
3869 10 >> x
3870 >>> (10 >> x).sexpr()
3871 '(bvashr #x0000000a x)'
3872 """
3873 a, b = _coerce_exprs(self, other)
3874 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3875
3876 def __rlshift__(self, other):
3877 """Create the Z3 expression left shift `other << self`.
3878
3879 Use the function LShR() for the right logical shift
3880
3881 >>> x = BitVec('x', 32)
3882 >>> 10 << x
3883 10 << x
3884 >>> (10 << x).sexpr()
3885 '(bvshl #x0000000a x)'
3886 """
3887 a, b = _coerce_exprs(self, other)
3888 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3889
3890
3892 """Bit-vector values."""
3893
3894 def as_long(self):
3895 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3896
3897 >>> v = BitVecVal(0xbadc0de, 32)
3898 >>> v
3899 195936478
3900 >>> print("0x%.8x" % v.as_long())
3901 0x0badc0de
3902 """
3903 return int(self.as_string())
3904
3906 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3907 The most significant bit is assumed to be the sign.
3908
3909 >>> BitVecVal(4, 3).as_signed_long()
3910 -4
3911 >>> BitVecVal(7, 3).as_signed_long()
3912 -1
3913 >>> BitVecVal(3, 3).as_signed_long()
3914 3
3915 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3916 -1
3917 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3918 -1
3919 """
3920 sz = self.size()
3921 val = self.as_long()
3922 if val >= 2**(sz - 1):
3923 val = val - 2**sz
3924 if val < -2**(sz - 1):
3925 val = val + 2**sz
3926 return int(val)
3927
3928 def as_string(self):
3929 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3930
3933
3934
3935def is_bv(a):
3936 """Return `True` if `a` is a Z3 bit-vector expression.
3937
3938 >>> b = BitVec('b', 32)
3939 >>> is_bv(b)
3940 True
3941 >>> is_bv(b + 10)
3942 True
3943 >>> is_bv(Int('x'))
3944 False
3945 """
3946 return isinstance(a, BitVecRef)
3947
3948
3950 """Return `True` if `a` is a Z3 bit-vector numeral value.
3951
3952 >>> b = BitVec('b', 32)
3953 >>> is_bv_value(b)
3954 False
3955 >>> b = BitVecVal(10, 32)
3956 >>> b
3957 10
3958 >>> is_bv_value(b)
3959 True
3960 """
3961 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3962
3963
3964def BV2Int(a, is_signed=False):
3965 """Return the Z3 expression BV2Int(a).
3966
3967 >>> b = BitVec('b', 3)
3968 >>> BV2Int(b).sort()
3969 Int
3970 >>> x = Int('x')
3971 >>> x > BV2Int(b)
3972 x > BV2Int(b)
3973 >>> x > BV2Int(b, is_signed=False)
3974 x > BV2Int(b)
3975 >>> x > BV2Int(b, is_signed=True)
3976 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3977 >>> solve(x > BV2Int(b), b == 1, x < 3)
3978 [x = 2, b = 1]
3979 """
3980 if z3_debug():
3981 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
3982 ctx = a.ctx
3983 # investigate problem with bv2int
3984 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3985
3986
3987def Int2BV(a, num_bits):
3988 """Return the z3 expression Int2BV(a, num_bits).
3989 It is a bit-vector of width num_bits and represents the
3990 modulo of a by 2^num_bits
3991 """
3992 ctx = a.ctx
3993 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3994
3995
3996def BitVecSort(sz, ctx=None):
3997 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3998
3999 >>> Byte = BitVecSort(8)
4000 >>> Word = BitVecSort(16)
4001 >>> Byte
4002 BitVec(8)
4003 >>> x = Const('x', Byte)
4004 >>> eq(x, BitVec('x', 8))
4005 True
4006 """
4007 ctx = _get_ctx(ctx)
4008 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4009
4010
4011def BitVecVal(val, bv, ctx=None):
4012 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4013
4014 >>> v = BitVecVal(10, 32)
4015 >>> v
4016 10
4017 >>> print("0x%.8x" % v.as_long())
4018 0x0000000a
4019 """
4020 if is_bv_sort(bv):
4021 ctx = bv.ctx
4022 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4023 else:
4024 ctx = _get_ctx(ctx)
4025 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4026
4027
4028def BitVec(name, bv, ctx=None):
4029 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4030 If `ctx=None`, then the global context is used.
4031
4032 >>> x = BitVec('x', 16)
4033 >>> is_bv(x)
4034 True
4035 >>> x.size()
4036 16
4037 >>> x.sort()
4038 BitVec(16)
4039 >>> word = BitVecSort(16)
4040 >>> x2 = BitVec('x', word)
4041 >>> eq(x, x2)
4042 True
4043 """
4044 if isinstance(bv, BitVecSortRef):
4045 ctx = bv.ctx
4046 else:
4047 ctx = _get_ctx(ctx)
4048 bv = BitVecSort(bv, ctx)
4049 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4050
4051
4052def BitVecs(names, bv, ctx=None):
4053 """Return a tuple of bit-vector constants of size bv.
4054
4055 >>> x, y, z = BitVecs('x y z', 16)
4056 >>> x.size()
4057 16
4058 >>> x.sort()
4059 BitVec(16)
4060 >>> Sum(x, y, z)
4061 0 + x + y + z
4062 >>> Product(x, y, z)
4063 1*x*y*z
4064 >>> simplify(Product(x, y, z))
4065 x*y*z
4066 """
4067 ctx = _get_ctx(ctx)
4068 if isinstance(names, str):
4069 names = names.split(" ")
4070 return [BitVec(name, bv, ctx) for name in names]
4071
4072
4073def Concat(*args):
4074 """Create a Z3 bit-vector concatenation expression.
4075
4076 >>> v = BitVecVal(1, 4)
4077 >>> Concat(v, v+1, v)
4078 Concat(Concat(1, 1 + 1), 1)
4079 >>> simplify(Concat(v, v+1, v))
4080 289
4081 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4082 121
4083 """
4084 args = _get_args(args)
4085 sz = len(args)
4086 if z3_debug():
4087 _z3_assert(sz >= 2, "At least two arguments expected.")
4088
4089 ctx = None
4090 for a in args:
4091 if is_expr(a):
4092 ctx = a.ctx
4093 break
4094 if is_seq(args[0]) or isinstance(args[0], str):
4095 args = [_coerce_seq(s, ctx) for s in args]
4096 if z3_debug():
4097 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4098 v = (Ast * sz)()
4099 for i in range(sz):
4100 v[i] = args[i].as_ast()
4101 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4102
4103 if is_re(args[0]):
4104 if z3_debug():
4105 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4106 v = (Ast * sz)()
4107 for i in range(sz):
4108 v[i] = args[i].as_ast()
4109 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4110
4111 if z3_debug():
4112 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4113 r = args[0]
4114 for i in range(sz - 1):
4115 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4116 return r
4117
4118
4119def Extract(high, low, a):
4120 """Create a Z3 bit-vector extraction expression.
4121 Extract is overloaded to also work on sequence extraction.
4122 The functions SubString and SubSeq are redirected to Extract.
4123 For this case, the arguments are reinterpreted as:
4124 high - is a sequence (string)
4125 low - is an offset
4126 a - is the length to be extracted
4127
4128 >>> x = BitVec('x', 8)
4129 >>> Extract(6, 2, x)
4130 Extract(6, 2, x)
4131 >>> Extract(6, 2, x).sort()
4132 BitVec(5)
4133 >>> simplify(Extract(StringVal("abcd"),2,1))
4134 "c"
4135 """
4136 if isinstance(high, str):
4137 high = StringVal(high)
4138 if is_seq(high):
4139 s = high
4140 offset, length = _coerce_exprs(low, a, s.ctx)
4141 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4142 if z3_debug():
4143 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4144 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4145 "First and second arguments must be non negative integers")
4146 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4147 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4148
4149
4150def _check_bv_args(a, b):
4151 if z3_debug():
4152 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4153
4154
4155def ULE(a, b):
4156 """Create the Z3 expression (unsigned) `other <= self`.
4157
4158 Use the operator <= for signed less than or equal to.
4159
4160 >>> x, y = BitVecs('x y', 32)
4161 >>> ULE(x, y)
4162 ULE(x, y)
4163 >>> (x <= y).sexpr()
4164 '(bvsle x y)'
4165 >>> ULE(x, y).sexpr()
4166 '(bvule x y)'
4167 """
4168 _check_bv_args(a, b)
4169 a, b = _coerce_exprs(a, b)
4170 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4171
4172
4173def ULT(a, b):
4174 """Create the Z3 expression (unsigned) `other < self`.
4175
4176 Use the operator < for signed less than.
4177
4178 >>> x, y = BitVecs('x y', 32)
4179 >>> ULT(x, y)
4180 ULT(x, y)
4181 >>> (x < y).sexpr()
4182 '(bvslt x y)'
4183 >>> ULT(x, y).sexpr()
4184 '(bvult x y)'
4185 """
4186 _check_bv_args(a, b)
4187 a, b = _coerce_exprs(a, b)
4188 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4189
4190
4191def UGE(a, b):
4192 """Create the Z3 expression (unsigned) `other >= self`.
4193
4194 Use the operator >= for signed greater than or equal to.
4195
4196 >>> x, y = BitVecs('x y', 32)
4197 >>> UGE(x, y)
4198 UGE(x, y)
4199 >>> (x >= y).sexpr()
4200 '(bvsge x y)'
4201 >>> UGE(x, y).sexpr()
4202 '(bvuge x y)'
4203 """
4204 _check_bv_args(a, b)
4205 a, b = _coerce_exprs(a, b)
4206 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4207
4208
4209def UGT(a, b):
4210 """Create the Z3 expression (unsigned) `other > self`.
4211
4212 Use the operator > for signed greater than.
4213
4214 >>> x, y = BitVecs('x y', 32)
4215 >>> UGT(x, y)
4216 UGT(x, y)
4217 >>> (x > y).sexpr()
4218 '(bvsgt x y)'
4219 >>> UGT(x, y).sexpr()
4220 '(bvugt x y)'
4221 """
4222 _check_bv_args(a, b)
4223 a, b = _coerce_exprs(a, b)
4224 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4225
4226
4227def UDiv(a, b):
4228 """Create the Z3 expression (unsigned) division `self / other`.
4229
4230 Use the operator / for signed division.
4231
4232 >>> x = BitVec('x', 32)
4233 >>> y = BitVec('y', 32)
4234 >>> UDiv(x, y)
4235 UDiv(x, y)
4236 >>> UDiv(x, y).sort()
4237 BitVec(32)
4238 >>> (x / y).sexpr()
4239 '(bvsdiv x y)'
4240 >>> UDiv(x, y).sexpr()
4241 '(bvudiv x y)'
4242 """
4243 _check_bv_args(a, b)
4244 a, b = _coerce_exprs(a, b)
4245 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4246
4247
4248def URem(a, b):
4249 """Create the Z3 expression (unsigned) remainder `self % other`.
4250
4251 Use the operator % for signed modulus, and SRem() for signed remainder.
4252
4253 >>> x = BitVec('x', 32)
4254 >>> y = BitVec('y', 32)
4255 >>> URem(x, y)
4256 URem(x, y)
4257 >>> URem(x, y).sort()
4258 BitVec(32)
4259 >>> (x % y).sexpr()
4260 '(bvsmod x y)'
4261 >>> URem(x, y).sexpr()
4262 '(bvurem x y)'
4263 """
4264 _check_bv_args(a, b)
4265 a, b = _coerce_exprs(a, b)
4266 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4267
4268
4269def SRem(a, b):
4270 """Create the Z3 expression signed remainder.
4271
4272 Use the operator % for signed modulus, and URem() for unsigned remainder.
4273
4274 >>> x = BitVec('x', 32)
4275 >>> y = BitVec('y', 32)
4276 >>> SRem(x, y)
4277 SRem(x, y)
4278 >>> SRem(x, y).sort()
4279 BitVec(32)
4280 >>> (x % y).sexpr()
4281 '(bvsmod x y)'
4282 >>> SRem(x, y).sexpr()
4283 '(bvsrem x y)'
4284 """
4285 _check_bv_args(a, b)
4286 a, b = _coerce_exprs(a, b)
4287 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4288
4289
4290def LShR(a, b):
4291 """Create the Z3 expression logical right shift.
4292
4293 Use the operator >> for the arithmetical right shift.
4294
4295 >>> x, y = BitVecs('x y', 32)
4296 >>> LShR(x, y)
4297 LShR(x, y)
4298 >>> (x >> y).sexpr()
4299 '(bvashr x y)'
4300 >>> LShR(x, y).sexpr()
4301 '(bvlshr x y)'
4302 >>> BitVecVal(4, 3)
4303 4
4304 >>> BitVecVal(4, 3).as_signed_long()
4305 -4
4306 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4307 -2
4308 >>> simplify(BitVecVal(4, 3) >> 1)
4309 6
4310 >>> simplify(LShR(BitVecVal(4, 3), 1))
4311 2
4312 >>> simplify(BitVecVal(2, 3) >> 1)
4313 1
4314 >>> simplify(LShR(BitVecVal(2, 3), 1))
4315 1
4316 """
4317 _check_bv_args(a, b)
4318 a, b = _coerce_exprs(a, b)
4319 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4320
4321
4322def RotateLeft(a, b):
4323 """Return an expression representing `a` rotated to the left `b` times.
4324
4325 >>> a, b = BitVecs('a b', 16)
4326 >>> RotateLeft(a, b)
4327 RotateLeft(a, b)
4328 >>> simplify(RotateLeft(a, 0))
4329 a
4330 >>> simplify(RotateLeft(a, 16))
4331 a
4332 """
4333 _check_bv_args(a, b)
4334 a, b = _coerce_exprs(a, b)
4335 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4336
4337
4338def RotateRight(a, b):
4339 """Return an expression representing `a` rotated to the right `b` times.
4340
4341 >>> a, b = BitVecs('a b', 16)
4342 >>> RotateRight(a, b)
4343 RotateRight(a, b)
4344 >>> simplify(RotateRight(a, 0))
4345 a
4346 >>> simplify(RotateRight(a, 16))
4347 a
4348 """
4349 _check_bv_args(a, b)
4350 a, b = _coerce_exprs(a, b)
4351 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4352
4353
4354def SignExt(n, a):
4355 """Return a bit-vector expression with `n` extra sign-bits.
4356
4357 >>> x = BitVec('x', 16)
4358 >>> n = SignExt(8, x)
4359 >>> n.size()
4360 24
4361 >>> n
4362 SignExt(8, x)
4363 >>> n.sort()
4364 BitVec(24)
4365 >>> v0 = BitVecVal(2, 2)
4366 >>> v0
4367 2
4368 >>> v0.size()
4369 2
4370 >>> v = simplify(SignExt(6, v0))
4371 >>> v
4372 254
4373 >>> v.size()
4374 8
4375 >>> print("%.x" % v.as_long())
4376 fe
4377 """
4378 if z3_debug():
4379 _z3_assert(_is_int(n), "First argument must be an integer")
4380 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4381 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4382
4383
4384def ZeroExt(n, a):
4385 """Return a bit-vector expression with `n` extra zero-bits.
4386
4387 >>> x = BitVec('x', 16)
4388 >>> n = ZeroExt(8, x)
4389 >>> n.size()
4390 24
4391 >>> n
4392 ZeroExt(8, x)
4393 >>> n.sort()
4394 BitVec(24)
4395 >>> v0 = BitVecVal(2, 2)
4396 >>> v0
4397 2
4398 >>> v0.size()
4399 2
4400 >>> v = simplify(ZeroExt(6, v0))
4401 >>> v
4402 2
4403 >>> v.size()
4404 8
4405 """
4406 if z3_debug():
4407 _z3_assert(_is_int(n), "First argument must be an integer")
4408 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4409 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4410
4411
4413 """Return an expression representing `n` copies of `a`.
4414
4415 >>> x = BitVec('x', 8)
4416 >>> n = RepeatBitVec(4, x)
4417 >>> n
4418 RepeatBitVec(4, x)
4419 >>> n.size()
4420 32
4421 >>> v0 = BitVecVal(10, 4)
4422 >>> print("%.x" % v0.as_long())
4423 a
4424 >>> v = simplify(RepeatBitVec(4, v0))
4425 >>> v.size()
4426 16
4427 >>> print("%.x" % v.as_long())
4428 aaaa
4429 """
4430 if z3_debug():
4431 _z3_assert(_is_int(n), "First argument must be an integer")
4432 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4433 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4434
4435
4437 """Return the reduction-and expression of `a`."""
4438 if z3_debug():
4439 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4440 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4441
4442
4443def BVRedOr(a):
4444 """Return the reduction-or expression of `a`."""
4445 if z3_debug():
4446 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4447 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4448
4449
4450def BVAddNoOverflow(a, b, signed):
4451 """A predicate the determines that bit-vector addition does not overflow"""
4452 _check_bv_args(a, b)
4453 a, b = _coerce_exprs(a, b)
4454 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4455
4456
4458 """A predicate the determines that signed bit-vector addition does not underflow"""
4459 _check_bv_args(a, b)
4460 a, b = _coerce_exprs(a, b)
4461 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4462
4463
4465 """A predicate the determines that bit-vector subtraction does not overflow"""
4466 _check_bv_args(a, b)
4467 a, b = _coerce_exprs(a, b)
4468 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4469
4470
4471def BVSubNoUnderflow(a, b, signed):
4472 """A predicate the determines that bit-vector subtraction does not underflow"""
4473 _check_bv_args(a, b)
4474 a, b = _coerce_exprs(a, b)
4475 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4476
4477
4479 """A predicate the determines that bit-vector signed division does not overflow"""
4480 _check_bv_args(a, b)
4481 a, b = _coerce_exprs(a, b)
4482 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4483
4484
4486 """A predicate the determines that bit-vector unary negation does not overflow"""
4487 if z3_debug():
4488 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4489 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4490
4491
4492def BVMulNoOverflow(a, b, signed):
4493 """A predicate the determines that bit-vector multiplication does not overflow"""
4494 _check_bv_args(a, b)
4495 a, b = _coerce_exprs(a, b)
4496 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4497
4498
4500 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4501 _check_bv_args(a, b)
4502 a, b = _coerce_exprs(a, b)
4503 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4504
4505
4506
4511
4513 """Array sorts."""
4514
4515 def domain(self):
4516 """Return the domain of the array sort `self`.
4517
4518 >>> A = ArraySort(IntSort(), BoolSort())
4519 >>> A.domain()
4520 Int
4521 """
4522 return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4523
4524 def domain_n(self, i):
4525 """Return the domain of the array sort `self`.
4526 """
4527 return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx)
4528
4529 def range(self):
4530 """Return the range of the array sort `self`.
4531
4532 >>> A = ArraySort(IntSort(), BoolSort())
4533 >>> A.range()
4534 Bool
4535 """
4536 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4537
4538
4540 """Array expressions. """
4541
4542 def sort(self):
4543 """Return the array sort of the array expression `self`.
4544
4545 >>> a = Array('a', IntSort(), BoolSort())
4546 >>> a.sort()
4547 Array(Int, Bool)
4548 """
4549 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4550
4551 def domain(self):
4552 """Shorthand for `self.sort().domain()`.
4553
4554 >>> a = Array('a', IntSort(), BoolSort())
4555 >>> a.domain()
4556 Int
4557 """
4558 return self.sortsort().domain()
4559
4560 def domain_n(self, i):
4561 """Shorthand for self.sort().domain_n(i)`."""
4562 return self.sortsort().domain_n(i)
4563
4564 def range(self):
4565 """Shorthand for `self.sort().range()`.
4566
4567 >>> a = Array('a', IntSort(), BoolSort())
4568 >>> a.range()
4569 Bool
4570 """
4571 return self.sortsort().range()
4572
4573 def __getitem__(self, arg):
4574 """Return the Z3 expression `self[arg]`.
4575
4576 >>> a = Array('a', IntSort(), BoolSort())
4577 >>> i = Int('i')
4578 >>> a[i]
4579 a[i]
4580 >>> a[i].sexpr()
4581 '(select a i)'
4582 """
4583 return _array_select(self, arg)
4584
4585 def default(self):
4586 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4587
4588
4589def _array_select(ar, arg):
4590 if isinstance(arg, tuple):
4591 args = [ar.domain_n(i).cast(arg[i]) for i in range(len(arg))]
4592 _args, sz = _to_ast_array(args)
4593 return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4594 arg = ar.domain().cast(arg)
4595 return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4596
4597
4599 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4600
4601
4603 """Return `True` if `a` is a Z3 array expression.
4604
4605 >>> a = Array('a', IntSort(), IntSort())
4606 >>> is_array(a)
4607 True
4608 >>> is_array(Store(a, 0, 1))
4609 True
4610 >>> is_array(a[0])
4611 False
4612 """
4613 return isinstance(a, ArrayRef)
4614
4615
4617 """Return `True` if `a` is a Z3 constant array.
4618
4619 >>> a = K(IntSort(), 10)
4620 >>> is_const_array(a)
4621 True
4622 >>> a = Array('a', IntSort(), IntSort())
4623 >>> is_const_array(a)
4624 False
4625 """
4626 return is_app_of(a, Z3_OP_CONST_ARRAY)
4627
4628
4629def is_K(a):
4630 """Return `True` if `a` is a Z3 constant array.
4631
4632 >>> a = K(IntSort(), 10)
4633 >>> is_K(a)
4634 True
4635 >>> a = Array('a', IntSort(), IntSort())
4636 >>> is_K(a)
4637 False
4638 """
4639 return is_app_of(a, Z3_OP_CONST_ARRAY)
4640
4641
4642def is_map(a):
4643 """Return `True` if `a` is a Z3 map array expression.
4644
4645 >>> f = Function('f', IntSort(), IntSort())
4646 >>> b = Array('b', IntSort(), IntSort())
4647 >>> a = Map(f, b)
4648 >>> a
4649 Map(f, b)
4650 >>> is_map(a)
4651 True
4652 >>> is_map(b)
4653 False
4654 """
4655 return is_app_of(a, Z3_OP_ARRAY_MAP)
4656
4657
4659 """Return `True` if `a` is a Z3 default array expression.
4660 >>> d = Default(K(IntSort(), 10))
4661 >>> is_default(d)
4662 True
4663 """
4664 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4665
4666
4668 """Return the function declaration associated with a Z3 map array expression.
4669
4670 >>> f = Function('f', IntSort(), IntSort())
4671 >>> b = Array('b', IntSort(), IntSort())
4672 >>> a = Map(f, b)
4673 >>> eq(f, get_map_func(a))
4674 True
4675 >>> get_map_func(a)
4676 f
4677 >>> get_map_func(a)(0)
4678 f(0)
4679 """
4680 if z3_debug():
4681 _z3_assert(is_map(a), "Z3 array map expression expected.")
4682 return FuncDeclRef(
4684 a.ctx_ref(),
4685 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4686 ),
4687 ctx=a.ctx,
4688 )
4689
4690
4691def ArraySort(*sig):
4692 """Return the Z3 array sort with the given domain and range sorts.
4693
4694 >>> A = ArraySort(IntSort(), BoolSort())
4695 >>> A
4696 Array(Int, Bool)
4697 >>> A.domain()
4698 Int
4699 >>> A.range()
4700 Bool
4701 >>> AA = ArraySort(IntSort(), A)
4702 >>> AA
4703 Array(Int, Array(Int, Bool))
4704 """
4705 sig = _get_args(sig)
4706 if z3_debug():
4707 _z3_assert(len(sig) > 1, "At least two arguments expected")
4708 arity = len(sig) - 1
4709 r = sig[arity]
4710 d = sig[0]
4711 if z3_debug():
4712 for s in sig:
4713 _z3_assert(is_sort(s), "Z3 sort expected")
4714 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4715 ctx = d.ctx
4716 if len(sig) == 2:
4717 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4718 dom = (Sort * arity)()
4719 for i in range(arity):
4720 dom[i] = sig[i].ast
4721 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4722
4723
4724def Array(name, *sorts):
4725 """Return an array constant named `name` with the given domain and range sorts.
4726
4727 >>> a = Array('a', IntSort(), IntSort())
4728 >>> a.sort()
4729 Array(Int, Int)
4730 >>> a[0]
4731 a[0]
4732 """
4733 s = ArraySort(sorts)
4734 ctx = s.ctx
4735 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4736
4737
4738def Update(a, *args):
4739 """Return a Z3 store array expression.
4740
4741 >>> a = Array('a', IntSort(), IntSort())
4742 >>> i, v = Ints('i v')
4743 >>> s = Update(a, i, v)
4744 >>> s.sort()
4745 Array(Int, Int)
4746 >>> prove(s[i] == v)
4747 proved
4748 >>> j = Int('j')
4749 >>> prove(Implies(i != j, s[j] == a[j]))
4750 proved
4751 """
4752 if z3_debug():
4753 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4754 args = _get_args(args)
4755 ctx = a.ctx
4756 if len(args) <= 1:
4757 raise Z3Exception("array update requires index and value arguments")
4758 if len(args) == 2:
4759 i = args[0]
4760 v = args[1]
4761 i = a.sort().domain().cast(i)
4762 v = a.sort().range().cast(v)
4763 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4764 v = a.sort().range().cast(args[-1])
4765 idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
4766 _args, sz = _to_ast_array(idxs)
4767 return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
4768
4769
4770def Default(a):
4771 """ Return a default value for array expression.
4772 >>> b = K(IntSort(), 1)
4773 >>> prove(Default(b) == 1)
4774 proved
4775 """
4776 if z3_debug():
4777 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4778 return a.default()
4779
4780
4781def Store(a, *args):
4782 """Return a Z3 store array expression.
4783
4784 >>> a = Array('a', IntSort(), IntSort())
4785 >>> i, v = Ints('i v')
4786 >>> s = Store(a, i, v)
4787 >>> s.sort()
4788 Array(Int, Int)
4789 >>> prove(s[i] == v)
4790 proved
4791 >>> j = Int('j')
4792 >>> prove(Implies(i != j, s[j] == a[j]))
4793 proved
4794 """
4795 return Update(a, args)
4796
4797
4798def Select(a, *args):
4799 """Return a Z3 select array expression.
4800
4801 >>> a = Array('a', IntSort(), IntSort())
4802 >>> i = Int('i')
4803 >>> Select(a, i)
4804 a[i]
4805 >>> eq(Select(a, i), a[i])
4806 True
4807 """
4808 args = _get_args(args)
4809 if z3_debug():
4810 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4811 return a[args]
4812
4813
4814def Map(f, *args):
4815 """Return a Z3 map array expression.
4816
4817 >>> f = Function('f', IntSort(), IntSort(), IntSort())
4818 >>> a1 = Array('a1', IntSort(), IntSort())
4819 >>> a2 = Array('a2', IntSort(), IntSort())
4820 >>> b = Map(f, a1, a2)
4821 >>> b
4822 Map(f, a1, a2)
4823 >>> prove(b[0] == f(a1[0], a2[0]))
4824 proved
4825 """
4826 args = _get_args(args)
4827 if z3_debug():
4828 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4829 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4830 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4831 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4832 _args, sz = _to_ast_array(args)
4833 ctx = f.ctx
4834 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4835
4836
4837def K(dom, v):
4838 """Return a Z3 constant array expression.
4839
4840 >>> a = K(IntSort(), 10)
4841 >>> a
4842 K(Int, 10)
4843 >>> a.sort()
4844 Array(Int, Int)
4845 >>> i = Int('i')
4846 >>> a[i]
4847 K(Int, 10)[i]
4848 >>> simplify(a[i])
4849 10
4850 """
4851 if z3_debug():
4852 _z3_assert(is_sort(dom), "Z3 sort expected")
4853 ctx = dom.ctx
4854 if not is_expr(v):
4855 v = _py2expr(v, ctx)
4856 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4857
4858
4859def Ext(a, b):
4860 """Return extensionality index for one-dimensional arrays.
4861 >> a, b = Consts('a b', SetSort(IntSort()))
4862 >> Ext(a, b)
4863 Ext(a, b)
4864 """
4865 ctx = a.ctx
4866 if z3_debug():
4867 _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
4868 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4869
4870
4871def SetHasSize(a, k):
4872 ctx = a.ctx
4873 k = _py2expr(k, ctx)
4874 return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4875
4876
4878 """Return `True` if `a` is a Z3 array select application.
4879
4880 >>> a = Array('a', IntSort(), IntSort())
4881 >>> is_select(a)
4882 False
4883 >>> i = Int('i')
4884 >>> is_select(a[i])
4885 True
4886 """
4887 return is_app_of(a, Z3_OP_SELECT)
4888
4889
4891 """Return `True` if `a` is a Z3 array store application.
4892
4893 >>> a = Array('a', IntSort(), IntSort())
4894 >>> is_store(a)
4895 False
4896 >>> is_store(Store(a, 0, 1))
4897 True
4898 """
4899 return is_app_of(a, Z3_OP_STORE)
4900
4901
4906
4907
4908def SetSort(s):
4909 """ Create a set sort over element sort s"""
4910 return ArraySort(s, BoolSort())
4911
4912
4914 """Create the empty set
4915 >>> EmptySet(IntSort())
4916 K(Int, False)
4917 """
4918 ctx = s.ctx
4919 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4920
4921
4922def FullSet(s):
4923 """Create the full set
4924 >>> FullSet(IntSort())
4925 K(Int, True)
4926 """
4927 ctx = s.ctx
4928 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4929
4930
4931def SetUnion(*args):
4932 """ Take the union of sets
4933 >>> a = Const('a', SetSort(IntSort()))
4934 >>> b = Const('b', SetSort(IntSort()))
4935 >>> SetUnion(a, b)
4936 union(a, b)
4937 """
4938 args = _get_args(args)
4939 ctx = _ctx_from_ast_arg_list(args)
4940 _args, sz = _to_ast_array(args)
4941 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4942
4943
4944def SetIntersect(*args):
4945 """ Take the union of sets
4946 >>> a = Const('a', SetSort(IntSort()))
4947 >>> b = Const('b', SetSort(IntSort()))
4948 >>> SetIntersect(a, b)
4949 intersection(a, b)
4950 """
4951 args = _get_args(args)
4952 ctx = _ctx_from_ast_arg_list(args)
4953 _args, sz = _to_ast_array(args)
4954 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4955
4956
4957def SetAdd(s, e):
4958 """ Add element e to set s
4959 >>> a = Const('a', SetSort(IntSort()))
4960 >>> SetAdd(a, 1)
4961 Store(a, 1, True)
4962 """
4963 ctx = _ctx_from_ast_arg_list([s, e])
4964 e = _py2expr(e, ctx)
4965 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4966
4967
4968def SetDel(s, e):
4969 """ Remove element e to set s
4970 >>> a = Const('a', SetSort(IntSort()))
4971 >>> SetDel(a, 1)
4972 Store(a, 1, False)
4973 """
4974 ctx = _ctx_from_ast_arg_list([s, e])
4975 e = _py2expr(e, ctx)
4976 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4977
4978
4980 """ The complement of set s
4981 >>> a = Const('a', SetSort(IntSort()))
4982 >>> SetComplement(a)
4983 complement(a)
4984 """
4985 ctx = s.ctx
4986 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4987
4988
4990 """ The set difference of a and b
4991 >>> a = Const('a', SetSort(IntSort()))
4992 >>> b = Const('b', SetSort(IntSort()))
4993 >>> SetDifference(a, b)
4994 setminus(a, b)
4995 """
4996 ctx = _ctx_from_ast_arg_list([a, b])
4997 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4998
4999
5000def IsMember(e, s):
5001 """ Check if e is a member of set s
5002 >>> a = Const('a', SetSort(IntSort()))
5003 >>> IsMember(1, a)
5004 a[1]
5005 """
5006 ctx = _ctx_from_ast_arg_list([s, e])
5007 e = _py2expr(e, ctx)
5008 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5009
5010
5011def IsSubset(a, b):
5012 """ Check if a is a subset of b
5013 >>> a = Const('a', SetSort(IntSort()))
5014 >>> b = Const('b', SetSort(IntSort()))
5015 >>> IsSubset(a, b)
5016 subset(a, b)
5017 """
5018 ctx = _ctx_from_ast_arg_list([a, b])
5019 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5020
5021
5022
5027
5028def _valid_accessor(acc):
5029 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5030 if not isinstance(acc, tuple):
5031 return False
5032 if len(acc) != 2:
5033 return False
5034 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5035
5036
5038 """Helper class for declaring Z3 datatypes.
5039
5040 >>> List = Datatype('List')
5041 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5042 >>> List.declare('nil')
5043 >>> List = List.create()
5044 >>> # List is now a Z3 declaration
5045 >>> List.nil
5046 nil
5047 >>> List.cons(10, List.nil)
5048 cons(10, nil)
5049 >>> List.cons(10, List.nil).sort()
5050 List
5051 >>> cons = List.cons
5052 >>> nil = List.nil
5053 >>> car = List.car
5054 >>> cdr = List.cdr
5055 >>> n = cons(1, cons(0, nil))
5056 >>> n
5057 cons(1, cons(0, nil))
5058 >>> simplify(cdr(n))
5059 cons(0, nil)
5060 >>> simplify(car(n))
5061 1
5062 """
5063
5064 def __init__(self, name, ctx=None):
5065 self.ctx = _get_ctx(ctx)
5066 self.name = name
5068
5069 def __deepcopy__(self, memo={}):
5070 r = Datatype(self.name, self.ctx)
5071 r.constructors = copy.deepcopy(self.constructors)
5072 return r
5073
5074 def declare_core(self, name, rec_name, *args):
5075 if z3_debug():
5076 _z3_assert(isinstance(name, str), "String expected")
5077 _z3_assert(isinstance(rec_name, str), "String expected")
5078 _z3_assert(
5079 all([_valid_accessor(a) for a in args]),
5080 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5081 )
5082 self.constructors.append((name, rec_name, args))
5083
5084 def declare(self, name, *args):
5085 """Declare constructor named `name` with the given accessors `args`.
5086 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5087 or a reference to the datatypes being declared.
5088
5089 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5090 declares the constructor named `cons` that builds a new List using an integer and a List.
5091 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5092 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5093 we use the method create() to create the actual datatype in Z3.
5094
5095 >>> List = Datatype('List')
5096 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5097 >>> List.declare('nil')
5098 >>> List = List.create()
5099 """
5100 if z3_debug():
5101 _z3_assert(isinstance(name, str), "String expected")
5102 _z3_assert(name != "", "Constructor name cannot be empty")
5103 return self.declare_core(name, "is-" + name, *args)
5104
5105 def __repr__(self):
5106 return "Datatype(%s, %s)" % (self.name, self.constructors)
5107
5108 def create(self):
5109 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5110
5111 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5112
5113 >>> List = Datatype('List')
5114 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5115 >>> List.declare('nil')
5116 >>> List = List.create()
5117 >>> List.nil
5118 nil
5119 >>> List.cons(10, List.nil)
5120 cons(10, nil)
5121 """
5122 return CreateDatatypes([self])[0]
5123
5124
5126 """Auxiliary object used to create Z3 datatypes."""
5127
5128 def __init__(self, c, ctx):
5129 self.c = c
5130 self.ctx = ctx
5131
5132 def __del__(self):
5133 if self.ctx.ref() is not None and Z3_del_constructor is not None:
5134 Z3_del_constructor(self.ctx.ref(), self.c)
5135
5136
5138 """Auxiliary object used to create Z3 datatypes."""
5139
5140 def __init__(self, c, ctx):
5141 self.c = c
5142 self.ctx = ctx
5143
5144 def __del__(self):
5145 if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5146 Z3_del_constructor_list(self.ctx.ref(), self.c)
5147
5148
5150 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5151
5152 In the following example we define a Tree-List using two mutually recursive datatypes.
5153
5154 >>> TreeList = Datatype('TreeList')
5155 >>> Tree = Datatype('Tree')
5156 >>> # Tree has two constructors: leaf and node
5157 >>> Tree.declare('leaf', ('val', IntSort()))
5158 >>> # a node contains a list of trees
5159 >>> Tree.declare('node', ('children', TreeList))
5160 >>> TreeList.declare('nil')
5161 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5162 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5163 >>> Tree.val(Tree.leaf(10))
5164 val(leaf(10))
5165 >>> simplify(Tree.val(Tree.leaf(10)))
5166 10
5167 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5168 >>> n1
5169 node(cons(leaf(10), cons(leaf(20), nil)))
5170 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5171 >>> simplify(n2 == n1)
5172 False
5173 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5174 True
5175 """
5176 ds = _get_args(ds)
5177 if z3_debug():
5178 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5179 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5180 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5181 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5182 ctx = ds[0].ctx
5183 num = len(ds)
5184 names = (Symbol * num)()
5185 out = (Sort * num)()
5186 clists = (ConstructorList * num)()
5187 to_delete = []
5188 for i in range(num):
5189 d = ds[i]
5190 names[i] = to_symbol(d.name, ctx)
5191 num_cs = len(d.constructors)
5192 cs = (Constructor * num_cs)()
5193 for j in range(num_cs):
5194 c = d.constructors[j]
5195 cname = to_symbol(c[0], ctx)
5196 rname = to_symbol(c[1], ctx)
5197 fs = c[2]
5198 num_fs = len(fs)
5199 fnames = (Symbol * num_fs)()
5200 sorts = (Sort * num_fs)()
5201 refs = (ctypes.c_uint * num_fs)()
5202 for k in range(num_fs):
5203 fname = fs[k][0]
5204 ftype = fs[k][1]
5205 fnames[k] = to_symbol(fname, ctx)
5206 if isinstance(ftype, Datatype):
5207 if z3_debug():
5208 _z3_assert(
5209 ds.count(ftype) == 1,
5210 "One and only one occurrence of each datatype is expected",
5211 )
5212 sorts[k] = None
5213 refs[k] = ds.index(ftype)
5214 else:
5215 if z3_debug():
5216 _z3_assert(is_sort(ftype), "Z3 sort expected")
5217 sorts[k] = ftype.ast
5218 refs[k] = 0
5219 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5220 to_delete.append(ScopedConstructor(cs[j], ctx))
5221 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5222 to_delete.append(ScopedConstructorList(clists[i], ctx))
5223 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5224 result = []
5225 # Create a field for every constructor, recognizer and accessor
5226 for i in range(num):
5227 dref = DatatypeSortRef(out[i], ctx)
5228 num_cs = dref.num_constructors()
5229 for j in range(num_cs):
5230 cref = dref.constructor(j)
5231 cref_name = cref.name()
5232 cref_arity = cref.arity()
5233 if cref.arity() == 0:
5234 cref = cref()
5235 setattr(dref, cref_name, cref)
5236 rref = dref.recognizer(j)
5237 setattr(dref, "is_" + cref_name, rref)
5238 for k in range(cref_arity):
5239 aref = dref.accessor(j, k)
5240 setattr(dref, aref.name(), aref)
5241 result.append(dref)
5242 return tuple(result)
5243
5244
5246 """Datatype sorts."""
5247
5249 """Return the number of constructors in the given Z3 datatype.
5250
5251 >>> List = Datatype('List')
5252 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5253 >>> List.declare('nil')
5254 >>> List = List.create()
5255 >>> # List is now a Z3 declaration
5256 >>> List.num_constructors()
5257 2
5258 """
5259 return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
5260
5261 def constructor(self, idx):
5262 """Return a constructor of the datatype `self`.
5263
5264 >>> List = Datatype('List')
5265 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5266 >>> List.declare('nil')
5267 >>> List = List.create()
5268 >>> # List is now a Z3 declaration
5269 >>> List.num_constructors()
5270 2
5271 >>> List.constructor(0)
5272 cons
5273 >>> List.constructor(1)
5274 nil
5275 """
5276 if z3_debug():
5277 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5278 return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
5279
5280 def recognizer(self, idx):
5281 """In Z3, each constructor has an associated recognizer predicate.
5282
5283 If the constructor is named `name`, then the recognizer `is_name`.
5284
5285 >>> List = Datatype('List')
5286 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5287 >>> List.declare('nil')
5288 >>> List = List.create()
5289 >>> # List is now a Z3 declaration
5290 >>> List.num_constructors()
5291 2
5292 >>> List.recognizer(0)
5293 is(cons)
5294 >>> List.recognizer(1)
5295 is(nil)
5296 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5297 False
5298 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5299 True
5300 >>> l = Const('l', List)
5301 >>> simplify(List.is_cons(l))
5302 is(cons, l)
5303 """
5304 if z3_debug():
5305 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5306 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
5307
5308 def accessor(self, i, j):
5309 """In Z3, each constructor has 0 or more accessor.
5310 The number of accessors is equal to the arity of the constructor.
5311
5312 >>> List = Datatype('List')
5313 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5314 >>> List.declare('nil')
5315 >>> List = List.create()
5316 >>> List.num_constructors()
5317 2
5318 >>> List.constructor(0)
5319 cons
5320 >>> num_accs = List.constructor(0).arity()
5321 >>> num_accs
5322 2
5323 >>> List.accessor(0, 0)
5324 car
5325 >>> List.accessor(0, 1)
5326 cdr
5327 >>> List.constructor(1)
5328 nil
5329 >>> num_accs = List.constructor(1).arity()
5330 >>> num_accs
5331 0
5332 """
5333 if z3_debug():
5334 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5335 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5336 return FuncDeclRef(
5338 ctx=self.ctx,
5339 )
5340
5341
5343 """Datatype expressions."""
5344
5345 def sort(self):
5346 """Return the datatype sort of the datatype expression `self`."""
5347 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
5348
5349def DatatypeSort(name, ctx = None):
5350 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype"""
5351 ctx = _get_ctx(ctx)
5352 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
5353
5354def TupleSort(name, sorts, ctx=None):
5355 """Create a named tuple sort base on a set of underlying sorts
5356 Example:
5357 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5358 """
5359 tuple = Datatype(name, ctx)
5360 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5361 tuple.declare(name, *projects)
5362 tuple = tuple.create()
5363 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5364
5365
5366def DisjointSum(name, sorts, ctx=None):
5367 """Create a named tagged union sort base on a set of underlying sorts
5368 Example:
5369 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5370 """
5371 sum = Datatype(name, ctx)
5372 for i in range(len(sorts)):
5373 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5374 sum = sum.create()
5375 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5376
5377
5378def EnumSort(name, values, ctx=None):
5379 """Return a new enumeration sort named `name` containing the given values.
5380
5381 The result is a pair (sort, list of constants).
5382 Example:
5383 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5384 """
5385 if z3_debug():
5386 _z3_assert(isinstance(name, str), "Name must be a string")
5387 _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5388 _z3_assert(len(values) > 0, "At least one value expected")
5389 ctx = _get_ctx(ctx)
5390 num = len(values)
5391 _val_names = (Symbol * num)()
5392 for i in range(num):
5393 _val_names[i] = to_symbol(values[i])
5394 _values = (FuncDecl * num)()
5395 _testers = (FuncDecl * num)()
5396 name = to_symbol(name)
5397 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5398 V = []
5399 for i in range(num):
5400 V.append(FuncDeclRef(_values[i], ctx))
5401 V = [a() for a in V]
5402 return S, V
5403
5404
5409
5410
5412 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5413
5414 Consider using the function `args2params` to create instances of this object.
5415 """
5416
5417 def __init__(self, ctx=None, params=None):
5418 self.ctx = _get_ctx(ctx)
5419 if params is None:
5420 self.params = Z3_mk_params(self.ctx.ref())
5421 else:
5422 self.params = params
5423 Z3_params_inc_ref(self.ctx.ref(), self.params)
5424
5425 def __deepcopy__(self, memo={}):
5426 return ParamsRef(self.ctx, self.params)
5427
5428 def __del__(self):
5429 if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
5430 Z3_params_dec_ref(self.ctx.ref(), self.params)
5431
5432 def set(self, name, val):
5433 """Set parameter name with value val."""
5434 if z3_debug():
5435 _z3_assert(isinstance(name, str), "parameter name must be a string")
5436 name_sym = to_symbol(name, self.ctx)
5437 if isinstance(val, bool):
5438 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5439 elif _is_int(val):
5440 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5441 elif isinstance(val, float):
5442 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5443 elif isinstance(val, str):
5444 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5445 else:
5446 if z3_debug():
5447 _z3_assert(False, "invalid parameter value")
5448
5449 def __repr__(self):
5450 return Z3_params_to_string(self.ctx.ref(), self.params)
5451
5452 def validate(self, ds):
5453 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5454 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5455
5456
5457def args2params(arguments, keywords, ctx=None):
5458 """Convert python arguments into a Z3_params object.
5459 A ':' is added to the keywords, and '_' is replaced with '-'
5460
5461 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5462 (params model true relevancy 2 elim_and true)
5463 """
5464 if z3_debug():
5465 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5466 prev = None
5467 r = ParamsRef(ctx)
5468 for a in arguments:
5469 if prev is None:
5470 prev = a
5471 else:
5472 r.set(prev, a)
5473 prev = None
5474 for k in keywords:
5475 v = keywords[k]
5476 r.set(k, v)
5477 return r
5478
5479
5481 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5482 """
5483
5484 def __init__(self, descr, ctx=None):
5485 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5486 self.ctx = _get_ctx(ctx)
5487 self.descr = descr
5488 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5489
5490 def __deepcopy__(self, memo={}):
5491 return ParamsDescrsRef(self.descr, self.ctx)
5492
5493 def __del__(self):
5494 if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
5495 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5496
5497 def size(self):
5498 """Return the size of in the parameter description `self`.
5499 """
5500 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5501
5502 def __len__(self):
5503 """Return the size of in the parameter description `self`.
5504 """
5505 return self.size()
5506
5507 def get_name(self, i):
5508 """Return the i-th parameter name in the parameter description `self`.
5509 """
5510 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5511
5512 def get_kind(self, n):
5513 """Return the kind of the parameter named `n`.
5514 """
5515 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5516
5517 def get_documentation(self, n):
5518 """Return the documentation string of the parameter named `n`.
5519 """
5520 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5521
5522 def __getitem__(self, arg):
5523 if _is_int(arg):
5524 return self.get_name(arg)
5525 else:
5526 return self.get_kind(arg)
5527
5528 def __repr__(self):
5529 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5530
5531
5536
5537
5539 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5540
5541 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5542 A goal has a solution if one of its subgoals has a solution.
5543 A goal is unsatisfiable if all subgoals are unsatisfiable.
5544 """
5545
5546 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5547 if z3_debug():
5548 _z3_assert(goal is None or ctx is not None,
5549 "If goal is different from None, then ctx must be also different from None")
5550 self.ctx = _get_ctx(ctx)
5551 self.goal = goal
5552 if self.goal is None:
5553 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5554 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5555
5556 def __del__(self):
5557 if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
5558 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5559
5560 def depth(self):
5561 """Return the depth of the goal `self`.
5562 The depth corresponds to the number of tactics applied to `self`.
5563
5564 >>> x, y = Ints('x y')
5565 >>> g = Goal()
5566 >>> g.add(x == 0, y >= x + 1)
5567 >>> g.depth()
5568 0
5569 >>> r = Then('simplify', 'solve-eqs')(g)
5570 >>> # r has 1 subgoal
5571 >>> len(r)
5572 1
5573 >>> r[0].depth()
5574 2
5575 """
5576 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5577
5578 def inconsistent(self):
5579 """Return `True` if `self` contains the `False` constraints.
5580
5581 >>> x, y = Ints('x y')
5582 >>> g = Goal()
5583 >>> g.inconsistent()
5584 False
5585 >>> g.add(x == 0, x == 1)
5586 >>> g
5587 [x == 0, x == 1]
5588 >>> g.inconsistent()
5589 False
5590 >>> g2 = Tactic('propagate-values')(g)[0]
5591 >>> g2.inconsistent()
5592 True
5593 """
5594 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5595
5596 def prec(self):
5597 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5598
5599 >>> g = Goal()
5600 >>> g.prec() == Z3_GOAL_PRECISE
5601 True
5602 >>> x, y = Ints('x y')
5603 >>> g.add(x == y + 1)
5604 >>> g.prec() == Z3_GOAL_PRECISE
5605 True
5606 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5607 >>> g2 = t(g)[0]
5608 >>> g2
5609 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5610 >>> g2.prec() == Z3_GOAL_PRECISE
5611 False
5612 >>> g2.prec() == Z3_GOAL_UNDER
5613 True
5614 """
5615 return Z3_goal_precision(self.ctx.ref(), self.goal)
5616
5617 def precision(self):
5618 """Alias for `prec()`.
5619
5620 >>> g = Goal()
5621 >>> g.precision() == Z3_GOAL_PRECISE
5622 True
5623 """
5624 return self.prec()
5625
5626 def size(self):
5627 """Return the number of constraints in the goal `self`.
5628
5629 >>> g = Goal()
5630 >>> g.size()
5631 0
5632 >>> x, y = Ints('x y')
5633 >>> g.add(x == 0, y > x)
5634 >>> g.size()
5635 2
5636 """
5637 return int(Z3_goal_size(self.ctx.ref(), self.goal))
5638
5639 def __len__(self):
5640 """Return the number of constraints in the goal `self`.
5641
5642 >>> g = Goal()
5643 >>> len(g)
5644 0
5645 >>> x, y = Ints('x y')
5646 >>> g.add(x == 0, y > x)
5647 >>> len(g)
5648 2
5649 """
5650 return self.size()
5651
5652 def get(self, i):
5653 """Return a constraint in the goal `self`.
5654
5655 >>> g = Goal()
5656 >>> x, y = Ints('x y')
5657 >>> g.add(x == 0, y > x)
5658 >>> g.get(0)
5659 x == 0
5660 >>> g.get(1)
5661 y > x
5662 """
5663 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5664
5665 def __getitem__(self, arg):
5666 """Return a constraint in the goal `self`.
5667
5668 >>> g = Goal()
5669 >>> x, y = Ints('x y')
5670 >>> g.add(x == 0, y > x)
5671 >>> g[0]
5672 x == 0
5673 >>> g[1]
5674 y > x
5675 """
5676 if arg >= len(self):
5677 raise IndexError
5678 return self.get(arg)
5679
5680 def assert_exprs(self, *args):
5681 """Assert constraints into the goal.
5682
5683 >>> x = Int('x')
5684 >>> g = Goal()
5685 >>> g.assert_exprs(x > 0, x < 2)
5686 >>> g
5687 [x > 0, x < 2]
5688 """
5689 args = _get_args(args)
5690 s = BoolSort(self.ctx)
5691 for arg in args:
5692 arg = s.cast(arg)
5693 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5694
5695 def append(self, *args):
5696 """Add constraints.
5697
5698 >>> x = Int('x')
5699 >>> g = Goal()
5700 >>> g.append(x > 0, x < 2)
5701 >>> g
5702 [x > 0, x < 2]
5703 """
5704 self.assert_exprs(*args)
5705
5706 def insert(self, *args):
5707 """Add constraints.
5708
5709 >>> x = Int('x')
5710 >>> g = Goal()
5711 >>> g.insert(x > 0, x < 2)
5712 >>> g
5713 [x > 0, x < 2]
5714 """
5715 self.assert_exprs(*args)
5716
5717 def add(self, *args):
5718 """Add constraints.
5719
5720 >>> x = Int('x')
5721 >>> g = Goal()
5722 >>> g.add(x > 0, x < 2)
5723 >>> g
5724 [x > 0, x < 2]
5725 """
5726 self.assert_exprs(*args)
5727
5728 def convert_model(self, model):
5729 """Retrieve model from a satisfiable goal
5730 >>> a, b = Ints('a b')
5731 >>> g = Goal()
5732 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5733 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5734 >>> r = t(g)
5735 >>> r[0]
5736 [Or(b == 0, b == 1), Not(0 <= b)]
5737 >>> r[1]
5738 [Or(b == 0, b == 1), Not(1 <= b)]
5739 >>> # Remark: the subgoal r[0] is unsatisfiable
5740 >>> # Creating a solver for solving the second subgoal
5741 >>> s = Solver()
5742 >>> s.add(r[1])
5743 >>> s.check()
5744 sat
5745 >>> s.model()
5746 [b = 0]
5747 >>> # Model s.model() does not assign a value to `a`
5748 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5749 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5750 >>> r[1].convert_model(s.model())
5751 [b = 0, a = 1]
5752 """
5753 if z3_debug():
5754 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5755 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5756
5757 def __repr__(self):
5758 return obj_to_string(self)
5759
5760 def sexpr(self):
5761 """Return a textual representation of the s-expression representing the goal."""
5762 return Z3_goal_to_string(self.ctx.ref(), self.goal)
5763
5764 def dimacs(self, include_names=True):
5765 """Return a textual representation of the goal in DIMACS format."""
5766 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
5767
5768 def translate(self, target):
5769 """Copy goal `self` to context `target`.
5770
5771 >>> x = Int('x')
5772 >>> g = Goal()
5773 >>> g.add(x > 10)
5774 >>> g
5775 [x > 10]
5776 >>> c2 = Context()
5777 >>> g2 = g.translate(c2)
5778 >>> g2
5779 [x > 10]
5780 >>> g.ctx == main_ctx()
5781 True
5782 >>> g2.ctx == c2
5783 True
5784 >>> g2.ctx == main_ctx()
5785 False
5786 """
5787 if z3_debug():
5788 _z3_assert(isinstance(target, Context), "target must be a context")
5789 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5790
5791 def __copy__(self):
5792 return self.translate(self.ctx)
5793
5794 def __deepcopy__(self, memo={}):
5795 return self.translate(self.ctx)
5796
5797 def simplify(self, *arguments, **keywords):
5798 """Return a new simplified goal.
5799
5800 This method is essentially invoking the simplify tactic.
5801
5802 >>> g = Goal()
5803 >>> x = Int('x')
5804 >>> g.add(x + 1 >= 2)
5805 >>> g
5806 [x + 1 >= 2]
5807 >>> g2 = g.simplify()
5808 >>> g2
5809 [x >= 1]
5810 >>> # g was not modified
5811 >>> g
5812 [x + 1 >= 2]
5813 """
5814 t = Tactic("simplify")
5815 return t.apply(self, *arguments, **keywords)[0]
5816
5817 def as_expr(self):
5818 """Return goal `self` as a single Z3 expression.
5819
5820 >>> x = Int('x')
5821 >>> g = Goal()
5822 >>> g.as_expr()
5823 True
5824 >>> g.add(x > 1)
5825 >>> g.as_expr()
5826 x > 1
5827 >>> g.add(x < 10)
5828 >>> g.as_expr()
5829 And(x > 1, x < 10)
5830 """
5831 sz = len(self)
5832 if sz == 0:
5833 return BoolVal(True, self.ctx)
5834 elif sz == 1:
5835 return self.get(0)
5836 else:
5837 return And([self.get(i) for i in range(len(self))], self.ctx)
5838
5839
5844
5845
5847 """A collection (vector) of ASTs."""
5848
5849 def __init__(self, v=None, ctx=None):
5850 self.vector = None
5851 if v is None:
5852 self.ctx = _get_ctx(ctx)
5853 self.vector = Z3_mk_ast_vector(self.ctx.ref())
5854 else:
5855 self.vector = v
5856 assert ctx is not None
5857 self.ctx = ctx
5858 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5859
5860 def __del__(self):
5861 if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
5862 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5863
5864 def __len__(self):
5865 """Return the size of the vector `self`.
5866
5867 >>> A = AstVector()
5868 >>> len(A)
5869 0
5870 >>> A.push(Int('x'))
5871 >>> A.push(Int('x'))
5872 >>> len(A)
5873 2
5874 """
5875 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5876
5877 def __getitem__(self, i):
5878 """Return the AST at position `i`.
5879
5880 >>> A = AstVector()
5881 >>> A.push(Int('x') + 1)
5882 >>> A.push(Int('y'))
5883 >>> A[0]
5884 x + 1
5885 >>> A[1]
5886 y
5887 """
5888
5889 if isinstance(i, int):
5890 if i < 0:
5891 i += self.__len__()
5892
5893 if i >= self.__len__():
5894 raise IndexError
5895 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5896
5897 elif isinstance(i, slice):
5898 result = []
5899 for ii in range(*i.indices(self.__len__())):
5900 result.append(_to_ast_ref(
5901 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
5902 self.ctx,
5903 ))
5904 return result
5905
5906 def __setitem__(self, i, v):
5907 """Update AST at position `i`.
5908
5909 >>> A = AstVector()
5910 >>> A.push(Int('x') + 1)
5911 >>> A.push(Int('y'))
5912 >>> A[0]
5913 x + 1
5914 >>> A[0] = Int('x')
5915 >>> A[0]
5916 x
5917 """
5918 if i >= self.__len__():
5919 raise IndexError
5920 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5921
5922 def push(self, v):
5923 """Add `v` in the end of the vector.
5924
5925 >>> A = AstVector()
5926 >>> len(A)
5927 0
5928 >>> A.push(Int('x'))
5929 >>> len(A)
5930 1
5931 """
5932 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5933
5934 def resize(self, sz):
5935 """Resize the vector to `sz` elements.
5936
5937 >>> A = AstVector()
5938 >>> A.resize(10)
5939 >>> len(A)
5940 10
5941 >>> for i in range(10): A[i] = Int('x')
5942 >>> A[5]
5943 x
5944 """
5945 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5946
5947 def __contains__(self, item):
5948 """Return `True` if the vector contains `item`.
5949
5950 >>> x = Int('x')
5951 >>> A = AstVector()
5952 >>> x in A
5953 False
5954 >>> A.push(x)
5955 >>> x in A
5956 True
5957 >>> (x+1) in A
5958 False
5959 >>> A.push(x+1)
5960 >>> (x+1) in A
5961 True
5962 >>> A
5963 [x, x + 1]
5964 """
5965 for elem in self:
5966 if elem.eq(item):
5967 return True
5968 return False
5969
5970 def translate(self, other_ctx):
5971 """Copy vector `self` to context `other_ctx`.
5972
5973 >>> x = Int('x')
5974 >>> A = AstVector()
5975 >>> A.push(x)
5976 >>> c2 = Context()
5977 >>> B = A.translate(c2)
5978 >>> B
5979 [x]
5980 """
5981 return AstVector(
5982 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
5983 ctx=other_ctx,
5984 )
5985
5986 def __copy__(self):
5987 return self.translate(self.ctx)
5988
5989 def __deepcopy__(self, memo={}):
5990 return self.translate(self.ctx)
5991
5992 def __repr__(self):
5993 return obj_to_string(self)
5994
5995 def sexpr(self):
5996 """Return a textual representation of the s-expression representing the vector."""
5997 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5998
5999
6004
6005
6007 """A mapping from ASTs to ASTs."""
6008
6009 def __init__(self, m=None, ctx=None):
6010 self.map = None
6011 if m is None:
6012 self.ctx = _get_ctx(ctx)
6013 self.map = Z3_mk_ast_map(self.ctx.ref())
6014 else:
6015 self.map = m
6016 assert ctx is not None
6017 self.ctx = ctx
6018 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6019
6020 def __deepcopy__(self, memo={}):
6021 return AstMap(self.map, self.ctx)
6022
6023 def __del__(self):
6024 if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6025 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6026
6027 def __len__(self):
6028 """Return the size of the map.
6029
6030 >>> M = AstMap()
6031 >>> len(M)
6032 0
6033 >>> x = Int('x')
6034 >>> M[x] = IntVal(1)
6035 >>> len(M)
6036 1
6037 """
6038 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6039
6040 def __contains__(self, key):
6041 """Return `True` if the map contains key `key`.
6042
6043 >>> M = AstMap()
6044 >>> x = Int('x')
6045 >>> M[x] = x + 1
6046 >>> x in M
6047 True
6048 >>> x+1 in M
6049 False
6050 """
6051 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6052
6053 def __getitem__(self, key):
6054 """Retrieve the value associated with key `key`.
6055
6056 >>> M = AstMap()
6057 >>> x = Int('x')
6058 >>> M[x] = x + 1
6059 >>> M[x]
6060 x + 1
6061 """
6062 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6063
6064 def __setitem__(self, k, v):
6065 """Add/Update key `k` with value `v`.
6066
6067 >>> M = AstMap()
6068 >>> x = Int('x')
6069 >>> M[x] = x + 1
6070 >>> len(M)
6071 1
6072 >>> M[x]
6073 x + 1
6074 >>> M[x] = IntVal(1)
6075 >>> M[x]
6076 1
6077 """
6078 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6079
6080 def __repr__(self):
6081 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6082
6083 def erase(self, k):
6084 """Remove the entry associated with key `k`.
6085
6086 >>> M = AstMap()
6087 >>> x = Int('x')
6088 >>> M[x] = x + 1
6089 >>> len(M)
6090 1
6091 >>> M.erase(x)
6092 >>> len(M)
6093 0
6094 """
6095 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6096
6097 def reset(self):
6098 """Remove all entries from the map.
6099
6100 >>> M = AstMap()
6101 >>> x = Int('x')
6102 >>> M[x] = x + 1
6103 >>> M[x+x] = IntVal(1)
6104 >>> len(M)
6105 2
6106 >>> M.reset()
6107 >>> len(M)
6108 0
6109 """
6110 Z3_ast_map_reset(self.ctx.ref(), self.map)
6111
6112 def keys(self):
6113 """Return an AstVector containing all keys in the map.
6114
6115 >>> M = AstMap()
6116 >>> x = Int('x')
6117 >>> M[x] = x + 1
6118 >>> M[x+x] = IntVal(1)
6119 >>> M.keys()
6120 [x, x + x]
6121 """
6122 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6123
6124
6129
6130
6132 """Store the value of the interpretation of a function in a particular point."""
6133
6134 def __init__(self, entry, ctx):
6135 self.entry = entry
6136 self.ctx = ctx
6137 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6138
6139 def __deepcopy__(self, memo={}):
6140 return FuncEntry(self.entry, self.ctx)
6141
6142 def __del__(self):
6143 if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6144 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6145
6146 def num_args(self):
6147 """Return the number of arguments in the given entry.
6148
6149 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6150 >>> s = Solver()
6151 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6152 >>> s.check()
6153 sat
6154 >>> m = s.model()
6155 >>> f_i = m[f]
6156 >>> f_i.num_entries()
6157 1
6158 >>> e = f_i.entry(0)
6159 >>> e.num_args()
6160 2
6161 """
6162 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6163
6164 def arg_value(self, idx):
6165 """Return the value of argument `idx`.
6166
6167 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6168 >>> s = Solver()
6169 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6170 >>> s.check()
6171 sat
6172 >>> m = s.model()
6173 >>> f_i = m[f]
6174 >>> f_i.num_entries()
6175 1
6176 >>> e = f_i.entry(0)
6177 >>> e
6178 [1, 2, 20]
6179 >>> e.num_args()
6180 2
6181 >>> e.arg_value(0)
6182 1
6183 >>> e.arg_value(1)
6184 2
6185 >>> try:
6186 ... e.arg_value(2)
6187 ... except IndexError:
6188 ... print("index error")
6189 index error
6190 """
6191 if idx >= self.num_args():
6192 raise IndexError
6193 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6194
6195 def value(self):
6196 """Return the value of the function at point `self`.
6197
6198 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6199 >>> s = Solver()
6200 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6201 >>> s.check()
6202 sat
6203 >>> m = s.model()
6204 >>> f_i = m[f]
6205 >>> f_i.num_entries()
6206 1
6207 >>> e = f_i.entry(0)
6208 >>> e
6209 [1, 2, 20]
6210 >>> e.num_args()
6211 2
6212 >>> e.value()
6213 20
6214 """
6215 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6216
6217 def as_list(self):
6218 """Return entry `self` as a Python list.
6219 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6220 >>> s = Solver()
6221 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6222 >>> s.check()
6223 sat
6224 >>> m = s.model()
6225 >>> f_i = m[f]
6226 >>> f_i.num_entries()
6227 1
6228 >>> e = f_i.entry(0)
6229 >>> e.as_list()
6230 [1, 2, 20]
6231 """
6232 args = [self.arg_value(i) for i in range(self.num_args())]
6233 args.append(self.value())
6234 return args
6235
6236 def __repr__(self):
6237 return repr(self.as_list())
6238
6239
6241 """Stores the interpretation of a function in a Z3 model."""
6242
6243 def __init__(self, f, ctx):
6244 self.f = f
6245 self.ctx = ctx
6246 if self.f is not None:
6247 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6248
6249 def __del__(self):
6250 if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6251 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6252
6253 def else_value(self):
6254 """
6255 Return the `else` value for a function interpretation.
6256 Return None if Z3 did not specify the `else` value for
6257 this object.
6258
6259 >>> f = Function('f', IntSort(), IntSort())
6260 >>> s = Solver()
6261 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6262 >>> s.check()
6263 sat
6264 >>> m = s.model()
6265 >>> m[f]
6266 [2 -> 0, else -> 1]
6267 >>> m[f].else_value()
6268 1
6269 """
6270 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6271 if r:
6272 return _to_expr_ref(r, self.ctx)
6273 else:
6274 return None
6275
6276 def num_entries(self):
6277 """Return the number of entries/points in the function interpretation `self`.
6278
6279 >>> f = Function('f', IntSort(), IntSort())
6280 >>> s = Solver()
6281 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6282 >>> s.check()
6283 sat
6284 >>> m = s.model()
6285 >>> m[f]
6286 [2 -> 0, else -> 1]
6287 >>> m[f].num_entries()
6288 1
6289 """
6290 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6291
6292 def arity(self):
6293 """Return the number of arguments for each entry in the function interpretation `self`.
6294
6295 >>> f = Function('f', IntSort(), IntSort())
6296 >>> s = Solver()
6297 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6298 >>> s.check()
6299 sat
6300 >>> m = s.model()
6301 >>> m[f].arity()
6302 1
6303 """
6304 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6305
6306 def entry(self, idx):
6307 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6308
6309 >>> f = Function('f', IntSort(), IntSort())
6310 >>> s = Solver()
6311 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6312 >>> s.check()
6313 sat
6314 >>> m = s.model()
6315 >>> m[f]
6316 [2 -> 0, else -> 1]
6317 >>> m[f].num_entries()
6318 1
6319 >>> m[f].entry(0)
6320 [2, 0]
6321 """
6322 if idx >= self.num_entries():
6323 raise IndexError
6324 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6325
6326 def translate(self, other_ctx):
6327 """Copy model 'self' to context 'other_ctx'.
6328 """
6329 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6330
6331 def __copy__(self):
6332 return self.translate(self.ctx)
6333
6334 def __deepcopy__(self, memo={}):
6335 return self.translate(self.ctx)
6336
6337 def as_list(self):
6338 """Return the function interpretation as a Python list.
6339 >>> f = Function('f', IntSort(), IntSort())
6340 >>> s = Solver()
6341 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6342 >>> s.check()
6343 sat
6344 >>> m = s.model()
6345 >>> m[f]
6346 [2 -> 0, else -> 1]
6347 >>> m[f].as_list()
6348 [[2, 0], 1]
6349 """
6350 r = [self.entry(i).as_list() for i in range(self.num_entries())]
6351 r.append(self.else_value())
6352 return r
6353
6354 def __repr__(self):
6355 return obj_to_string(self)
6356
6357
6359 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6360
6361 def __init__(self, m, ctx):
6362 assert ctx is not None
6363 self.model = m
6364 self.ctx = ctx
6365 Z3_model_inc_ref(self.ctx.ref(), self.model)
6366
6367 def __del__(self):
6368 if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
6369 Z3_model_dec_ref(self.ctx.ref(), self.model)
6370
6371 def __repr__(self):
6372 return obj_to_string(self)
6373
6374 def sexpr(self):
6375 """Return a textual representation of the s-expression representing the model."""
6376 return Z3_model_to_string(self.ctx.ref(), self.model)
6377
6378 def eval(self, t, model_completion=False):
6379 """Evaluate the expression `t` in the model `self`.
6380 If `model_completion` is enabled, then a default interpretation is automatically added
6381 for symbols that do not have an interpretation in the model `self`.
6382
6383 >>> x = Int('x')
6384 >>> s = Solver()
6385 >>> s.add(x > 0, x < 2)
6386 >>> s.check()
6387 sat
6388 >>> m = s.model()
6389 >>> m.eval(x + 1)
6390 2
6391 >>> m.eval(x == 1)
6392 True
6393 >>> y = Int('y')
6394 >>> m.eval(y + x)
6395 1 + y
6396 >>> m.eval(y)
6397 y
6398 >>> m.eval(y, model_completion=True)
6399 0
6400 >>> # Now, m contains an interpretation for y
6401 >>> m.eval(y + x)
6402 1
6403 """
6404 r = (Ast * 1)()
6405 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6406 return _to_expr_ref(r[0], self.ctx)
6407 raise Z3Exception("failed to evaluate expression in the model")
6408
6409 def evaluate(self, t, model_completion=False):
6410 """Alias for `eval`.
6411
6412 >>> x = Int('x')
6413 >>> s = Solver()
6414 >>> s.add(x > 0, x < 2)
6415 >>> s.check()
6416 sat
6417 >>> m = s.model()
6418 >>> m.evaluate(x + 1)
6419 2
6420 >>> m.evaluate(x == 1)
6421 True
6422 >>> y = Int('y')
6423 >>> m.evaluate(y + x)
6424 1 + y
6425 >>> m.evaluate(y)
6426 y
6427 >>> m.evaluate(y, model_completion=True)
6428 0
6429 >>> # Now, m contains an interpretation for y
6430 >>> m.evaluate(y + x)
6431 1
6432 """
6433 return self.eval(t, model_completion)
6434
6435 def __len__(self):
6436 """Return the number of constant and function declarations in the model `self`.
6437
6438 >>> f = Function('f', IntSort(), IntSort())
6439 >>> x = Int('x')
6440 >>> s = Solver()
6441 >>> s.add(x > 0, f(x) != x)
6442 >>> s.check()
6443 sat
6444 >>> m = s.model()
6445 >>> len(m)
6446 2
6447 """
6448 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
6449 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6450 return num_consts + num_funcs
6451
6452 def get_interp(self, decl):
6453 """Return the interpretation for a given declaration or constant.
6454
6455 >>> f = Function('f', IntSort(), IntSort())
6456 >>> x = Int('x')
6457 >>> s = Solver()
6458 >>> s.add(x > 0, x < 2, f(x) == 0)
6459 >>> s.check()
6460 sat
6461 >>> m = s.model()
6462 >>> m[x]
6463 1
6464 >>> m[f]
6465 [else -> 0]
6466 """
6467 if z3_debug():
6468 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6469 if is_const(decl):
6470 decl = decl.decl()
6471 try:
6472 if decl.arity() == 0:
6473 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6474 if _r.value is None:
6475 return None
6476 r = _to_expr_ref(_r, self.ctx)
6477 if is_as_array(r):
6478 fi = self.get_interp(get_as_array_func(r))
6479 if fi is None:
6480 return fi
6481 e = fi.else_value()
6482 if e is None:
6483 return fi
6484 if fi.arity() != 1:
6485 return fi
6486 srt = decl.range()
6487 dom = srt.domain()
6488 e = K(dom, e)
6489 i = 0
6490 sz = fi.num_entries()
6491 n = fi.arity()
6492 while i < sz:
6493 fe = fi.entry(i)
6494 e = Store(e, fe.arg_value(0), fe.value())
6495 i += 1
6496 return e
6497 else:
6498 return r
6499 else:
6500 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6501 except Z3Exception:
6502 return None
6503
6504 def num_sorts(self):
6505 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6506
6507 >>> A = DeclareSort('A')
6508 >>> a, b = Consts('a b', A)
6509 >>> s = Solver()
6510 >>> s.add(a != b)
6511 >>> s.check()
6512 sat
6513 >>> m = s.model()
6514 >>> m.num_sorts()
6515 1
6516 """
6517 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6518
6519 def get_sort(self, idx):
6520 """Return the uninterpreted sort at position `idx` < self.num_sorts().
6521
6522 >>> A = DeclareSort('A')
6523 >>> B = DeclareSort('B')
6524 >>> a1, a2 = Consts('a1 a2', A)
6525 >>> b1, b2 = Consts('b1 b2', B)
6526 >>> s = Solver()
6527 >>> s.add(a1 != a2, b1 != b2)
6528 >>> s.check()
6529 sat
6530 >>> m = s.model()
6531 >>> m.num_sorts()
6532 2
6533 >>> m.get_sort(0)
6534 A
6535 >>> m.get_sort(1)
6536 B
6537 """
6538 if idx >= self.num_sorts():
6539 raise IndexError
6540 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6541
6542 def sorts(self):
6543 """Return all uninterpreted sorts that have an interpretation in the model `self`.
6544
6545 >>> A = DeclareSort('A')
6546 >>> B = DeclareSort('B')
6547 >>> a1, a2 = Consts('a1 a2', A)
6548 >>> b1, b2 = Consts('b1 b2', B)
6549 >>> s = Solver()
6550 >>> s.add(a1 != a2, b1 != b2)
6551 >>> s.check()
6552 sat
6553 >>> m = s.model()
6554 >>> m.sorts()
6555 [A, B]
6556 """
6557 return [self.get_sort(i) for i in range(self.num_sorts())]
6558
6559 def get_universe(self, s):
6560 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6561
6562 >>> A = DeclareSort('A')
6563 >>> a, b = Consts('a b', A)
6564 >>> s = Solver()
6565 >>> s.add(a != b)
6566 >>> s.check()
6567 sat
6568 >>> m = s.model()
6569 >>> m.get_universe(A)
6570 [A!val!1, A!val!0]
6571 """
6572 if z3_debug():
6573 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6574 try:
6575 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6576 except Z3Exception:
6577 return None
6578
6579 def __getitem__(self, idx):
6580 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
6581 If `idx` is a declaration, then the actual interpretation is returned.
6582
6583 The elements can be retrieved using position or the actual declaration.
6584
6585 >>> f = Function('f', IntSort(), IntSort())
6586 >>> x = Int('x')
6587 >>> s = Solver()
6588 >>> s.add(x > 0, x < 2, f(x) == 0)
6589 >>> s.check()
6590 sat
6591 >>> m = s.model()
6592 >>> len(m)
6593 2
6594 >>> m[0]
6595 x
6596 >>> m[1]
6597 f
6598 >>> m[x]
6599 1
6600 >>> m[f]
6601 [else -> 0]
6602 >>> for d in m: print("%s -> %s" % (d, m[d]))
6603 x -> 1
6604 f -> [else -> 0]
6605 """
6606 if _is_int(idx):
6607 if idx >= len(self):
6608 raise IndexError
6609 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6610 if (idx < num_consts):
6611 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6612 else:
6613 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6614 if isinstance(idx, FuncDeclRef):
6615 return self.get_interp(idx)
6616 if is_const(idx):
6617 return self.get_interp(idx.decl())
6618 if isinstance(idx, SortRef):
6619 return self.get_universe(idx)
6620 if z3_debug():
6621 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6622 return None
6623
6624 def decls(self):
6625 """Return a list with all symbols that have an interpretation in the model `self`.
6626 >>> f = Function('f', IntSort(), IntSort())
6627 >>> x = Int('x')
6628 >>> s = Solver()
6629 >>> s.add(x > 0, x < 2, f(x) == 0)
6630 >>> s.check()
6631 sat
6632 >>> m = s.model()
6633 >>> m.decls()
6634 [x, f]
6635 """
6636 r = []
6637 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6638 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6639 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6640 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6641 return r
6642
6643 def update_value(self, x, value):
6644 """Update the interpretation of a constant"""
6645 if is_expr(x):
6646 x = x.decl()
6647 if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
6648 fi1 = value.f
6649 fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
6650 fi2 = FuncInterp(fi2, x.ctx)
6651 for i in range(value.num_entries()):
6652 e = value.entry(i)
6653 n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
6654 v = AstVector()
6655 for j in range(n):
6656 v.push(entry.arg_value(j))
6657 val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
6658 Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
6659 return
6660 if not is_func_decl(x) or x.arity() != 0:
6661 raise Z3Exception("Expecting 0-ary function or constant expression")
6662 value = _py2expr(value)
6663 Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
6664
6665 def translate(self, target):
6666 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6667 """
6668 if z3_debug():
6669 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6670 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6671 return ModelRef(model, target)
6672
6673 def __copy__(self):
6674 return self.translate(self.ctx)
6675
6676 def __deepcopy__(self, memo={}):
6677 return self.translate(self.ctx)
6678
6679
6680def Model(ctx=None):
6681 ctx = _get_ctx(ctx)
6682 return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6683
6684
6686 """Return true if n is a Z3 expression of the form (_ as-array f)."""
6687 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6688
6689
6691 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6692 if z3_debug():
6693 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6694 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6695
6696
6701
6702
6704 """Statistics for `Solver.check()`."""
6705
6706 def __init__(self, stats, ctx):
6707 self.stats = stats
6708 self.ctx = ctx
6709 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6710
6711 def __deepcopy__(self, memo={}):
6712 return Statistics(self.stats, self.ctx)
6713
6714 def __del__(self):
6715 if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
6716 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6717
6718 def __repr__(self):
6719 if in_html_mode():
6720 out = io.StringIO()
6721 even = True
6722 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6723 for k, v in self:
6724 if even:
6725 out.write(u('<tr style="background-color:#CFCFCF">'))
6726 even = False
6727 else:
6728 out.write(u("<tr>"))
6729 even = True
6730 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
6731 out.write(u("</table>"))
6732 return out.getvalue()
6733 else:
6734 return Z3_stats_to_string(self.ctx.ref(), self.stats)
6735
6736 def __len__(self):
6737 """Return the number of statistical counters.
6738
6739 >>> x = Int('x')
6740 >>> s = Then('simplify', 'nlsat').solver()
6741 >>> s.add(x > 0)
6742 >>> s.check()
6743 sat
6744 >>> st = s.statistics()
6745 >>> len(st)
6746 6
6747 """
6748 return int(Z3_stats_size(self.ctx.ref(), self.stats))
6749
6750 def __getitem__(self, idx):
6751 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6752
6753 >>> x = Int('x')
6754 >>> s = Then('simplify', 'nlsat').solver()
6755 >>> s.add(x > 0)
6756 >>> s.check()
6757 sat
6758 >>> st = s.statistics()
6759 >>> len(st)
6760 6
6761 >>> st[0]
6762 ('nlsat propagations', 2)
6763 >>> st[1]
6764 ('nlsat stages', 2)
6765 """
6766 if idx >= len(self):
6767 raise IndexError
6768 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6769 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6770 else:
6771 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6772 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6773
6774 def keys(self):
6775 """Return the list of statistical counters.
6776
6777 >>> x = Int('x')
6778 >>> s = Then('simplify', 'nlsat').solver()
6779 >>> s.add(x > 0)
6780 >>> s.check()
6781 sat
6782 >>> st = s.statistics()
6783 """
6784 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6785
6786 def get_key_value(self, key):
6787 """Return the value of a particular statistical counter.
6788
6789 >>> x = Int('x')
6790 >>> s = Then('simplify', 'nlsat').solver()
6791 >>> s.add(x > 0)
6792 >>> s.check()
6793 sat
6794 >>> st = s.statistics()
6795 >>> st.get_key_value('nlsat propagations')
6796 2
6797 """
6798 for idx in range(len(self)):
6799 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6800 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6801 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6802 else:
6803 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6804 raise Z3Exception("unknown key")
6805
6806 def __getattr__(self, name):
6807 """Access the value of statistical using attributes.
6808
6809 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6810 we should use '_' (e.g., 'nlsat_propagations').
6811
6812 >>> x = Int('x')
6813 >>> s = Then('simplify', 'nlsat').solver()
6814 >>> s.add(x > 0)
6815 >>> s.check()
6816 sat
6817 >>> st = s.statistics()
6818 >>> st.nlsat_propagations
6819 2
6820 >>> st.nlsat_stages
6821 2
6822 """
6823 key = name.replace("_", " ")
6824 try:
6825 return self.get_key_value(key)
6826 except Z3Exception:
6827 raise AttributeError
6828
6829
6834
6835
6837 """Represents the result of a satisfiability check: sat, unsat, unknown.
6838
6839 >>> s = Solver()
6840 >>> s.check()
6841 sat
6842 >>> r = s.check()
6843 >>> isinstance(r, CheckSatResult)
6844 True
6845 """
6846
6847 def __init__(self, r):
6848 self.r = r
6849
6850 def __deepcopy__(self, memo={}):
6851 return CheckSatResult(self.r)
6852
6853 def __eq__(self, other):
6854 return isinstance(other, CheckSatResult) and self.r == other.r
6855
6856 def __ne__(self, other):
6857 return not self.__eq__(other)
6858
6859 def __repr__(self):
6860 if in_html_mode():
6861 if self.r == Z3_L_TRUE:
6862 return "<b>sat</b>"
6863 elif self.r == Z3_L_FALSE:
6864 return "<b>unsat</b>"
6865 else:
6866 return "<b>unknown</b>"
6867 else:
6868 if self.r == Z3_L_TRUE:
6869 return "sat"
6870 elif self.r == Z3_L_FALSE:
6871 return "unsat"
6872 else:
6873 return "unknown"
6874
6875 def _repr_html_(self):
6876 in_html = in_html_mode()
6877 set_html_mode(True)
6878 res = repr(self)
6879 set_html_mode(in_html)
6880 return res
6881
6882
6883sat = CheckSatResult(Z3_L_TRUE)
6884unsat = CheckSatResult(Z3_L_FALSE)
6885unknown = CheckSatResult(Z3_L_UNDEF)
6886
6887
6889 """
6890 Solver API provides methods for implementing the main SMT 2.0 commands:
6891 push, pop, check, get-model, etc.
6892 """
6893
6894 def __init__(self, solver=None, ctx=None, logFile=None):
6895 assert solver is None or ctx is not None
6896 self.ctx = _get_ctx(ctx)
6897 self.backtrack_level = 4000000000
6898 self.solver = None
6899 if solver is None:
6900 self.solver = Z3_mk_solver(self.ctx.ref())
6901 else:
6902 self.solver = solver
6903 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6904 if logFile is not None:
6905 self.set("smtlib2_log", logFile)
6906
6907 def __del__(self):
6908 if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
6909 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6910
6911 def set(self, *args, **keys):
6912 """Set a configuration option.
6913 The method `help()` return a string containing all available options.
6914
6915 >>> s = Solver()
6916 >>> # The option MBQI can be set using three different approaches.
6917 >>> s.set(mbqi=True)
6918 >>> s.set('MBQI', True)
6919 >>> s.set(':mbqi', True)
6920 """
6921 p = args2params(args, keys, self.ctx)
6922 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6923
6924 def push(self):
6925 """Create a backtracking point.
6926
6927 >>> x = Int('x')
6928 >>> s = Solver()
6929 >>> s.add(x > 0)
6930 >>> s
6931 [x > 0]
6932 >>> s.push()
6933 >>> s.add(x < 1)
6934 >>> s
6935 [x > 0, x < 1]
6936 >>> s.check()
6937 unsat
6938 >>> s.pop()
6939 >>> s.check()
6940 sat
6941 >>> s
6942 [x > 0]
6943 """
6944 Z3_solver_push(self.ctx.ref(), self.solver)
6945
6946 def pop(self, num=1):
6947 """Backtrack \\c num backtracking points.
6948
6949 >>> x = Int('x')
6950 >>> s = Solver()
6951 >>> s.add(x > 0)
6952 >>> s
6953 [x > 0]
6954 >>> s.push()
6955 >>> s.add(x < 1)
6956 >>> s
6957 [x > 0, x < 1]
6958 >>> s.check()
6959 unsat
6960 >>> s.pop()
6961 >>> s.check()
6962 sat
6963 >>> s
6964 [x > 0]
6965 """
6966 Z3_solver_pop(self.ctx.ref(), self.solver, num)
6967
6968 def num_scopes(self):
6969 """Return the current number of backtracking points.
6970
6971 >>> s = Solver()
6972 >>> s.num_scopes()
6973 0
6974 >>> s.push()
6975 >>> s.num_scopes()
6976 1
6977 >>> s.push()
6978 >>> s.num_scopes()
6979 2
6980 >>> s.pop()
6981 >>> s.num_scopes()
6982 1
6983 """
6984 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6985
6986 def reset(self):
6987 """Remove all asserted constraints and backtracking points created using `push()`.
6988
6989 >>> x = Int('x')
6990 >>> s = Solver()
6991 >>> s.add(x > 0)
6992 >>> s
6993 [x > 0]
6994 >>> s.reset()
6995 >>> s
6996 []
6997 """
6998 Z3_solver_reset(self.ctx.ref(), self.solver)
6999
7000 def assert_exprs(self, *args):
7001 """Assert constraints into the solver.
7002
7003 >>> x = Int('x')
7004 >>> s = Solver()
7005 >>> s.assert_exprs(x > 0, x < 2)
7006 >>> s
7007 [x > 0, x < 2]
7008 """
7009 args = _get_args(args)
7010 s = BoolSort(self.ctx)
7011 for arg in args:
7012 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7013 for f in arg:
7014 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7015 else:
7016 arg = s.cast(arg)
7017 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7018
7019 def add(self, *args):
7020 """Assert constraints into the solver.
7021
7022 >>> x = Int('x')
7023 >>> s = Solver()
7024 >>> s.add(x > 0, x < 2)
7025 >>> s
7026 [x > 0, x < 2]
7027 """
7028 self.assert_exprs(*args)
7029
7030 def __iadd__(self, fml):
7031 self.add(fml)
7032 return self
7033
7034 def append(self, *args):
7035 """Assert constraints into the solver.
7036
7037 >>> x = Int('x')
7038 >>> s = Solver()
7039 >>> s.append(x > 0, x < 2)
7040 >>> s
7041 [x > 0, x < 2]
7042 """
7043 self.assert_exprs(*args)
7044
7045 def insert(self, *args):
7046 """Assert constraints into the solver.
7047
7048 >>> x = Int('x')
7049 >>> s = Solver()
7050 >>> s.insert(x > 0, x < 2)
7051 >>> s
7052 [x > 0, x < 2]
7053 """
7054 self.assert_exprs(*args)
7055
7056 def assert_and_track(self, a, p):
7057 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7058
7059 If `p` is a string, it will be automatically converted into a Boolean constant.
7060
7061 >>> x = Int('x')
7062 >>> p3 = Bool('p3')
7063 >>> s = Solver()
7064 >>> s.set(unsat_core=True)
7065 >>> s.assert_and_track(x > 0, 'p1')
7066 >>> s.assert_and_track(x != 1, 'p2')
7067 >>> s.assert_and_track(x < 0, p3)
7068 >>> print(s.check())
7069 unsat
7070 >>> c = s.unsat_core()
7071 >>> len(c)
7072 2
7073 >>> Bool('p1') in c
7074 True
7075 >>> Bool('p2') in c
7076 False
7077 >>> p3 in c
7078 True
7079 """
7080 if isinstance(p, str):
7081 p = Bool(p, self.ctx)
7082 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7083 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7084 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7085
7086 def check(self, *assumptions):
7087 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7088
7089 >>> x = Int('x')
7090 >>> s = Solver()
7091 >>> s.check()
7092 sat
7093 >>> s.add(x > 0, x < 2)
7094 >>> s.check()
7095 sat
7096 >>> s.model().eval(x)
7097 1
7098 >>> s.add(x < 1)
7099 >>> s.check()
7100 unsat
7101 >>> s.reset()
7102 >>> s.add(2**x == 4)
7103 >>> s.check()
7104 unknown
7105 """
7106 s = BoolSort(self.ctx)
7107 assumptions = _get_args(assumptions)
7108 num = len(assumptions)
7109 _assumptions = (Ast * num)()
7110 for i in range(num):
7111 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7112 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7113 return CheckSatResult(r)
7114
7115 def model(self):
7116 """Return a model for the last `check()`.
7117
7118 This function raises an exception if
7119 a model is not available (e.g., last `check()` returned unsat).
7120
7121 >>> s = Solver()
7122 >>> a = Int('a')
7123 >>> s.add(a + 2 == 0)
7124 >>> s.check()
7125 sat
7126 >>> s.model()
7127 [a = -2]
7128 """
7129 try:
7130 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7131 except Z3Exception:
7132 raise Z3Exception("model is not available")
7133
7134 def import_model_converter(self, other):
7135 """Import model converter from other into the current solver"""
7136 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7137
7138 def unsat_core(self):
7139 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7140
7141 These are the assumptions Z3 used in the unsatisfiability proof.
7142 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7143 They may be also used to "retract" assumptions. Note that, assumptions are not really
7144 "soft constraints", but they can be used to implement them.
7145
7146 >>> p1, p2, p3 = Bools('p1 p2 p3')
7147 >>> x, y = Ints('x y')
7148 >>> s = Solver()
7149 >>> s.add(Implies(p1, x > 0))
7150 >>> s.add(Implies(p2, y > x))
7151 >>> s.add(Implies(p2, y < 1))
7152 >>> s.add(Implies(p3, y > -3))
7153 >>> s.check(p1, p2, p3)
7154 unsat
7155 >>> core = s.unsat_core()
7156 >>> len(core)
7157 2
7158 >>> p1 in core
7159 True
7160 >>> p2 in core
7161 True
7162 >>> p3 in core
7163 False
7164 >>> # "Retracting" p2
7165 >>> s.check(p1, p3)
7166 sat
7167 """
7168 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7169
7170 def consequences(self, assumptions, variables):
7171 """Determine fixed values for the variables based on the solver state and assumptions.
7172 >>> s = Solver()
7173 >>> a, b, c, d = Bools('a b c d')
7174 >>> s.add(Implies(a,b), Implies(b, c))
7175 >>> s.consequences([a],[b,c,d])
7176 (sat, [Implies(a, b), Implies(a, c)])
7177 >>> s.consequences([Not(c),d],[a,b,c,d])
7178 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7179 """
7180 if isinstance(assumptions, list):
7181 _asms = AstVector(None, self.ctx)
7182 for a in assumptions:
7183 _asms.push(a)
7184 assumptions = _asms
7185 if isinstance(variables, list):
7186 _vars = AstVector(None, self.ctx)
7187 for a in variables:
7188 _vars.push(a)
7189 variables = _vars
7190 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7191 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7192 consequences = AstVector(None, self.ctx)
7193 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7194 variables.vector, consequences.vector)
7195 sz = len(consequences)
7196 consequences = [consequences[i] for i in range(sz)]
7197 return CheckSatResult(r), consequences
7198
7199 def from_file(self, filename):
7200 """Parse assertions from a file"""
7201 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7202
7203 def from_string(self, s):
7204 """Parse assertions from a string"""
7205 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7206
7207 def cube(self, vars=None):
7208 """Get set of cubes
7209 The method takes an optional set of variables that restrict which
7210 variables may be used as a starting point for cubing.
7211 If vars is not None, then the first case split is based on a variable in
7212 this set.
7213 """
7214 self.cube_vs = AstVector(None, self.ctx)
7215 if vars is not None:
7216 for v in vars:
7217 self.cube_vs.push(v)
7218 while True:
7219 lvl = self.backtrack_level
7220 self.backtrack_level = 4000000000
7221 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7222 if (len(r) == 1 and is_false(r[0])):
7223 return
7224 yield r
7225 if (len(r) == 0):
7226 return
7227
7228 def cube_vars(self):
7229 """Access the set of variables that were touched by the most recently generated cube.
7230 This set of variables can be used as a starting point for additional cubes.
7231 The idea is that variables that appear in clauses that are reduced by the most recent
7232 cube are likely more useful to cube on."""
7233 return self.cube_vs
7234
7235 def proof(self):
7236 """Return a proof for the last `check()`. Proof construction must be enabled."""
7237 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7238
7239 def assertions(self):
7240 """Return an AST vector containing all added constraints.
7241
7242 >>> s = Solver()
7243 >>> s.assertions()
7244 []
7245 >>> a = Int('a')
7246 >>> s.add(a > 0)
7247 >>> s.add(a < 10)
7248 >>> s.assertions()
7249 [a > 0, a < 10]
7250 """
7251 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7252
7253 def units(self):
7254 """Return an AST vector containing all currently inferred units.
7255 """
7256 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7257
7258 def non_units(self):
7259 """Return an AST vector containing all atomic formulas in solver state that are not units.
7260 """
7261 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7262
7263 def trail_levels(self):
7264 """Return trail and decision levels of the solver state after a check() call.
7265 """
7266 trail = self.trail()
7267 levels = (ctypes.c_uint * len(trail))()
7268 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7269 return trail, levels
7270
7271 def trail(self):
7272 """Return trail of the solver state after a check() call.
7273 """
7274 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7275
7276 def statistics(self):
7277 """Return statistics for the last `check()`.
7278
7279 >>> s = SimpleSolver()
7280 >>> x = Int('x')
7281 >>> s.add(x > 0)
7282 >>> s.check()
7283 sat
7284 >>> st = s.statistics()
7285 >>> st.get_key_value('final checks')
7286 1
7287 >>> len(st) > 0
7288 True
7289 >>> st[0] != 0
7290 True
7291 """
7292 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
7293
7295 """Return a string describing why the last `check()` returned `unknown`.
7296
7297 >>> x = Int('x')
7298 >>> s = SimpleSolver()
7299 >>> s.add(2**x == 4)
7300 >>> s.check()
7301 unknown
7302 >>> s.reason_unknown()
7303 '(incomplete (theory arithmetic))'
7304 """
7305 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
7306
7307 def help(self):
7308 """Display a string describing all available options."""
7309 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
7310
7311 def param_descrs(self):
7312 """Return the parameter description set."""
7313 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
7314
7315 def __repr__(self):
7316 """Return a formatted string with all added constraints."""
7317 return obj_to_string(self)
7318
7319 def translate(self, target):
7320 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7321
7322 >>> c1 = Context()
7323 >>> c2 = Context()
7324 >>> s1 = Solver(ctx=c1)
7325 >>> s2 = s1.translate(c2)
7326 """
7327 if z3_debug():
7328 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7329 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
7330 return Solver(solver, target)
7331
7332 def __copy__(self):
7333 return self.translate(self.ctx)
7334
7335 def __deepcopy__(self, memo={}):
7336 return self.translate(self.ctx)
7337
7338 def sexpr(self):
7339 """Return a formatted string (in Lisp-like format) with all added constraints.
7340 We say the string is in s-expression format.
7341
7342 >>> x = Int('x')
7343 >>> s = Solver()
7344 >>> s.add(x > 0)
7345 >>> s.add(x < 2)
7346 >>> r = s.sexpr()
7347 """
7348 return Z3_solver_to_string(self.ctx.ref(), self.solver)
7349
7350 def dimacs(self, include_names=True):
7351 """Return a textual representation of the solver in DIMACS format."""
7352 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
7353
7354 def to_smt2(self):
7355 """return SMTLIB2 formatted benchmark for solver's assertions"""
7356 es = self.assertions()
7357 sz = len(es)
7358 sz1 = sz
7359 if sz1 > 0:
7360 sz1 -= 1
7361 v = (Ast * sz1)()
7362 for i in range(sz1):
7363 v[i] = es[i].as_ast()
7364 if sz > 0:
7365 e = es[sz1].as_ast()
7366 else:
7367 e = BoolVal(True, self.ctx).as_ast()
7369 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
7370 )
7371
7372
7373def SolverFor(logic, ctx=None, logFile=None):
7374 """Create a solver customized for the given logic.
7375
7376 The parameter `logic` is a string. It should be contains
7377 the name of a SMT-LIB logic.
7378 See http://www.smtlib.org/ for the name of all available logics.
7379
7380 >>> s = SolverFor("QF_LIA")
7381 >>> x = Int('x')
7382 >>> s.add(x > 0)
7383 >>> s.add(x < 2)
7384 >>> s.check()
7385 sat
7386 >>> s.model()
7387 [x = 1]
7388 """
7389 ctx = _get_ctx(ctx)
7390 logic = to_symbol(logic)
7391 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
7392
7393
7394def SimpleSolver(ctx=None, logFile=None):
7395 """Return a simple general purpose solver with limited amount of preprocessing.
7396
7397 >>> s = SimpleSolver()
7398 >>> x = Int('x')
7399 >>> s.add(x > 0)
7400 >>> s.check()
7401 sat
7402 """
7403 ctx = _get_ctx(ctx)
7404 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
7405
7406
7411
7412
7414 """Fixedpoint API provides methods for solving with recursive predicates"""
7415
7416 def __init__(self, fixedpoint=None, ctx=None):
7417 assert fixedpoint is None or ctx is not None
7418 self.ctx = _get_ctx(ctx)
7419 self.fixedpoint = None
7420 if fixedpoint is None:
7421 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
7422 else:
7423 self.fixedpoint = fixedpoint
7424 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
7425 self.vars = []
7426
7427 def __deepcopy__(self, memo={}):
7428 return FixedPoint(self.fixedpoint, self.ctx)
7429
7430 def __del__(self):
7431 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
7432 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
7433
7434 def set(self, *args, **keys):
7435 """Set a configuration option. The method `help()` return a string containing all available options.
7436 """
7437 p = args2params(args, keys, self.ctx)
7438 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
7439
7440 def help(self):
7441 """Display a string describing all available options."""
7442 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
7443
7444 def param_descrs(self):
7445 """Return the parameter description set."""
7446 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
7447
7448 def assert_exprs(self, *args):
7449 """Assert constraints as background axioms for the fixedpoint solver."""
7450 args = _get_args(args)
7451 s = BoolSort(self.ctx)
7452 for arg in args:
7453 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7454 for f in arg:
7455 f = self.abstract(f)
7456 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
7457 else:
7458 arg = s.cast(arg)
7459 arg = self.abstract(arg)
7460 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
7461
7462 def add(self, *args):
7463 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7464 self.assert_exprs(*args)
7465
7466 def __iadd__(self, fml):
7467 self.add(fml)
7468 return self
7469
7470 def append(self, *args):
7471 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7472 self.assert_exprs(*args)
7473
7474 def insert(self, *args):
7475 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7476 self.assert_exprs(*args)
7477
7478 def add_rule(self, head, body=None, name=None):
7479 """Assert rules defining recursive predicates to the fixedpoint solver.
7480 >>> a = Bool('a')
7481 >>> b = Bool('b')
7482 >>> s = Fixedpoint()
7483 >>> s.register_relation(a.decl())
7484 >>> s.register_relation(b.decl())
7485 >>> s.fact(a)
7486 >>> s.rule(b, a)
7487 >>> s.query(b)
7488 sat
7489 """
7490 if name is None:
7491 name = ""
7492 name = to_symbol(name, self.ctx)
7493 if body is None:
7494 head = self.abstract(head)
7495 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7496 else:
7497 body = _get_args(body)
7498 f = self.abstract(Implies(And(body, self.ctx), head))
7499 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7500
7501 def rule(self, head, body=None, name=None):
7502 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7503 self.add_rule(head, body, name)
7504
7505 def fact(self, head, name=None):
7506 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7507 self.add_rule(head, None, name)
7508
7509 def query(self, *query):
7510 """Query the fixedpoint engine whether formula is derivable.
7511 You can also pass an tuple or list of recursive predicates.
7512 """
7513 query = _get_args(query)
7514 sz = len(query)
7515 if sz >= 1 and isinstance(query[0], FuncDeclRef):
7516 _decls = (FuncDecl * sz)()
7517 i = 0
7518 for q in query:
7519 _decls[i] = q.ast
7520 i = i + 1
7521 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7522 else:
7523 if sz == 1:
7524 query = query[0]
7525 else:
7526 query = And(query, self.ctx)
7527 query = self.abstract(query, False)
7528 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7529 return CheckSatResult(r)
7530
7531 def query_from_lvl(self, lvl, *query):
7532 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7533 """
7534 query = _get_args(query)
7535 sz = len(query)
7536 if sz >= 1 and isinstance(query[0], FuncDecl):
7537 _z3_assert(False, "unsupported")
7538 else:
7539 if sz == 1:
7540 query = query[0]
7541 else:
7542 query = And(query)
7543 query = self.abstract(query, False)
7544 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7545 return CheckSatResult(r)
7546
7547 def update_rule(self, head, body, name):
7548 """update rule"""
7549 if name is None:
7550 name = ""
7551 name = to_symbol(name, self.ctx)
7552 body = _get_args(body)
7553 f = self.abstract(Implies(And(body, self.ctx), head))
7554 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7555
7556 def get_answer(self):
7557 """Retrieve answer from last query call."""
7558 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7559 return _to_expr_ref(r, self.ctx)
7560
7562 """Retrieve a ground cex from last query call."""
7563 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7564 return _to_expr_ref(r, self.ctx)
7565
7567 """retrieve rules along the counterexample trace"""
7568 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7569
7571 """retrieve rule names along the counterexample trace"""
7572 # this is a hack as I don't know how to return a list of symbols from C++;
7573 # obtain names as a single string separated by semicolons
7574 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7575 # split into individual names
7576 return names.split(";")
7577
7578 def get_num_levels(self, predicate):
7579 """Retrieve number of levels used for predicate in PDR engine"""
7580 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7581
7582 def get_cover_delta(self, level, predicate):
7583 """Retrieve properties known about predicate for the level'th unfolding.
7584 -1 is treated as the limit (infinity)
7585 """
7586 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7587 return _to_expr_ref(r, self.ctx)
7588
7589 def add_cover(self, level, predicate, property):
7590 """Add property to predicate for the level'th unfolding.
7591 -1 is treated as infinity (infinity)
7592 """
7593 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7594
7595 def register_relation(self, *relations):
7596 """Register relation as recursive"""
7597 relations = _get_args(relations)
7598 for f in relations:
7599 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7600
7601 def set_predicate_representation(self, f, *representations):
7602 """Control how relation is represented"""
7603 representations = _get_args(representations)
7604 representations = [to_symbol(s) for s in representations]
7605 sz = len(representations)
7606 args = (Symbol * sz)()
7607 for i in range(sz):
7608 args[i] = representations[i]
7609 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7610
7611 def parse_string(self, s):
7612 """Parse rules and queries from a string"""
7613 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7614
7615 def parse_file(self, f):
7616 """Parse rules and queries from a file"""
7617 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7618
7619 def get_rules(self):
7620 """retrieve rules that have been added to fixedpoint context"""
7621 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7622
7624 """retrieve assertions that have been added to fixedpoint context"""
7625 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7626
7627 def __repr__(self):
7628 """Return a formatted string with all added rules and constraints."""
7629 return self.sexpr()
7630
7631 def sexpr(self):
7632 """Return a formatted string (in Lisp-like format) with all added constraints.
7633 We say the string is in s-expression format.
7634 """
7635 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7636
7637 def to_string(self, queries):
7638 """Return a formatted string (in Lisp-like format) with all added constraints.
7639 We say the string is in s-expression format.
7640 Include also queries.
7641 """
7642 args, len = _to_ast_array(queries)
7643 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7644
7645 def statistics(self):
7646 """Return statistics for the last `query()`.
7647 """
7648 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7649
7651 """Return a string describing why the last `query()` returned `unknown`.
7652 """
7653 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7654
7655 def declare_var(self, *vars):
7656 """Add variable or several variables.
7657 The added variable or variables will be bound in the rules
7658 and queries
7659 """
7660 vars = _get_args(vars)
7661 for v in vars:
7662 self.vars += [v]
7663
7664 def abstract(self, fml, is_forall=True):
7665 if self.vars == []:
7666 return fml
7667 if is_forall:
7668 return ForAll(self.vars, fml)
7669 else:
7670 return Exists(self.vars, fml)
7671
7672
7673
7678
7680 """Finite domain sort."""
7681
7682 def size(self):
7683 """Return the size of the finite domain sort"""
7684 r = (ctypes.c_ulonglong * 1)()
7685 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7686 return r[0]
7687 else:
7688 raise Z3Exception("Failed to retrieve finite domain sort size")
7689
7690
7691def FiniteDomainSort(name, sz, ctx=None):
7692 """Create a named finite domain sort of a given size sz"""
7693 if not isinstance(name, Symbol):
7694 name = to_symbol(name)
7695 ctx = _get_ctx(ctx)
7696 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7697
7698
7700 """Return True if `s` is a Z3 finite-domain sort.
7701
7703 True
7705 False
7706 """
7707 return isinstance(s, FiniteDomainSortRef)
7708
7709
7711 """Finite-domain expressions."""
7712
7713 def sort(self):
7714 """Return the sort of the finite-domain expression `self`."""
7715 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
7716
7717 def as_string(self):
7718 """Return a Z3 floating point expression as a Python string."""
7719 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
7720
7721
7723 """Return `True` if `a` is a Z3 finite-domain expression.
7724
7725 >>> s = FiniteDomainSort('S', 100)
7726 >>> b = Const('b', s)
7727 >>> is_finite_domain(b)
7728 True
7729 >>> is_finite_domain(Int('x'))
7730 False
7731 """
7732 return isinstance(a, FiniteDomainRef)
7733
7734
7736 """Integer values."""
7737
7738 def as_long(self):
7739 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7740
7741 >>> s = FiniteDomainSort('S', 100)
7742 >>> v = FiniteDomainVal(3, s)
7743 >>> v
7744 3
7745 >>> v.as_long() + 1
7746 4
7747 """
7748 return int(self.as_stringas_string())
7749
7750 def as_string(self):
7751 """Return a Z3 finite-domain numeral as a Python string.
7752
7753 >>> s = FiniteDomainSort('S', 100)
7754 >>> v = FiniteDomainVal(42, s)
7755 >>> v.as_string()
7756 '42'
7757 """
7758 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
7759
7760
7761def FiniteDomainVal(val, sort, ctx=None):
7762 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7763
7764 >>> s = FiniteDomainSort('S', 256)
7765 >>> FiniteDomainVal(255, s)
7766 255
7767 >>> FiniteDomainVal('100', s)
7768 100
7769 """
7770 if z3_debug():
7771 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
7772 ctx = sort.ctx
7773 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7774
7775
7777 """Return `True` if `a` is a Z3 finite-domain value.
7778
7779 >>> s = FiniteDomainSort('S', 100)
7780 >>> b = Const('b', s)
7782 False
7783 >>> b = FiniteDomainVal(10, s)
7784 >>> b
7785 10
7787 True
7788 """
7789 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7790
7791
7792
7797
7799 def __init__(self, opt, value, is_max):
7800 self._opt = opt
7801 self._value = value
7802 self._is_max = is_max
7803
7804 def lower(self):
7805 opt = self._opt
7806 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7807
7808 def upper(self):
7809 opt = self._opt
7810 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7811
7812 def lower_values(self):
7813 opt = self._opt
7814 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7815
7816 def upper_values(self):
7817 opt = self._opt
7818 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7819
7820 def value(self):
7821 if self._is_max:
7822 return self.upper()
7823 else:
7824 return self.lower()
7825
7826 def __str__(self):
7827 return "%s:%s" % (self._value, self._is_max)
7828
7829
7830_on_models = {}
7831
7832
7833def _global_on_model(ctx):
7834 (fn, mdl) = _on_models[ctx]
7835 fn(mdl)
7836
7837
7838_on_model_eh = on_model_eh_type(_global_on_model)
7839
7840
7842 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7843
7844 def __init__(self, ctx=None):
7845 self.ctx = _get_ctx(ctx)
7846 self.optimize = Z3_mk_optimize(self.ctx.ref())
7847 self._on_models_id = None
7848 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7849
7850 def __deepcopy__(self, memo={}):
7851 return Optimize(self.optimize, self.ctx)
7852
7853 def __del__(self):
7854 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
7855 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7856 if self._on_models_id is not None:
7857 del _on_models[self._on_models_id]
7858
7859 def set(self, *args, **keys):
7860 """Set a configuration option.
7861 The method `help()` return a string containing all available options.
7862 """
7863 p = args2params(args, keys, self.ctx)
7864 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7865
7866 def help(self):
7867 """Display a string describing all available options."""
7868 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7869
7870 def param_descrs(self):
7871 """Return the parameter description set."""
7872 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7873
7874 def assert_exprs(self, *args):
7875 """Assert constraints as background axioms for the optimize solver."""
7876 args = _get_args(args)
7877 s = BoolSort(self.ctx)
7878 for arg in args:
7879 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7880 for f in arg:
7881 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7882 else:
7883 arg = s.cast(arg)
7884 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7885
7886 def add(self, *args):
7887 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7888 self.assert_exprs(*args)
7889
7890 def __iadd__(self, fml):
7891 self.add(fml)
7892 return self
7893
7894 def assert_and_track(self, a, p):
7895 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7896
7897 If `p` is a string, it will be automatically converted into a Boolean constant.
7898
7899 >>> x = Int('x')
7900 >>> p3 = Bool('p3')
7901 >>> s = Optimize()
7902 >>> s.assert_and_track(x > 0, 'p1')
7903 >>> s.assert_and_track(x != 1, 'p2')
7904 >>> s.assert_and_track(x < 0, p3)
7905 >>> print(s.check())
7906 unsat
7907 >>> c = s.unsat_core()
7908 >>> len(c)
7909 2
7910 >>> Bool('p1') in c
7911 True
7912 >>> Bool('p2') in c
7913 False
7914 >>> p3 in c
7915 True
7916 """
7917 if isinstance(p, str):
7918 p = Bool(p, self.ctx)
7919 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7920 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7921 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7922
7923 def add_soft(self, arg, weight="1", id=None):
7924 """Add soft constraint with optional weight and optional identifier.
7925 If no weight is supplied, then the penalty for violating the soft constraint
7926 is 1.
7927 Soft constraints are grouped by identifiers. Soft constraints that are
7928 added without identifiers are grouped by default.
7929 """
7930 if _is_int(weight):
7931 weight = "%d" % weight
7932 elif isinstance(weight, float):
7933 weight = "%f" % weight
7934 if not isinstance(weight, str):
7935 raise Z3Exception("weight should be a string or an integer")
7936 if id is None:
7937 id = ""
7938 id = to_symbol(id, self.ctx)
7939
7940 def asoft(a):
7941 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
7942 return OptimizeObjective(self, v, False)
7943 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
7944 return [asoft(a) for a in arg]
7945 return asoft(arg)
7946
7947 def maximize(self, arg):
7948 """Add objective function to maximize."""
7949 return OptimizeObjective(
7950 self,
7951 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
7952 is_max=True,
7953 )
7954
7955 def minimize(self, arg):
7956 """Add objective function to minimize."""
7957 return OptimizeObjective(
7958 self,
7959 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
7960 is_max=False,
7961 )
7962
7963 def push(self):
7964 """create a backtracking point for added rules, facts and assertions"""
7965 Z3_optimize_push(self.ctx.ref(), self.optimize)
7966
7967 def pop(self):
7968 """restore to previously created backtracking point"""
7969 Z3_optimize_pop(self.ctx.ref(), self.optimize)
7970
7971 def check(self, *assumptions):
7972 """Check satisfiability while optimizing objective functions."""
7973 assumptions = _get_args(assumptions)
7974 num = len(assumptions)
7975 _assumptions = (Ast * num)()
7976 for i in range(num):
7977 _assumptions[i] = assumptions[i].as_ast()
7978 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7979
7981 """Return a string that describes why the last `check()` returned `unknown`."""
7982 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7983
7984 def model(self):
7985 """Return a model for the last check()."""
7986 try:
7987 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7988 except Z3Exception:
7989 raise Z3Exception("model is not available")
7990
7991 def unsat_core(self):
7992 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7993
7994 def lower(self, obj):
7995 if not isinstance(obj, OptimizeObjective):
7996 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7997 return obj.lower()
7998
7999 def upper(self, obj):
8000 if not isinstance(obj, OptimizeObjective):
8001 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8002 return obj.upper()
8003
8004 def lower_values(self, obj):
8005 if not isinstance(obj, OptimizeObjective):
8006 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8007 return obj.lower_values()
8008
8009 def upper_values(self, obj):
8010 if not isinstance(obj, OptimizeObjective):
8011 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8012 return obj.upper_values()
8013
8014 def from_file(self, filename):
8015 """Parse assertions and objectives from a file"""
8016 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8017
8018 def from_string(self, s):
8019 """Parse assertions and objectives from a string"""
8020 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8021
8022 def assertions(self):
8023 """Return an AST vector containing all added constraints."""
8024 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8025
8026 def objectives(self):
8027 """returns set of objective functions"""
8028 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8029
8030 def __repr__(self):
8031 """Return a formatted string with all added rules and constraints."""
8032 return self.sexpr()
8033
8034 def sexpr(self):
8035 """Return a formatted string (in Lisp-like format) with all added constraints.
8036 We say the string is in s-expression format.
8037 """
8038 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8039
8040 def statistics(self):
8041 """Return statistics for the last check`.
8042 """
8043 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8044
8045 def set_on_model(self, on_model):
8046 """Register a callback that is invoked with every incremental improvement to
8047 objective values. The callback takes a model as argument.
8048 The life-time of the model is limited to the callback so the
8049 model has to be (deep) copied if it is to be used after the callback
8050 """
8051 id = len(_on_models) + 41
8052 mdl = Model(self.ctx)
8053 _on_models[id] = (on_model, mdl)
8054 self._on_models_id = id
8056 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8057 )
8058
8059
8060
8066 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8067 It also contains model and proof converters.
8068 """
8069
8070 def __init__(self, result, ctx):
8071 self.result = result
8072 self.ctx = ctx
8073 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8074
8075 def __deepcopy__(self, memo={}):
8076 return ApplyResult(self.result, self.ctx)
8077
8078 def __del__(self):
8079 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8080 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8081
8082 def __len__(self):
8083 """Return the number of subgoals in `self`.
8084
8085 >>> a, b = Ints('a b')
8086 >>> g = Goal()
8087 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8088 >>> t = Tactic('split-clause')
8089 >>> r = t(g)
8090 >>> len(r)
8091 2
8092 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8093 >>> len(t(g))
8094 4
8095 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8096 >>> len(t(g))
8097 1
8098 """
8099 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8100
8101 def __getitem__(self, idx):
8102 """Return one of the subgoals stored in ApplyResult object `self`.
8103
8104 >>> a, b = Ints('a b')
8105 >>> g = Goal()
8106 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8107 >>> t = Tactic('split-clause')
8108 >>> r = t(g)
8109 >>> r[0]
8110 [a == 0, Or(b == 0, b == 1), a > b]
8111 >>> r[1]
8112 [a == 1, Or(b == 0, b == 1), a > b]
8113 """
8114 if idx >= len(self):
8115 raise IndexError
8116 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8117
8118 def __repr__(self):
8119 return obj_to_string(self)
8120
8121 def sexpr(self):
8122 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8123 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8124
8125 def as_expr(self):
8126 """Return a Z3 expression consisting of all subgoals.
8127
8128 >>> x = Int('x')
8129 >>> g = Goal()
8130 >>> g.add(x > 1)
8131 >>> g.add(Or(x == 2, x == 3))
8132 >>> r = Tactic('simplify')(g)
8133 >>> r
8134 [[Not(x <= 1), Or(x == 2, x == 3)]]
8135 >>> r.as_expr()
8136 And(Not(x <= 1), Or(x == 2, x == 3))
8137 >>> r = Tactic('split-clause')(g)
8138 >>> r
8139 [[x > 1, x == 2], [x > 1, x == 3]]
8140 >>> r.as_expr()
8141 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8142 """
8143 sz = len(self)
8144 if sz == 0:
8145 return BoolVal(False, self.ctx)
8146 elif sz == 1:
8147 return self[0].as_expr()
8148 else:
8149 return Or([self[i].as_expr() for i in range(len(self))])
8150
8151
8156
8157
8159 """Tactics transform, solver and/or simplify sets of constraints (Goal).
8160 A Tactic can be converted into a Solver using the method solver().
8161
8162 Several combinators are available for creating new tactics using the built-in ones:
8163 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8164 """
8165
8166 def __init__(self, tactic, ctx=None):
8167 self.ctx = _get_ctx(ctx)
8168 self.tactic = None
8169 if isinstance(tactic, TacticObj):
8170 self.tactic = tactic
8171 else:
8172 if z3_debug():
8173 _z3_assert(isinstance(tactic, str), "tactic name expected")
8174 try:
8175 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
8176 except Z3Exception:
8177 raise Z3Exception("unknown tactic '%s'" % tactic)
8178 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
8179
8180 def __deepcopy__(self, memo={}):
8181 return Tactic(self.tactic, self.ctx)
8182
8183 def __del__(self):
8184 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
8185 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
8186
8187 def solver(self, logFile=None):
8188 """Create a solver using the tactic `self`.
8189
8190 The solver supports the methods `push()` and `pop()`, but it
8191 will always solve each `check()` from scratch.
8192
8193 >>> t = Then('simplify', 'nlsat')
8194 >>> s = t.solver()
8195 >>> x = Real('x')
8196 >>> s.add(x**2 == 2, x > 0)
8197 >>> s.check()
8198 sat
8199 >>> s.model()
8200 [x = 1.4142135623?]
8201 """
8202 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
8203
8204 def apply(self, goal, *arguments, **keywords):
8205 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8206
8207 >>> x, y = Ints('x y')
8208 >>> t = Tactic('solve-eqs')
8209 >>> t.apply(And(x == 0, y >= x + 1))
8210 [[y >= 1]]
8211 """
8212 if z3_debug():
8213 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
8214 goal = _to_goal(goal)
8215 if len(arguments) > 0 or len(keywords) > 0:
8216 p = args2params(arguments, keywords, self.ctx)
8217 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
8218 else:
8219 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
8220
8221 def __call__(self, goal, *arguments, **keywords):
8222 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
8223
8224 >>> x, y = Ints('x y')
8225 >>> t = Tactic('solve-eqs')
8226 >>> t(And(x == 0, y >= x + 1))
8227 [[y >= 1]]
8228 """
8229 return self.apply(goal, *arguments, **keywords)
8230
8231 def help(self):
8232 """Display a string containing a description of the available options for the `self` tactic."""
8233 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
8234
8235 def param_descrs(self):
8236 """Return the parameter description set."""
8237 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
8238
8239
8240def _to_goal(a):
8241 if isinstance(a, BoolRef):
8242 goal = Goal(ctx=a.ctx)
8243 goal.add(a)
8244 return goal
8245 else:
8246 return a
8247
8248
8249def _to_tactic(t, ctx=None):
8250 if isinstance(t, Tactic):
8251 return t
8252 else:
8253 return Tactic(t, ctx)
8254
8255
8256def _and_then(t1, t2, ctx=None):
8257 t1 = _to_tactic(t1, ctx)
8258 t2 = _to_tactic(t2, ctx)
8259 if z3_debug():
8260 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8261 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8262
8263
8264def _or_else(t1, t2, ctx=None):
8265 t1 = _to_tactic(t1, ctx)
8266 t2 = _to_tactic(t2, ctx)
8267 if z3_debug():
8268 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8269 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8270
8271
8272def AndThen(*ts, **ks):
8273 """Return a tactic that applies the tactics in `*ts` in sequence.
8274
8275 >>> x, y = Ints('x y')
8276 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
8277 >>> t(And(x == 0, y > x + 1))
8278 [[Not(y <= 1)]]
8279 >>> t(And(x == 0, y > x + 1)).as_expr()
8280 Not(y <= 1)
8281 """
8282 if z3_debug():
8283 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8284 ctx = ks.get("ctx", None)
8285 num = len(ts)
8286 r = ts[0]
8287 for i in range(num - 1):
8288 r = _and_then(r, ts[i + 1], ctx)
8289 return r
8290
8291
8292def Then(*ts, **ks):
8293 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
8294
8295 >>> x, y = Ints('x y')
8296 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
8297 >>> t(And(x == 0, y > x + 1))
8298 [[Not(y <= 1)]]
8299 >>> t(And(x == 0, y > x + 1)).as_expr()
8300 Not(y <= 1)
8301 """
8302 return AndThen(*ts, **ks)
8303
8304
8305def OrElse(*ts, **ks):
8306 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
8307
8308 >>> x = Int('x')
8309 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
8310 >>> # Tactic split-clause fails if there is no clause in the given goal.
8311 >>> t(x == 0)
8312 [[x == 0]]
8313 >>> t(Or(x == 0, x == 1))
8314 [[x == 0], [x == 1]]
8315 """
8316 if z3_debug():
8317 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8318 ctx = ks.get("ctx", None)
8319 num = len(ts)
8320 r = ts[0]
8321 for i in range(num - 1):
8322 r = _or_else(r, ts[i + 1], ctx)
8323 return r
8324
8325
8326def ParOr(*ts, **ks):
8327 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
8328
8329 >>> x = Int('x')
8330 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
8331 >>> t(x + 1 == 2)
8332 [[x == 1]]
8333 """
8334 if z3_debug():
8335 _z3_assert(len(ts) >= 2, "At least two arguments expected")
8336 ctx = _get_ctx(ks.get("ctx", None))
8337 ts = [_to_tactic(t, ctx) for t in ts]
8338 sz = len(ts)
8339 _args = (TacticObj * sz)()
8340 for i in range(sz):
8341 _args[i] = ts[i].tactic
8342 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
8343
8344
8345def ParThen(t1, t2, ctx=None):
8346 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
8347 The subgoals are processed in parallel.
8348
8349 >>> x, y = Ints('x y')
8350 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
8351 >>> t(And(Or(x == 1, x == 2), y == x + 1))
8352 [[x == 1, y == 2], [x == 2, y == 3]]
8353 """
8354 t1 = _to_tactic(t1, ctx)
8355 t2 = _to_tactic(t2, ctx)
8356 if z3_debug():
8357 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
8358 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
8359
8360
8361def ParAndThen(t1, t2, ctx=None):
8362 """Alias for ParThen(t1, t2, ctx)."""
8363 return ParThen(t1, t2, ctx)
8364
8365
8366def With(t, *args, **keys):
8367 """Return a tactic that applies tactic `t` using the given configuration options.
8368
8369 >>> x, y = Ints('x y')
8370 >>> t = With(Tactic('simplify'), som=True)
8371 >>> t((x + 1)*(y + 2) == 0)
8372 [[2*x + y + x*y == -2]]
8373 """
8374 ctx = keys.pop("ctx", None)
8375 t = _to_tactic(t, ctx)
8376 p = args2params(args, keys, t.ctx)
8377 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8378
8379
8380def WithParams(t, p):
8381 """Return a tactic that applies tactic `t` using the given configuration options.
8382
8383 >>> x, y = Ints('x y')
8384 >>> p = ParamsRef()
8385 >>> p.set("som", True)
8386 >>> t = WithParams(Tactic('simplify'), p)
8387 >>> t((x + 1)*(y + 2) == 0)
8388 [[2*x + y + x*y == -2]]
8389 """
8390 t = _to_tactic(t, None)
8391 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
8392
8393
8394def Repeat(t, max=4294967295, ctx=None):
8395 """Return a tactic that keeps applying `t` until the goal is not modified anymore
8396 or the maximum number of iterations `max` is reached.
8397
8398 >>> x, y = Ints('x y')
8399 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
8400 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
8401 >>> r = t(c)
8402 >>> for subgoal in r: print(subgoal)
8403 [x == 0, y == 0, x > y]
8404 [x == 0, y == 1, x > y]
8405 [x == 1, y == 0, x > y]
8406 [x == 1, y == 1, x > y]
8407 >>> t = Then(t, Tactic('propagate-values'))
8408 >>> t(c)
8409 [[x == 1, y == 0]]
8410 """
8411 t = _to_tactic(t, ctx)
8412 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
8413
8414
8415def TryFor(t, ms, ctx=None):
8416 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
8417
8418 If `t` does not terminate in `ms` milliseconds, then it fails.
8419 """
8420 t = _to_tactic(t, ctx)
8421 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
8422
8423
8424def tactics(ctx=None):
8425 """Return a list of all available tactics in Z3.
8426
8427 >>> l = tactics()
8428 >>> l.count('simplify') == 1
8429 True
8430 """
8431 ctx = _get_ctx(ctx)
8432 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
8433
8434
8435def tactic_description(name, ctx=None):
8436 """Return a short description for the tactic named `name`.
8437
8438 >>> d = tactic_description('simplify')
8439 """
8440 ctx = _get_ctx(ctx)
8441 return Z3_tactic_get_descr(ctx.ref(), name)
8442
8443
8445 """Display a (tabular) description of all available tactics in Z3."""
8446 if in_html_mode():
8447 even = True
8448 print('<table border="1" cellpadding="2" cellspacing="0">')
8449 for t in tactics():
8450 if even:
8451 print('<tr style="background-color:#CFCFCF">')
8452 even = False
8453 else:
8454 print("<tr>")
8455 even = True
8456 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
8457 print("</table>")
8458 else:
8459 for t in tactics():
8460 print("%s : %s" % (t, tactic_description(t)))
8461
8462
8463class Probe:
8464 """Probes are used to inspect a goal (aka problem) and collect information that may be used
8465 to decide which solver and/or preprocessing step will be used.
8466 """
8467
8468 def __init__(self, probe, ctx=None):
8469 self.ctx = _get_ctx(ctx)
8470 self.probe = None
8471 if isinstance(probe, ProbeObj):
8472 self.probe = probe
8473 elif isinstance(probe, float):
8474 self.probe = Z3_probe_const(self.ctx.ref(), probe)
8475 elif _is_int(probe):
8476 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
8477 elif isinstance(probe, bool):
8478 if probe:
8479 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
8480 else:
8481 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
8482 else:
8483 if z3_debug():
8484 _z3_assert(isinstance(probe, str), "probe name expected")
8485 try:
8486 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
8487 except Z3Exception:
8488 raise Z3Exception("unknown probe '%s'" % probe)
8489 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
8490
8491 def __deepcopy__(self, memo={}):
8492 return Probe(self.probe, self.ctx)
8493
8494 def __del__(self):
8495 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
8496 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
8497
8498 def __lt__(self, other):
8499 """Return a probe that evaluates to "true" when the value returned by `self`
8500 is less than the value returned by `other`.
8501
8502 >>> p = Probe('size') < 10
8503 >>> x = Int('x')
8504 >>> g = Goal()
8505 >>> g.add(x > 0)
8506 >>> g.add(x < 10)
8507 >>> p(g)
8508 1.0
8509 """
8510 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8511
8512 def __gt__(self, other):
8513 """Return a probe that evaluates to "true" when the value returned by `self`
8514 is greater than the value returned by `other`.
8515
8516 >>> p = Probe('size') > 10
8517 >>> x = Int('x')
8518 >>> g = Goal()
8519 >>> g.add(x > 0)
8520 >>> g.add(x < 10)
8521 >>> p(g)
8522 0.0
8523 """
8524 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8525
8526 def __le__(self, other):
8527 """Return a probe that evaluates to "true" when the value returned by `self`
8528 is less than or equal to the value returned by `other`.
8529
8530 >>> p = Probe('size') <= 2
8531 >>> x = Int('x')
8532 >>> g = Goal()
8533 >>> g.add(x > 0)
8534 >>> g.add(x < 10)
8535 >>> p(g)
8536 1.0
8537 """
8538 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8539
8540 def __ge__(self, other):
8541 """Return a probe that evaluates to "true" when the value returned by `self`
8542 is greater than or equal to the value returned by `other`.
8543
8544 >>> p = Probe('size') >= 2
8545 >>> x = Int('x')
8546 >>> g = Goal()
8547 >>> g.add(x > 0)
8548 >>> g.add(x < 10)
8549 >>> p(g)
8550 1.0
8551 """
8552 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8553
8554 def __eq__(self, other):
8555 """Return a probe that evaluates to "true" when the value returned by `self`
8556 is equal to the value returned by `other`.
8557
8558 >>> p = Probe('size') == 2
8559 >>> x = Int('x')
8560 >>> g = Goal()
8561 >>> g.add(x > 0)
8562 >>> g.add(x < 10)
8563 >>> p(g)
8564 1.0
8565 """
8566 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8567
8568 def __ne__(self, other):
8569 """Return a probe that evaluates to "true" when the value returned by `self`
8570 is not equal to the value returned by `other`.
8571
8572 >>> p = Probe('size') != 2
8573 >>> x = Int('x')
8574 >>> g = Goal()
8575 >>> g.add(x > 0)
8576 >>> g.add(x < 10)
8577 >>> p(g)
8578 0.0
8579 """
8580 p = self.__eq__(other)
8581 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8582
8583 def __call__(self, goal):
8584 """Evaluate the probe `self` in the given goal.
8585
8586 >>> p = Probe('size')
8587 >>> x = Int('x')
8588 >>> g = Goal()
8589 >>> g.add(x > 0)
8590 >>> g.add(x < 10)
8591 >>> p(g)
8592 2.0
8593 >>> g.add(x < 20)
8594 >>> p(g)
8595 3.0
8596 >>> p = Probe('num-consts')
8597 >>> p(g)
8598 1.0
8599 >>> p = Probe('is-propositional')
8600 >>> p(g)
8601 0.0
8602 >>> p = Probe('is-qflia')
8603 >>> p(g)
8604 1.0
8605 """
8606 if z3_debug():
8607 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
8608 goal = _to_goal(goal)
8609 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8610
8611
8613 """Return `True` if `p` is a Z3 probe.
8614
8615 >>> is_probe(Int('x'))
8616 False
8617 >>> is_probe(Probe('memory'))
8618 True
8619 """
8620 return isinstance(p, Probe)
8621
8622
8623def _to_probe(p, ctx=None):
8624 if is_probe(p):
8625 return p
8626 else:
8627 return Probe(p, ctx)
8628
8629
8630def probes(ctx=None):
8631 """Return a list of all available probes in Z3.
8632
8633 >>> l = probes()
8634 >>> l.count('memory') == 1
8635 True
8636 """
8637 ctx = _get_ctx(ctx)
8638 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
8639
8640
8641def probe_description(name, ctx=None):
8642 """Return a short description for the probe named `name`.
8643
8644 >>> d = probe_description('memory')
8645 """
8646 ctx = _get_ctx(ctx)
8647 return Z3_probe_get_descr(ctx.ref(), name)
8648
8649
8651 """Display a (tabular) description of all available probes in Z3."""
8652 if in_html_mode():
8653 even = True
8654 print('<table border="1" cellpadding="2" cellspacing="0">')
8655 for p in probes():
8656 if even:
8657 print('<tr style="background-color:#CFCFCF">')
8658 even = False
8659 else:
8660 print("<tr>")
8661 even = True
8662 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
8663 print("</table>")
8664 else:
8665 for p in probes():
8666 print("%s : %s" % (p, probe_description(p)))
8667
8668
8669def _probe_nary(f, args, ctx):
8670 if z3_debug():
8671 _z3_assert(len(args) > 0, "At least one argument expected")
8672 num = len(args)
8673 r = _to_probe(args[0], ctx)
8674 for i in range(num - 1):
8675 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
8676 return r
8677
8678
8679def _probe_and(args, ctx):
8680 return _probe_nary(Z3_probe_and, args, ctx)
8681
8682
8683def _probe_or(args, ctx):
8684 return _probe_nary(Z3_probe_or, args, ctx)
8685
8686
8687def FailIf(p, ctx=None):
8688 """Return a tactic that fails if the probe `p` evaluates to true.
8689 Otherwise, it returns the input goal unmodified.
8690
8691 In the following example, the tactic applies 'simplify' if and only if there are
8692 more than 2 constraints in the goal.
8693
8694 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8695 >>> x, y = Ints('x y')
8696 >>> g = Goal()
8697 >>> g.add(x > 0)
8698 >>> g.add(y > 0)
8699 >>> t(g)
8700 [[x > 0, y > 0]]
8701 >>> g.add(x == y + 1)
8702 >>> t(g)
8703 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8704 """
8705 p = _to_probe(p, ctx)
8706 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8707
8708
8709def When(p, t, ctx=None):
8710 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
8711 Otherwise, it returns the input goal unmodified.
8712
8713 >>> t = When(Probe('size') > 2, Tactic('simplify'))
8714 >>> x, y = Ints('x y')
8715 >>> g = Goal()
8716 >>> g.add(x > 0)
8717 >>> g.add(y > 0)
8718 >>> t(g)
8719 [[x > 0, y > 0]]
8720 >>> g.add(x == y + 1)
8721 >>> t(g)
8722 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8723 """
8724 p = _to_probe(p, ctx)
8725 t = _to_tactic(t, ctx)
8726 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8727
8728
8729def Cond(p, t1, t2, ctx=None):
8730 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8731
8732 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8733 """
8734 p = _to_probe(p, ctx)
8735 t1 = _to_tactic(t1, ctx)
8736 t2 = _to_tactic(t2, ctx)
8737 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8738
8739
8744
8745
8746def simplify(a, *arguments, **keywords):
8747 """Simplify the expression `a` using the given options.
8748
8749 This function has many options. Use `help_simplify` to obtain the complete list.
8750
8751 >>> x = Int('x')
8752 >>> y = Int('y')
8753 >>> simplify(x + 1 + y + x + 1)
8754 2 + 2*x + y
8755 >>> simplify((x + 1)*(y + 1), som=True)
8756 1 + x + y + x*y
8757 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8758 And(Not(x == y), Not(x == 1), Not(y == 1))
8759 >>> simplify(And(x == 0, y == 1), elim_and=True)
8760 Not(Or(Not(x == 0), Not(y == 1)))
8761 """
8762 if z3_debug():
8763 _z3_assert(is_expr(a), "Z3 expression expected")
8764 if len(arguments) > 0 or len(keywords) > 0:
8765 p = args2params(arguments, keywords, a.ctx)
8766 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8767 else:
8768 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8769
8770
8772 """Return a string describing all options available for Z3 `simplify` procedure."""
8773 print(Z3_simplify_get_help(main_ctx().ref()))
8774
8775
8777 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8779
8780
8781def substitute(t, *m):
8782 """Apply substitution m on t, m is a list of pairs of the form (from, to).
8783 Every occurrence in t of from is replaced with to.
8784
8785 >>> x = Int('x')
8786 >>> y = Int('y')
8787 >>> substitute(x + 1, (x, y + 1))
8788 y + 1 + 1
8789 >>> f = Function('f', IntSort(), IntSort())
8790 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8791 1 + 1
8792 """
8793 if isinstance(m, tuple):
8794 m1 = _get_args(m)
8795 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8796 m = m1
8797 if z3_debug():
8798 _z3_assert(is_expr(t), "Z3 expression expected")
8799 _z3_assert(
8800 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
8801 "Z3 invalid substitution, expression pairs expected.")
8802 _z3_assert(
8803 all([p[0].sort().eq(p[1].sort()) for p in m]),
8804 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
8805 num = len(m)
8806 _from = (Ast * num)()
8807 _to = (Ast * num)()
8808 for i in range(num):
8809 _from[i] = m[i][0].as_ast()
8810 _to[i] = m[i][1].as_ast()
8811 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8812
8813
8815 """Substitute the free variables in t with the expression in m.
8816
8817 >>> v0 = Var(0, IntSort())
8818 >>> v1 = Var(1, IntSort())
8819 >>> x = Int('x')
8820 >>> f = Function('f', IntSort(), IntSort(), IntSort())
8821 >>> # replace v0 with x+1 and v1 with x
8822 >>> substitute_vars(f(v0, v1), x + 1, x)
8823 f(x + 1, x)
8824 """
8825 if z3_debug():
8826 _z3_assert(is_expr(t), "Z3 expression expected")
8827 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8828 num = len(m)
8829 _to = (Ast * num)()
8830 for i in range(num):
8831 _to[i] = m[i].as_ast()
8832 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8833
8835 """Apply subistitution m on t, m is a list of pairs of a function and expression (from, to)
8836 Every occurrence in to of the function from is replaced with the expression to.
8837 The expression to can have free variables, that refer to the arguments of from.
8838 For examples, see
8839 """
8840 if isinstance(m, tuple):
8841 m1 = _get_args(m)
8842 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8843 m = m1
8844 if z3_debug():
8845 _z3_assert(is_expr(t), "Z3 expression expected")
8846 _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.")
8847 num = len(m)
8848 _from = (FuncDecl * num)()
8849 _to = (Ast * num)()
8850 for i in range(num):
8851 _from[i] = m[i][0].as_func_decl()
8852 _to[i] = m[i][1].as_ast()
8853 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8854
8855
8856def Sum(*args):
8857 """Create the sum of the Z3 expressions.
8858
8859 >>> a, b, c = Ints('a b c')
8860 >>> Sum(a, b, c)
8861 a + b + c
8862 >>> Sum([a, b, c])
8863 a + b + c
8864 >>> A = IntVector('a', 5)
8865 >>> Sum(A)
8866 a__0 + a__1 + a__2 + a__3 + a__4
8867 """
8868 args = _get_args(args)
8869 if len(args) == 0:
8870 return 0
8871 ctx = _ctx_from_ast_arg_list(args)
8872 if ctx is None:
8873 return _reduce(lambda a, b: a + b, args, 0)
8874 args = _coerce_expr_list(args, ctx)
8875 if is_bv(args[0]):
8876 return _reduce(lambda a, b: a + b, args, 0)
8877 else:
8878 _args, sz = _to_ast_array(args)
8879 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8880
8881
8882def Product(*args):
8883 """Create the product of the Z3 expressions.
8884
8885 >>> a, b, c = Ints('a b c')
8886 >>> Product(a, b, c)
8887 a*b*c
8888 >>> Product([a, b, c])
8889 a*b*c
8890 >>> A = IntVector('a', 5)
8891 >>> Product(A)
8892 a__0*a__1*a__2*a__3*a__4
8893 """
8894 args = _get_args(args)
8895 if len(args) == 0:
8896 return 1
8897 ctx = _ctx_from_ast_arg_list(args)
8898 if ctx is None:
8899 return _reduce(lambda a, b: a * b, args, 1)
8900 args = _coerce_expr_list(args, ctx)
8901 if is_bv(args[0]):
8902 return _reduce(lambda a, b: a * b, args, 1)
8903 else:
8904 _args, sz = _to_ast_array(args)
8905 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8906
8907def Abs(arg):
8908 """Create the absolute value of an arithmetic expression"""
8909 return If(arg > 0, arg, -arg)
8910
8911
8912def AtMost(*args):
8913 """Create an at-most Pseudo-Boolean k constraint.
8914
8915 >>> a, b, c = Bools('a b c')
8916 >>> f = AtMost(a, b, c, 2)
8917 """
8918 args = _get_args(args)
8919 if z3_debug():
8920 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8921 ctx = _ctx_from_ast_arg_list(args)
8922 if z3_debug():
8923 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8924 args1 = _coerce_expr_list(args[:-1], ctx)
8925 k = args[-1]
8926 _args, sz = _to_ast_array(args1)
8927 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8928
8929
8930def AtLeast(*args):
8931 """Create an at-most Pseudo-Boolean k constraint.
8932
8933 >>> a, b, c = Bools('a b c')
8934 >>> f = AtLeast(a, b, c, 2)
8935 """
8936 args = _get_args(args)
8937 if z3_debug():
8938 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8939 ctx = _ctx_from_ast_arg_list(args)
8940 if z3_debug():
8941 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8942 args1 = _coerce_expr_list(args[:-1], ctx)
8943 k = args[-1]
8944 _args, sz = _to_ast_array(args1)
8945 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8946
8947
8948def _reorder_pb_arg(arg):
8949 a, b = arg
8950 if not _is_int(b) and _is_int(a):
8951 return b, a
8952 return arg
8953
8954
8955def _pb_args_coeffs(args, default_ctx=None):
8956 args = _get_args_ast_list(args)
8957 if len(args) == 0:
8958 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8959 args = [_reorder_pb_arg(arg) for arg in args]
8960 args, coeffs = zip(*args)
8961 if z3_debug():
8962 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8963 ctx = _ctx_from_ast_arg_list(args)
8964 if z3_debug():
8965 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8966 args = _coerce_expr_list(args, ctx)
8967 _args, sz = _to_ast_array(args)
8968 _coeffs = (ctypes.c_int * len(coeffs))()
8969 for i in range(len(coeffs)):
8970 _z3_check_cint_overflow(coeffs[i], "coefficient")
8971 _coeffs[i] = coeffs[i]
8972 return ctx, sz, _args, _coeffs, args
8973
8974
8975def PbLe(args, k):
8976 """Create a Pseudo-Boolean inequality k constraint.
8977
8978 >>> a, b, c = Bools('a b c')
8979 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8980 """
8981 _z3_check_cint_overflow(k, "k")
8982 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8983 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8984
8985
8986def PbGe(args, k):
8987 """Create a Pseudo-Boolean inequality k constraint.
8988
8989 >>> a, b, c = Bools('a b c')
8990 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8991 """
8992 _z3_check_cint_overflow(k, "k")
8993 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
8994 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8995
8996
8997def PbEq(args, k, ctx=None):
8998 """Create a Pseudo-Boolean inequality k constraint.
8999
9000 >>> a, b, c = Bools('a b c')
9001 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9002 """
9003 _z3_check_cint_overflow(k, "k")
9004 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9005 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9006
9007
9008def solve(*args, **keywords):
9009 """Solve the constraints `*args`.
9010
9011 This is a simple function for creating demonstrations. It creates a solver,
9012 configure it using the options in `keywords`, adds the constraints
9013 in `args`, and invokes check.
9014
9015 >>> a = Int('a')
9016 >>> solve(a > 0, a < 2)
9017 [a = 1]
9018 """
9019 show = keywords.pop("show", False)
9020 s = Solver()
9021 s.set(**keywords)
9022 s.add(*args)
9023 if show:
9024 print(s)
9025 r = s.check()
9026 if r == unsat:
9027 print("no solution")
9028 elif r == unknown:
9029 print("failed to solve")
9030 try:
9031 print(s.model())
9032 except Z3Exception:
9033 return
9034 else:
9035 print(s.model())
9036
9037
9038def solve_using(s, *args, **keywords):
9039 """Solve the constraints `*args` using solver `s`.
9040
9041 This is a simple function for creating demonstrations. It is similar to `solve`,
9042 but it uses the given solver `s`.
9043 It configures solver `s` using the options in `keywords`, adds the constraints
9044 in `args`, and invokes check.
9045 """
9046 show = keywords.pop("show", False)
9047 if z3_debug():
9048 _z3_assert(isinstance(s, Solver), "Solver object expected")
9049 s.set(**keywords)
9050 s.add(*args)
9051 if show:
9052 print("Problem:")
9053 print(s)
9054 r = s.check()
9055 if r == unsat:
9056 print("no solution")
9057 elif r == unknown:
9058 print("failed to solve")
9059 try:
9060 print(s.model())
9061 except Z3Exception:
9062 return
9063 else:
9064 if show:
9065 print("Solution:")
9066 print(s.model())
9067
9068
9069def prove(claim, show=False, **keywords):
9070 """Try to prove the given claim.
9071
9072 This is a simple function for creating demonstrations. It tries to prove
9073 `claim` by showing the negation is unsatisfiable.
9074
9075 >>> p, q = Bools('p q')
9076 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9077 proved
9078 """
9079 if z3_debug():
9080 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9081 s = Solver()
9082 s.set(**keywords)
9083 s.add(Not(claim))
9084 if show:
9085 print(s)
9086 r = s.check()
9087 if r == unsat:
9088 print("proved")
9089 elif r == unknown:
9090 print("failed to prove")
9091 print(s.model())
9092 else:
9093 print("counterexample")
9094 print(s.model())
9095
9096
9097def _solve_html(*args, **keywords):
9098 """Version of function `solve` that renders HTML output."""
9099 show = keywords.pop("show", False)
9100 s = Solver()
9101 s.set(**keywords)
9102 s.add(*args)
9103 if show:
9104 print("<b>Problem:</b>")
9105 print(s)
9106 r = s.check()
9107 if r == unsat:
9108 print("<b>no solution</b>")
9109 elif r == unknown:
9110 print("<b>failed to solve</b>")
9111 try:
9112 print(s.model())
9113 except Z3Exception:
9114 return
9115 else:
9116 if show:
9117 print("<b>Solution:</b>")
9118 print(s.model())
9119
9120
9121def _solve_using_html(s, *args, **keywords):
9122 """Version of function `solve_using` that renders HTML."""
9123 show = keywords.pop("show", False)
9124 if z3_debug():
9125 _z3_assert(isinstance(s, Solver), "Solver object expected")
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 _prove_html(claim, show=False, **keywords):
9147 """Version of function `prove` that renders HTML."""
9148 if z3_debug():
9149 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9150 s = Solver()
9151 s.set(**keywords)
9152 s.add(Not(claim))
9153 if show:
9154 print(s)
9155 r = s.check()
9156 if r == unsat:
9157 print("<b>proved</b>")
9158 elif r == unknown:
9159 print("<b>failed to prove</b>")
9160 print(s.model())
9161 else:
9162 print("<b>counterexample</b>")
9163 print(s.model())
9164
9165
9166def _dict2sarray(sorts, ctx):
9167 sz = len(sorts)
9168 _names = (Symbol * sz)()
9169 _sorts = (Sort * sz)()
9170 i = 0
9171 for k in sorts:
9172 v = sorts[k]
9173 if z3_debug():
9174 _z3_assert(isinstance(k, str), "String expected")
9175 _z3_assert(is_sort(v), "Z3 sort expected")
9176 _names[i] = to_symbol(k, ctx)
9177 _sorts[i] = v.ast
9178 i = i + 1
9179 return sz, _names, _sorts
9180
9181
9182def _dict2darray(decls, ctx):
9183 sz = len(decls)
9184 _names = (Symbol * sz)()
9185 _decls = (FuncDecl * sz)()
9186 i = 0
9187 for k in decls:
9188 v = decls[k]
9189 if z3_debug():
9190 _z3_assert(isinstance(k, str), "String expected")
9191 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
9192 _names[i] = to_symbol(k, ctx)
9193 if is_const(v):
9194 _decls[i] = v.decl().ast
9195 else:
9196 _decls[i] = v.ast
9197 i = i + 1
9198 return sz, _names, _decls
9199
9201 def __init__(self, ctx= None):
9202 self.ctx = _get_ctx(ctx)
9203 self.pctx = Z3_mk_parser_context(self.ctx.ref())
9204 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
9205
9206 def __del__(self):
9207 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
9208 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
9209 self.pctx = None
9210
9211 def add_sort(self, sort):
9212 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
9213
9214 def add_decl(self, decl):
9215 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
9216
9217 def from_string(self, s):
9218 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
9219
9220def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
9221 """Parse a string in SMT 2.0 format using the given sorts and decls.
9222
9223 The arguments sorts and decls are Python dictionaries used to initialize
9224 the symbol table used for the SMT 2.0 parser.
9225
9226 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
9227 [x > 0, x < 10]
9228 >>> x, y = Ints('x y')
9229 >>> f = Function('f', IntSort(), IntSort())
9230 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
9231 [x + f(y) > 0]
9232 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
9233 [a > 0]
9234 """
9235 ctx = _get_ctx(ctx)
9236 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9237 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9238 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9239
9240
9241def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
9242 """Parse a file in SMT 2.0 format using the given sorts and decls.
9243
9244 This function is similar to parse_smt2_string().
9245 """
9246 ctx = _get_ctx(ctx)
9247 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
9248 dsz, dnames, ddecls = _dict2darray(decls, ctx)
9249 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
9250
9251
9252
9257
9258
9259# Global default rounding mode
9260_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
9261_dflt_fpsort_ebits = 11
9262_dflt_fpsort_sbits = 53
9263
9264
9266 """Retrieves the global default rounding mode."""
9267 global _dflt_rounding_mode
9268 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
9269 return RTZ(ctx)
9270 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
9271 return RTN(ctx)
9272 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
9273 return RTP(ctx)
9274 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
9275 return RNE(ctx)
9276 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
9277 return RNA(ctx)
9278
9279
9280_ROUNDING_MODES = frozenset({
9281 Z3_OP_FPA_RM_TOWARD_ZERO,
9282 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
9283 Z3_OP_FPA_RM_TOWARD_POSITIVE,
9284 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
9285 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
9286})
9287
9288
9290 global _dflt_rounding_mode
9291 if is_fprm_value(rm):
9292 _dflt_rounding_mode = rm.decl().kind()
9293 else:
9294 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
9295 _dflt_rounding_mode = rm
9296
9297
9299 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
9300
9301
9302def set_default_fp_sort(ebits, sbits, ctx=None):
9303 global _dflt_fpsort_ebits
9304 global _dflt_fpsort_sbits
9305 _dflt_fpsort_ebits = ebits
9306 _dflt_fpsort_sbits = sbits
9307
9308
9309def _dflt_rm(ctx=None):
9310 return get_default_rounding_mode(ctx)
9311
9312
9313def _dflt_fps(ctx=None):
9314 return get_default_fp_sort(ctx)
9315
9316
9317def _coerce_fp_expr_list(alist, ctx):
9318 first_fp_sort = None
9319 for a in alist:
9320 if is_fp(a):
9321 if first_fp_sort is None:
9322 first_fp_sort = a.sort()
9323 elif first_fp_sort == a.sort():
9324 pass # OK, same as before
9325 else:
9326 # we saw at least 2 different float sorts; something will
9327 # throw a sort mismatch later, for now assume None.
9328 first_fp_sort = None
9329 break
9330
9331 r = []
9332 for i in range(len(alist)):
9333 a = alist[i]
9334 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
9335 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
9336 r.append(FPVal(a, None, first_fp_sort, ctx))
9337 else:
9338 r.append(a)
9339 return _coerce_expr_list(r, ctx)
9340
9341
9342# FP Sorts
9343
9345 """Floating-point sort."""
9346
9347 def ebits(self):
9348 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
9349 >>> b = FPSort(8, 24)
9350 >>> b.ebits()
9351 8
9352 """
9353 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
9354
9355 def sbits(self):
9356 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
9357 >>> b = FPSort(8, 24)
9358 >>> b.sbits()
9359 24
9360 """
9361 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
9362
9363 def cast(self, val):
9364 """Try to cast `val` as a floating-point expression.
9365 >>> b = FPSort(8, 24)
9366 >>> b.cast(1.0)
9367 1
9368 >>> b.cast(1.0).sexpr()
9369 '(fp #b0 #x7f #b00000000000000000000000)'
9370 """
9371 if is_expr(val):
9372 if z3_debug():
9373 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
9374 return val
9375 else:
9376 return FPVal(val, None, self, self.ctxctx)
9377
9378
9379def Float16(ctx=None):
9380 """Floating-point 16-bit (half) sort."""
9381 ctx = _get_ctx(ctx)
9382 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
9383
9384
9385def FloatHalf(ctx=None):
9386 """Floating-point 16-bit (half) sort."""
9387 ctx = _get_ctx(ctx)
9388 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
9389
9390
9391def Float32(ctx=None):
9392 """Floating-point 32-bit (single) sort."""
9393 ctx = _get_ctx(ctx)
9394 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
9395
9396
9397def FloatSingle(ctx=None):
9398 """Floating-point 32-bit (single) sort."""
9399 ctx = _get_ctx(ctx)
9400 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
9401
9402
9403def Float64(ctx=None):
9404 """Floating-point 64-bit (double) sort."""
9405 ctx = _get_ctx(ctx)
9406 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
9407
9408
9409def FloatDouble(ctx=None):
9410 """Floating-point 64-bit (double) sort."""
9411 ctx = _get_ctx(ctx)
9412 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
9413
9414
9415def Float128(ctx=None):
9416 """Floating-point 128-bit (quadruple) sort."""
9417 ctx = _get_ctx(ctx)
9418 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
9419
9420
9421def FloatQuadruple(ctx=None):
9422 """Floating-point 128-bit (quadruple) sort."""
9423 ctx = _get_ctx(ctx)
9424 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
9425
9426
9428 """"Floating-point rounding mode sort."""
9429
9430
9432 """Return True if `s` is a Z3 floating-point sort.
9433
9434 >>> is_fp_sort(FPSort(8, 24))
9435 True
9436 >>> is_fp_sort(IntSort())
9437 False
9438 """
9439 return isinstance(s, FPSortRef)
9440
9441
9443 """Return True if `s` is a Z3 floating-point rounding mode sort.
9444
9445 >>> is_fprm_sort(FPSort(8, 24))
9446 False
9447 >>> is_fprm_sort(RNE().sort())
9448 True
9449 """
9450 return isinstance(s, FPRMSortRef)
9451
9452# FP Expressions
9453
9454
9456 """Floating-point expressions."""
9457
9458 def sort(self):
9459 """Return the sort of the floating-point expression `self`.
9460
9461 >>> x = FP('1.0', FPSort(8, 24))
9462 >>> x.sort()
9463 FPSort(8, 24)
9464 >>> x.sort() == FPSort(8, 24)
9465 True
9466 """
9467 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
9468
9469 def ebits(self):
9470 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9471 >>> b = FPSort(8, 24)
9472 >>> b.ebits()
9473 8
9474 """
9475 return self.sortsort().ebits()
9476
9477 def sbits(self):
9478 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
9479 >>> b = FPSort(8, 24)
9480 >>> b.sbits()
9481 24
9482 """
9483 return self.sortsort().sbits()
9484
9485 def as_string(self):
9486 """Return a Z3 floating point expression as a Python string."""
9487 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9488
9489 def __le__(self, other):
9490 return fpLEQ(self, other, self.ctx)
9491
9492 def __lt__(self, other):
9493 return fpLT(self, other, self.ctx)
9494
9495 def __ge__(self, other):
9496 return fpGEQ(self, other, self.ctx)
9497
9498 def __gt__(self, other):
9499 return fpGT(self, other, self.ctx)
9500
9501 def __add__(self, other):
9502 """Create the Z3 expression `self + other`.
9503
9504 >>> x = FP('x', FPSort(8, 24))
9505 >>> y = FP('y', FPSort(8, 24))
9506 >>> x + y
9507 x + y
9508 >>> (x + y).sort()
9509 FPSort(8, 24)
9510 """
9511 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9512 return fpAdd(_dflt_rm(), a, b, self.ctx)
9513
9514 def __radd__(self, other):
9515 """Create the Z3 expression `other + self`.
9516
9517 >>> x = FP('x', FPSort(8, 24))
9518 >>> 10 + x
9519 1.25*(2**3) + x
9520 """
9521 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9522 return fpAdd(_dflt_rm(), a, b, self.ctx)
9523
9524 def __sub__(self, other):
9525 """Create the Z3 expression `self - other`.
9526
9527 >>> x = FP('x', FPSort(8, 24))
9528 >>> y = FP('y', FPSort(8, 24))
9529 >>> x - y
9530 x - y
9531 >>> (x - y).sort()
9532 FPSort(8, 24)
9533 """
9534 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9535 return fpSub(_dflt_rm(), a, b, self.ctx)
9536
9537 def __rsub__(self, other):
9538 """Create the Z3 expression `other - self`.
9539
9540 >>> x = FP('x', FPSort(8, 24))
9541 >>> 10 - x
9542 1.25*(2**3) - x
9543 """
9544 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9545 return fpSub(_dflt_rm(), a, b, self.ctx)
9546
9547 def __mul__(self, other):
9548 """Create the Z3 expression `self * other`.
9549
9550 >>> x = FP('x', FPSort(8, 24))
9551 >>> y = FP('y', FPSort(8, 24))
9552 >>> x * y
9553 x * y
9554 >>> (x * y).sort()
9555 FPSort(8, 24)
9556 >>> 10 * y
9557 1.25*(2**3) * y
9558 """
9559 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9560 return fpMul(_dflt_rm(), a, b, self.ctx)
9561
9562 def __rmul__(self, other):
9563 """Create the Z3 expression `other * self`.
9564
9565 >>> x = FP('x', FPSort(8, 24))
9566 >>> y = FP('y', FPSort(8, 24))
9567 >>> x * y
9568 x * y
9569 >>> x * 10
9570 x * 1.25*(2**3)
9571 """
9572 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9573 return fpMul(_dflt_rm(), a, b, self.ctx)
9574
9575 def __pos__(self):
9576 """Create the Z3 expression `+self`."""
9577 return self
9578
9579 def __neg__(self):
9580 """Create the Z3 expression `-self`.
9581
9582 >>> x = FP('x', Float32())
9583 >>> -x
9584 -x
9585 """
9586 return fpNeg(self)
9587
9588 def __div__(self, other):
9589 """Create the Z3 expression `self / other`.
9590
9591 >>> x = FP('x', FPSort(8, 24))
9592 >>> y = FP('y', FPSort(8, 24))
9593 >>> x / y
9594 x / y
9595 >>> (x / y).sort()
9596 FPSort(8, 24)
9597 >>> 10 / y
9598 1.25*(2**3) / y
9599 """
9600 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
9601 return fpDiv(_dflt_rm(), a, b, self.ctx)
9602
9603 def __rdiv__(self, other):
9604 """Create the Z3 expression `other / self`.
9605
9606 >>> x = FP('x', FPSort(8, 24))
9607 >>> y = FP('y', FPSort(8, 24))
9608 >>> x / y
9609 x / y
9610 >>> x / 10
9611 x / 1.25*(2**3)
9612 """
9613 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
9614 return fpDiv(_dflt_rm(), a, b, self.ctx)
9615
9616 def __truediv__(self, other):
9617 """Create the Z3 expression division `self / other`."""
9618 return self.__div__(other)
9619
9620 def __rtruediv__(self, other):
9621 """Create the Z3 expression division `other / self`."""
9622 return self.__rdiv__(other)
9623
9624 def __mod__(self, other):
9625 """Create the Z3 expression mod `self % other`."""
9626 return fpRem(self, other)
9627
9628 def __rmod__(self, other):
9629 """Create the Z3 expression mod `other % self`."""
9630 return fpRem(other, self)
9631
9632
9634 """Floating-point rounding mode expressions"""
9635
9636 def as_string(self):
9637 """Return a Z3 floating point expression as a Python string."""
9638 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
9639
9640
9642 ctx = _get_ctx(ctx)
9643 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9644
9645
9646def RNE(ctx=None):
9647 ctx = _get_ctx(ctx)
9648 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
9649
9650
9652 ctx = _get_ctx(ctx)
9653 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9654
9655
9656def RNA(ctx=None):
9657 ctx = _get_ctx(ctx)
9658 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
9659
9660
9662 ctx = _get_ctx(ctx)
9663 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9664
9665
9666def RTP(ctx=None):
9667 ctx = _get_ctx(ctx)
9668 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9669
9670
9672 ctx = _get_ctx(ctx)
9673 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9674
9675
9676def RTN(ctx=None):
9677 ctx = _get_ctx(ctx)
9678 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9679
9680
9681def RoundTowardZero(ctx=None):
9682 ctx = _get_ctx(ctx)
9683 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9684
9685
9686def RTZ(ctx=None):
9687 ctx = _get_ctx(ctx)
9688 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9689
9690
9691def is_fprm(a):
9692 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9693
9694 >>> rm = RNE()
9695 >>> is_fprm(rm)
9696 True
9697 >>> rm = 1.0
9698 >>> is_fprm(rm)
9699 False
9700 """
9701 return isinstance(a, FPRMRef)
9702
9703
9705 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9706 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9707
9708# FP Numerals
9709
9710
9712 """The sign of the numeral.
9713
9714 >>> x = FPVal(+1.0, FPSort(8, 24))
9715 >>> x.sign()
9716 False
9717 >>> x = FPVal(-1.0, FPSort(8, 24))
9718 >>> x.sign()
9719 True
9720 """
9721
9722 def sign(self):
9723 num = (ctypes.c_int)()
9724 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_astas_ast(), byref(num))
9725 if nsign is False:
9726 raise Z3Exception("error retrieving the sign of a numeral.")
9727 return num.value != 0
9728
9729 """The sign of a floating-point numeral as a bit-vector expression.
9730
9731 Remark: NaN's are invalid arguments.
9732 """
9733
9734 def sign_as_bv(self):
9735 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9736
9737 """The significand of the numeral.
9738
9739 >>> x = FPVal(2.5, FPSort(8, 24))
9740 >>> x.significand()
9741 1.25
9742 """
9743
9744 def significand(self):
9745 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_astas_ast())
9746
9747 """The significand of the numeral as a long.
9748
9749 >>> x = FPVal(2.5, FPSort(8, 24))
9750 >>> x.significand_as_long()
9751 1.25
9752 """
9753
9755 ptr = (ctypes.c_ulonglong * 1)()
9756 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_astas_ast(), ptr):
9757 raise Z3Exception("error retrieving the significand of a numeral.")
9758 return ptr[0]
9759
9760 """The significand of the numeral as a bit-vector expression.
9761
9762 Remark: NaN are invalid arguments.
9763 """
9764
9766 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9767
9768 """The exponent of the numeral.
9769
9770 >>> x = FPVal(2.5, FPSort(8, 24))
9771 >>> x.exponent()
9772 1
9773 """
9774
9775 def exponent(self, biased=True):
9776 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_astas_ast(), biased)
9777
9778 """The exponent of the numeral as a long.
9779
9780 >>> x = FPVal(2.5, FPSort(8, 24))
9781 >>> x.exponent_as_long()
9782 1
9783 """
9784
9785 def exponent_as_long(self, biased=True):
9786 ptr = (ctypes.c_longlong * 1)()
9787 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_astas_ast(), ptr, biased):
9788 raise Z3Exception("error retrieving the exponent of a numeral.")
9789 return ptr[0]
9790
9791 """The exponent of the numeral as a bit-vector expression.
9792
9793 Remark: NaNs are invalid arguments.
9794 """
9795
9796 def exponent_as_bv(self, biased=True):
9797 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_astas_ast(), biased), self.ctx)
9798
9799 """Indicates whether the numeral is a NaN."""
9800
9801 def isNaN(self):
9802 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_astas_ast())
9803
9804 """Indicates whether the numeral is +oo or -oo."""
9805
9806 def isInf(self):
9807 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_astas_ast())
9808
9809 """Indicates whether the numeral is +zero or -zero."""
9810
9811 def isZero(self):
9812 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_astas_ast())
9813
9814 """Indicates whether the numeral is normal."""
9815
9816 def isNormal(self):
9817 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_astas_ast())
9818
9819 """Indicates whether the numeral is subnormal."""
9820
9821 def isSubnormal(self):
9822 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_astas_ast())
9823
9824 """Indicates whether the numeral is positive."""
9825
9826 def isPositive(self):
9827 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_astas_ast())
9828
9829 """Indicates whether the numeral is negative."""
9830
9831 def isNegative(self):
9832 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_astas_ast())
9833
9834 """
9835 The string representation of the numeral.
9836
9837 >>> x = FPVal(20, FPSort(8, 24))
9838 >>> x.as_string()
9839 1.25*(2**4)
9840 """
9841
9842 def as_string(self):
9843 s = Z3_get_numeral_string(self.ctx.ref(), self.as_astas_ast())
9844 return ("FPVal(%s, %s)" % (s, self.sortsort()))
9845
9846
9847def is_fp(a):
9848 """Return `True` if `a` is a Z3 floating-point expression.
9849
9850 >>> b = FP('b', FPSort(8, 24))
9851 >>> is_fp(b)
9852 True
9853 >>> is_fp(b + 1.0)
9854 True
9855 >>> is_fp(Int('x'))
9856 False
9857 """
9858 return isinstance(a, FPRef)
9859
9860
9862 """Return `True` if `a` is a Z3 floating-point numeral value.
9863
9864 >>> b = FP('b', FPSort(8, 24))
9865 >>> is_fp_value(b)
9866 False
9867 >>> b = FPVal(1.0, FPSort(8, 24))
9868 >>> b
9869 1
9870 >>> is_fp_value(b)
9871 True
9872 """
9873 return is_fp(a) and _is_numeral(a.ctx, a.ast)
9874
9875
9876def FPSort(ebits, sbits, ctx=None):
9877 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9878
9879 >>> Single = FPSort(8, 24)
9880 >>> Double = FPSort(11, 53)
9881 >>> Single
9882 FPSort(8, 24)
9883 >>> x = Const('x', Single)
9884 >>> eq(x, FP('x', FPSort(8, 24)))
9885 True
9886 """
9887 ctx = _get_ctx(ctx)
9888 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9889
9890
9891def _to_float_str(val, exp=0):
9892 if isinstance(val, float):
9893 if math.isnan(val):
9894 res = "NaN"
9895 elif val == 0.0:
9896 sone = math.copysign(1.0, val)
9897 if sone < 0.0:
9898 return "-0.0"
9899 else:
9900 return "+0.0"
9901 elif val == float("+inf"):
9902 res = "+oo"
9903 elif val == float("-inf"):
9904 res = "-oo"
9905 else:
9906 v = val.as_integer_ratio()
9907 num = v[0]
9908 den = v[1]
9909 rvs = str(num) + "/" + str(den)
9910 res = rvs + "p" + _to_int_str(exp)
9911 elif isinstance(val, bool):
9912 if val:
9913 res = "1.0"
9914 else:
9915 res = "0.0"
9916 elif _is_int(val):
9917 res = str(val)
9918 elif isinstance(val, str):
9919 inx = val.find("*(2**")
9920 if inx == -1:
9921 res = val
9922 elif val[-1] == ")":
9923 res = val[0:inx]
9924 exp = str(int(val[inx + 5:-1]) + int(exp))
9925 else:
9926 _z3_assert(False, "String does not have floating-point numeral form.")
9927 elif z3_debug():
9928 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9929 if exp == 0:
9930 return res
9931 else:
9932 return res + "p" + exp
9933
9934
9935def fpNaN(s):
9936 """Create a Z3 floating-point NaN term.
9937
9938 >>> s = FPSort(8, 24)
9939 >>> set_fpa_pretty(True)
9940 >>> fpNaN(s)
9941 NaN
9942 >>> pb = get_fpa_pretty()
9943 >>> set_fpa_pretty(False)
9944 >>> fpNaN(s)
9945 fpNaN(FPSort(8, 24))
9946 >>> set_fpa_pretty(pb)
9947 """
9948 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9949 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9950
9951
9953 """Create a Z3 floating-point +oo term.
9954
9955 >>> s = FPSort(8, 24)
9956 >>> pb = get_fpa_pretty()
9957 >>> set_fpa_pretty(True)
9958 >>> fpPlusInfinity(s)
9959 +oo
9960 >>> set_fpa_pretty(False)
9961 >>> fpPlusInfinity(s)
9962 fpPlusInfinity(FPSort(8, 24))
9963 >>> set_fpa_pretty(pb)
9964 """
9965 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9966 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9967
9968
9970 """Create a Z3 floating-point -oo term."""
9971 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9972 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9973
9974
9975def fpInfinity(s, negative):
9976 """Create a Z3 floating-point +oo or -oo term."""
9977 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9978 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9979 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9980
9981
9983 """Create a Z3 floating-point +0.0 term."""
9984 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9985 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9986
9987
9989 """Create a Z3 floating-point -0.0 term."""
9990 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9991 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9992
9993
9994def fpZero(s, negative):
9995 """Create a Z3 floating-point +0.0 or -0.0 term."""
9996 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9997 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9998 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9999
10000
10001def FPVal(sig, exp=None, fps=None, ctx=None):
10002 """Return a floating-point value of value `val` and sort `fps`.
10003 If `ctx=None`, then the global context is used.
10004
10005 >>> v = FPVal(20.0, FPSort(8, 24))
10006 >>> v
10007 1.25*(2**4)
10008 >>> print("0x%.8x" % v.exponent_as_long(False))
10009 0x00000004
10010 >>> v = FPVal(2.25, FPSort(8, 24))
10011 >>> v
10012 1.125*(2**1)
10013 >>> v = FPVal(-2.25, FPSort(8, 24))
10014 >>> v
10015 -1.125*(2**1)
10016 >>> FPVal(-0.0, FPSort(8, 24))
10017 -0.0
10018 >>> FPVal(0.0, FPSort(8, 24))
10019 +0.0
10020 >>> FPVal(+0.0, FPSort(8, 24))
10021 +0.0
10022 """
10023 ctx = _get_ctx(ctx)
10024 if is_fp_sort(exp):
10025 fps = exp
10026 exp = None
10027 elif fps is None:
10028 fps = _dflt_fps(ctx)
10029 _z3_assert(is_fp_sort(fps), "sort mismatch")
10030 if exp is None:
10031 exp = 0
10032 val = _to_float_str(sig)
10033 if val == "NaN" or val == "nan":
10034 return fpNaN(fps)
10035 elif val == "-0.0":
10036 return fpMinusZero(fps)
10037 elif val == "0.0" or val == "+0.0":
10038 return fpPlusZero(fps)
10039 elif val == "+oo" or val == "+inf" or val == "+Inf":
10040 return fpPlusInfinity(fps)
10041 elif val == "-oo" or val == "-inf" or val == "-Inf":
10042 return fpMinusInfinity(fps)
10043 else:
10044 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10045
10046
10047def FP(name, fpsort, ctx=None):
10048 """Return a floating-point constant named `name`.
10049 `fpsort` is the floating-point sort.
10050 If `ctx=None`, then the global context is used.
10051
10052 >>> x = FP('x', FPSort(8, 24))
10053 >>> is_fp(x)
10054 True
10055 >>> x.ebits()
10056 8
10057 >>> x.sort()
10058 FPSort(8, 24)
10059 >>> word = FPSort(8, 24)
10060 >>> x2 = FP('x', word)
10061 >>> eq(x, x2)
10062 True
10063 """
10064 if isinstance(fpsort, FPSortRef) and ctx is None:
10065 ctx = fpsort.ctx
10066 else:
10067 ctx = _get_ctx(ctx)
10068 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10069
10070
10071def FPs(names, fpsort, ctx=None):
10072 """Return an array of floating-point constants.
10073
10074 >>> x, y, z = FPs('x y z', FPSort(8, 24))
10075 >>> x.sort()
10076 FPSort(8, 24)
10077 >>> x.sbits()
10078 24
10079 >>> x.ebits()
10080 8
10081 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10082 fpMul(RNE(), fpAdd(RNE(), x, y), z)
10083 """
10084 ctx = _get_ctx(ctx)
10085 if isinstance(names, str):
10086 names = names.split(" ")
10087 return [FP(name, fpsort, ctx) for name in names]
10088
10089
10090def fpAbs(a, ctx=None):
10091 """Create a Z3 floating-point absolute value expression.
10092
10093 >>> s = FPSort(8, 24)
10094 >>> rm = RNE()
10095 >>> x = FPVal(1.0, s)
10096 >>> fpAbs(x)
10097 fpAbs(1)
10098 >>> y = FPVal(-20.0, s)
10099 >>> y
10100 -1.25*(2**4)
10101 >>> fpAbs(y)
10102 fpAbs(-1.25*(2**4))
10103 >>> fpAbs(-1.25*(2**4))
10104 fpAbs(-1.25*(2**4))
10105 >>> fpAbs(x).sort()
10106 FPSort(8, 24)
10107 """
10108 ctx = _get_ctx(ctx)
10109 [a] = _coerce_fp_expr_list([a], ctx)
10110 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10111
10112
10113def fpNeg(a, ctx=None):
10114 """Create a Z3 floating-point addition expression.
10115
10116 >>> s = FPSort(8, 24)
10117 >>> rm = RNE()
10118 >>> x = FP('x', s)
10119 >>> fpNeg(x)
10120 -x
10121 >>> fpNeg(x).sort()
10122 FPSort(8, 24)
10123 """
10124 ctx = _get_ctx(ctx)
10125 [a] = _coerce_fp_expr_list([a], ctx)
10126 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10127
10128
10129def _mk_fp_unary(f, rm, a, ctx):
10130 ctx = _get_ctx(ctx)
10131 [a] = _coerce_fp_expr_list([a], ctx)
10132 if z3_debug():
10133 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10134 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10135 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10136
10137
10138def _mk_fp_unary_pred(f, a, ctx):
10139 ctx = _get_ctx(ctx)
10140 [a] = _coerce_fp_expr_list([a], ctx)
10141 if z3_debug():
10142 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10143 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10144
10145
10146def _mk_fp_bin(f, rm, a, b, ctx):
10147 ctx = _get_ctx(ctx)
10148 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10149 if z3_debug():
10150 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10151 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10152 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10153
10154
10155def _mk_fp_bin_norm(f, a, b, ctx):
10156 ctx = _get_ctx(ctx)
10157 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10158 if z3_debug():
10159 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10160 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10161
10162
10163def _mk_fp_bin_pred(f, a, b, ctx):
10164 ctx = _get_ctx(ctx)
10165 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10166 if z3_debug():
10167 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10168 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
10169
10170
10171def _mk_fp_tern(f, rm, a, b, c, ctx):
10172 ctx = _get_ctx(ctx)
10173 [a, b, c] = _coerce_fp_expr_list([a, b, c], 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) or is_fp(
10177 c), "Second, third or fourth argument must be a Z3 floating-point expression")
10178 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
10179
10180
10181def fpAdd(rm, a, b, ctx=None):
10182 """Create a Z3 floating-point addition expression.
10183
10184 >>> s = FPSort(8, 24)
10185 >>> rm = RNE()
10186 >>> x = FP('x', s)
10187 >>> y = FP('y', s)
10188 >>> fpAdd(rm, x, y)
10189 fpAdd(RNE(), x, y)
10190 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
10191 x + y
10192 >>> fpAdd(rm, x, y).sort()
10193 FPSort(8, 24)
10194 """
10195 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
10196
10197
10198def fpSub(rm, a, b, ctx=None):
10199 """Create a Z3 floating-point subtraction expression.
10200
10201 >>> s = FPSort(8, 24)
10202 >>> rm = RNE()
10203 >>> x = FP('x', s)
10204 >>> y = FP('y', s)
10205 >>> fpSub(rm, x, y)
10206 fpSub(RNE(), x, y)
10207 >>> fpSub(rm, x, y).sort()
10208 FPSort(8, 24)
10209 """
10210 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
10211
10212
10213def fpMul(rm, a, b, ctx=None):
10214 """Create a Z3 floating-point multiplication expression.
10215
10216 >>> s = FPSort(8, 24)
10217 >>> rm = RNE()
10218 >>> x = FP('x', s)
10219 >>> y = FP('y', s)
10220 >>> fpMul(rm, x, y)
10221 fpMul(RNE(), x, y)
10222 >>> fpMul(rm, x, y).sort()
10223 FPSort(8, 24)
10224 """
10225 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
10226
10227
10228def fpDiv(rm, a, b, ctx=None):
10229 """Create a Z3 floating-point division expression.
10230
10231 >>> s = FPSort(8, 24)
10232 >>> rm = RNE()
10233 >>> x = FP('x', s)
10234 >>> y = FP('y', s)
10235 >>> fpDiv(rm, x, y)
10236 fpDiv(RNE(), x, y)
10237 >>> fpDiv(rm, x, y).sort()
10238 FPSort(8, 24)
10239 """
10240 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
10241
10242
10243def fpRem(a, b, ctx=None):
10244 """Create a Z3 floating-point remainder expression.
10245
10246 >>> s = FPSort(8, 24)
10247 >>> x = FP('x', s)
10248 >>> y = FP('y', s)
10249 >>> fpRem(x, y)
10250 fpRem(x, y)
10251 >>> fpRem(x, y).sort()
10252 FPSort(8, 24)
10253 """
10254 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
10255
10256
10257def fpMin(a, b, ctx=None):
10258 """Create a Z3 floating-point minimum expression.
10259
10260 >>> s = FPSort(8, 24)
10261 >>> rm = RNE()
10262 >>> x = FP('x', s)
10263 >>> y = FP('y', s)
10264 >>> fpMin(x, y)
10265 fpMin(x, y)
10266 >>> fpMin(x, y).sort()
10267 FPSort(8, 24)
10268 """
10269 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
10270
10271
10272def fpMax(a, b, ctx=None):
10273 """Create a Z3 floating-point maximum expression.
10274
10275 >>> s = FPSort(8, 24)
10276 >>> rm = RNE()
10277 >>> x = FP('x', s)
10278 >>> y = FP('y', s)
10279 >>> fpMax(x, y)
10280 fpMax(x, y)
10281 >>> fpMax(x, y).sort()
10282 FPSort(8, 24)
10283 """
10284 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
10285
10286
10287def fpFMA(rm, a, b, c, ctx=None):
10288 """Create a Z3 floating-point fused multiply-add expression.
10289 """
10290 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
10291
10292
10293def fpSqrt(rm, a, ctx=None):
10294 """Create a Z3 floating-point square root expression.
10295 """
10296 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
10297
10298
10299def fpRoundToIntegral(rm, a, ctx=None):
10300 """Create a Z3 floating-point roundToIntegral expression.
10301 """
10302 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
10303
10304
10305def fpIsNaN(a, ctx=None):
10306 """Create a Z3 floating-point isNaN expression.
10307
10308 >>> s = FPSort(8, 24)
10309 >>> x = FP('x', s)
10310 >>> y = FP('y', s)
10311 >>> fpIsNaN(x)
10312 fpIsNaN(x)
10313 """
10314 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
10315
10316
10317def fpIsInf(a, ctx=None):
10318 """Create a Z3 floating-point isInfinite expression.
10319
10320 >>> s = FPSort(8, 24)
10321 >>> x = FP('x', s)
10322 >>> fpIsInf(x)
10323 fpIsInf(x)
10324 """
10325 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
10326
10327
10328def fpIsZero(a, ctx=None):
10329 """Create a Z3 floating-point isZero expression.
10330 """
10331 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
10332
10333
10334def fpIsNormal(a, ctx=None):
10335 """Create a Z3 floating-point isNormal expression.
10336 """
10337 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
10338
10339
10340def fpIsSubnormal(a, ctx=None):
10341 """Create a Z3 floating-point isSubnormal expression.
10342 """
10343 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
10344
10345
10346def fpIsNegative(a, ctx=None):
10347 """Create a Z3 floating-point isNegative expression.
10348 """
10349 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
10350
10351
10352def fpIsPositive(a, ctx=None):
10353 """Create a Z3 floating-point isPositive expression.
10354 """
10355 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
10356
10357
10358def _check_fp_args(a, b):
10359 if z3_debug():
10360 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10361
10362
10363def fpLT(a, b, ctx=None):
10364 """Create the Z3 floating-point expression `other < self`.
10365
10366 >>> x, y = FPs('x y', FPSort(8, 24))
10367 >>> fpLT(x, y)
10368 x < y
10369 >>> (x < y).sexpr()
10370 '(fp.lt x y)'
10371 """
10372 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
10373
10374
10375def fpLEQ(a, b, ctx=None):
10376 """Create the Z3 floating-point expression `other <= self`.
10377
10378 >>> x, y = FPs('x y', FPSort(8, 24))
10379 >>> fpLEQ(x, y)
10380 x <= y
10381 >>> (x <= y).sexpr()
10382 '(fp.leq x y)'
10383 """
10384 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
10385
10386
10387def fpGT(a, b, ctx=None):
10388 """Create the Z3 floating-point expression `other > self`.
10389
10390 >>> x, y = FPs('x y', FPSort(8, 24))
10391 >>> fpGT(x, y)
10392 x > y
10393 >>> (x > y).sexpr()
10394 '(fp.gt x y)'
10395 """
10396 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
10397
10398
10399def fpGEQ(a, b, ctx=None):
10400 """Create the Z3 floating-point expression `other >= self`.
10401
10402 >>> x, y = FPs('x y', FPSort(8, 24))
10403 >>> fpGEQ(x, y)
10404 x >= y
10405 >>> (x >= y).sexpr()
10406 '(fp.geq x y)'
10407 """
10408 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
10409
10410
10411def fpEQ(a, b, ctx=None):
10412 """Create the Z3 floating-point expression `fpEQ(other, self)`.
10413
10414 >>> x, y = FPs('x y', FPSort(8, 24))
10415 >>> fpEQ(x, y)
10416 fpEQ(x, y)
10417 >>> fpEQ(x, y).sexpr()
10418 '(fp.eq x y)'
10419 """
10420 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
10421
10422
10423def fpNEQ(a, b, ctx=None):
10424 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
10425
10426 >>> x, y = FPs('x y', FPSort(8, 24))
10427 >>> fpNEQ(x, y)
10428 Not(fpEQ(x, y))
10429 >>> (x != y).sexpr()
10430 '(distinct x y)'
10431 """
10432 return Not(fpEQ(a, b, ctx))
10433
10434
10435def fpFP(sgn, exp, sig, ctx=None):
10436 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
10437
10438 >>> s = FPSort(8, 24)
10439 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
10440 >>> print(x)
10441 fpFP(1, 127, 4194304)
10442 >>> xv = FPVal(-1.5, s)
10443 >>> print(xv)
10444 -1.5
10445 >>> slvr = Solver()
10446 >>> slvr.add(fpEQ(x, xv))
10447 >>> slvr.check()
10448 sat
10449 >>> xv = FPVal(+1.5, s)
10450 >>> print(xv)
10451 1.5
10452 >>> slvr = Solver()
10453 >>> slvr.add(fpEQ(x, xv))
10454 >>> slvr.check()
10455 unsat
10456 """
10457 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
10458 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
10459 ctx = _get_ctx(ctx)
10460 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
10461 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
10462
10463
10464def fpToFP(a1, a2=None, a3=None, ctx=None):
10465 """Create a Z3 floating-point conversion expression from other term sorts
10466 to floating-point.
10467
10468 From a bit-vector term in IEEE 754-2008 format:
10469 >>> x = FPVal(1.0, Float32())
10470 >>> x_bv = fpToIEEEBV(x)
10471 >>> simplify(fpToFP(x_bv, Float32()))
10472 1
10473
10474 From a floating-point term with different precision:
10475 >>> x = FPVal(1.0, Float32())
10476 >>> x_db = fpToFP(RNE(), x, Float64())
10477 >>> x_db.sort()
10478 FPSort(11, 53)
10479
10480 From a real term:
10481 >>> x_r = RealVal(1.5)
10482 >>> simplify(fpToFP(RNE(), x_r, Float32()))
10483 1.5
10484
10485 From a signed bit-vector term:
10486 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10487 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
10488 -1.25*(2**2)
10489 """
10490 ctx = _get_ctx(ctx)
10491 if is_bv(a1) and is_fp_sort(a2):
10492 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
10493 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
10494 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10495 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
10496 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10497 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
10498 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
10499 else:
10500 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
10501
10502
10503def fpBVToFP(v, sort, ctx=None):
10504 """Create a Z3 floating-point conversion expression that represents the
10505 conversion from a bit-vector term to a floating-point term.
10506
10507 >>> x_bv = BitVecVal(0x3F800000, 32)
10508 >>> x_fp = fpBVToFP(x_bv, Float32())
10509 >>> x_fp
10510 fpToFP(1065353216)
10511 >>> simplify(x_fp)
10512 1
10513 """
10514 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
10515 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
10516 ctx = _get_ctx(ctx)
10517 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
10518
10519
10520def fpFPToFP(rm, v, sort, ctx=None):
10521 """Create a Z3 floating-point conversion expression that represents the
10522 conversion from a floating-point term to a floating-point term of different precision.
10523
10524 >>> x_sgl = FPVal(1.0, Float32())
10525 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
10526 >>> x_dbl
10527 fpToFP(RNE(), 1)
10528 >>> simplify(x_dbl)
10529 1
10530 >>> x_dbl.sort()
10531 FPSort(11, 53)
10532 """
10533 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10534 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
10535 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10536 ctx = _get_ctx(ctx)
10537 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10538
10539
10540def fpRealToFP(rm, v, sort, ctx=None):
10541 """Create a Z3 floating-point conversion expression that represents the
10542 conversion from a real term to a floating-point term.
10543
10544 >>> x_r = RealVal(1.5)
10545 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
10546 >>> x_fp
10547 fpToFP(RNE(), 3/2)
10548 >>> simplify(x_fp)
10549 1.5
10550 """
10551 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10552 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
10553 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10554 ctx = _get_ctx(ctx)
10555 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10556
10557
10558def fpSignedToFP(rm, v, sort, ctx=None):
10559 """Create a Z3 floating-point conversion expression that represents the
10560 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
10561
10562 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10563 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
10564 >>> x_fp
10565 fpToFP(RNE(), 4294967291)
10566 >>> simplify(x_fp)
10567 -1.25*(2**2)
10568 """
10569 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10570 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10571 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10572 ctx = _get_ctx(ctx)
10573 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10574
10575
10576def fpUnsignedToFP(rm, v, sort, ctx=None):
10577 """Create a Z3 floating-point conversion expression that represents the
10578 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
10579
10580 >>> x_signed = BitVecVal(-5, BitVecSort(32))
10581 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
10582 >>> x_fp
10583 fpToFPUnsigned(RNE(), 4294967291)
10584 >>> simplify(x_fp)
10585 1*(2**32)
10586 """
10587 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
10588 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
10589 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
10590 ctx = _get_ctx(ctx)
10591 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
10592
10593
10594def fpToFPUnsigned(rm, x, s, ctx=None):
10595 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
10596 if z3_debug():
10597 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10598 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
10599 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
10600 ctx = _get_ctx(ctx)
10601 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
10602
10603
10604def fpToSBV(rm, x, s, ctx=None):
10605 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
10606
10607 >>> x = FP('x', FPSort(8, 24))
10608 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
10609 >>> print(is_fp(x))
10610 True
10611 >>> print(is_bv(y))
10612 True
10613 >>> print(is_fp(y))
10614 False
10615 >>> print(is_bv(x))
10616 False
10617 """
10618 if z3_debug():
10619 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10620 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10621 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10622 ctx = _get_ctx(ctx)
10623 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10624
10625
10626def fpToUBV(rm, x, s, ctx=None):
10627 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
10628
10629 >>> x = FP('x', FPSort(8, 24))
10630 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
10631 >>> print(is_fp(x))
10632 True
10633 >>> print(is_bv(y))
10634 True
10635 >>> print(is_fp(y))
10636 False
10637 >>> print(is_bv(x))
10638 False
10639 """
10640 if z3_debug():
10641 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10642 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
10643 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
10644 ctx = _get_ctx(ctx)
10645 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
10646
10647
10648def fpToReal(x, ctx=None):
10649 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
10650
10651 >>> x = FP('x', FPSort(8, 24))
10652 >>> y = fpToReal(x)
10653 >>> print(is_fp(x))
10654 True
10655 >>> print(is_real(y))
10656 True
10657 >>> print(is_fp(y))
10658 False
10659 >>> print(is_real(x))
10660 False
10661 """
10662 if z3_debug():
10663 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10664 ctx = _get_ctx(ctx)
10665 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
10666
10667
10668def fpToIEEEBV(x, ctx=None):
10669 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
10670
10671 The size of the resulting bit-vector is automatically determined.
10672
10673 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
10674 knows only one NaN and it will always produce the same bit-vector representation of
10675 that NaN.
10676
10677 >>> x = FP('x', FPSort(8, 24))
10678 >>> y = fpToIEEEBV(x)
10679 >>> print(is_fp(x))
10680 True
10681 >>> print(is_bv(y))
10682 True
10683 >>> print(is_fp(y))
10684 False
10685 >>> print(is_bv(x))
10686 False
10687 """
10688 if z3_debug():
10689 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
10690 ctx = _get_ctx(ctx)
10691 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
10692
10693
10694
10699
10701 """Sequence sort."""
10702
10703 def is_string(self):
10704 """Determine if sort is a string
10705 >>> s = StringSort()
10706 >>> s.is_string()
10707 True
10708 >>> s = SeqSort(IntSort())
10709 >>> s.is_string()
10710 False
10711 """
10712 return Z3_is_string_sort(self.ctx_ref(), self.ast)
10713
10714 def basis(self):
10715 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10716
10718 """Character sort."""
10719
10720
10721def StringSort(ctx=None):
10722 """Create a string sort
10723 >>> s = StringSort()
10724 >>> print(s)
10725 String
10726 """
10727 ctx = _get_ctx(ctx)
10728 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
10729
10730def CharSort(ctx=None):
10731 """Create a character sort
10732 >>> ch = CharSort()
10733 >>> print(ch)
10734 Char
10735 """
10736 ctx = _get_ctx(ctx)
10737 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
10738
10739
10740def SeqSort(s):
10741 """Create a sequence sort over elements provided in the argument
10742 >>> s = SeqSort(IntSort())
10743 >>> s == Unit(IntVal(1)).sort()
10744 True
10745 """
10746 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
10747
10748
10750 """Sequence expression."""
10751
10752 def sort(self):
10753 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10754
10755 def __add__(self, other):
10756 return Concat(self, other)
10757
10758 def __radd__(self, other):
10759 return Concat(other, self)
10760
10761 def __getitem__(self, i):
10762 if _is_int(i):
10763 i = IntVal(i, self.ctx)
10764 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10765
10766 def at(self, i):
10767 if _is_int(i):
10768 i = IntVal(i, self.ctx)
10769 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10770
10771 def is_string(self):
10772 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_astas_ast()))
10773
10775 return Z3_is_string(self.ctx_ref(), self.as_astas_ast())
10776
10777 def as_string(self):
10778 """Return a string representation of sequence expression."""
10779 if self.is_string_value():
10780 string_length = ctypes.c_uint()
10781 chars = Z3_get_lstring(self.ctx_ref(), self.as_astas_ast(), byref(string_length))
10782 return string_at(chars, size=string_length.value).decode("latin-1")
10783 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
10784
10785 def __le__(self, other):
10786 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10787
10788 def __lt__(self, other):
10789 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10790
10791 def __ge__(self, other):
10792 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10793
10794 def __gt__(self, other):
10795 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10796
10797
10798def _coerce_char(ch, ctx=None):
10799 if isinstance(ch, str):
10800 ctx = _get_ctx(ctx)
10801 ch = CharVal(ch, ctx)
10802 if not is_expr(ch):
10803 raise Z3Exception("Character expression expected")
10804 return ch
10805
10807 """Character expression."""
10808
10809 def __le__(self, other):
10810 other = _coerce_char(other, self.ctx)
10811 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10812
10813 def to_int(self):
10814 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10815
10816 def to_bv(self):
10817 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10818
10819 def is_digit(self):
10820 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_astas_ast()), self.ctx)
10821
10822
10823def CharVal(ch, ctx=None):
10824 ctx = _get_ctx(ctx)
10825 if isinstance(ch, str):
10826 ch = ord(ch)
10827 if not isinstance(ch, int):
10828 raise Z3Exception("character value should be an ordinal")
10829 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
10830
10831def CharFromBv(ch, ctx=None):
10832 if not is_expr(ch):
10833 raise Z3Expression("Bit-vector expression needed")
10834 return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
10835
10836def CharToBv(ch, ctx=None):
10837 ch = _coerce_char(ch, ctx)
10838 return ch.to_bv()
10839
10840def CharToInt(ch, ctx=None):
10841 ch = _coerce_char(ch, ctx)
10842 return ch.to_int()
10843
10844def CharIsDigit(ch, ctx=None):
10845 ch = _coerce_char(ch, ctx)
10846 return ch.is_digit()
10847
10848def _coerce_seq(s, ctx=None):
10849 if isinstance(s, str):
10850 ctx = _get_ctx(ctx)
10851 s = StringVal(s, ctx)
10852 if not is_expr(s):
10853 raise Z3Exception("Non-expression passed as a sequence")
10854 if not is_seq(s):
10855 raise Z3Exception("Non-sequence passed as a sequence")
10856 return s
10857
10858
10859def _get_ctx2(a, b, ctx=None):
10860 if is_expr(a):
10861 return a.ctx
10862 if is_expr(b):
10863 return b.ctx
10864 if ctx is None:
10865 ctx = main_ctx()
10866 return ctx
10867
10868
10869def is_seq(a):
10870 """Return `True` if `a` is a Z3 sequence expression.
10871 >>> print (is_seq(Unit(IntVal(0))))
10872 True
10873 >>> print (is_seq(StringVal("abc")))
10874 True
10875 """
10876 return isinstance(a, SeqRef)
10877
10878
10880 """Return `True` if `a` is a Z3 string expression.
10881 >>> print (is_string(StringVal("ab")))
10882 True
10883 """
10884 return isinstance(a, SeqRef) and a.is_string()
10885
10886
10888 """return 'True' if 'a' is a Z3 string constant expression.
10889 >>> print (is_string_value(StringVal("a")))
10890 True
10891 >>> print (is_string_value(StringVal("a") + StringVal("b")))
10892 False
10893 """
10894 return isinstance(a, SeqRef) and a.is_string_value()
10895
10896def StringVal(s, ctx=None):
10897 """create a string expression"""
10898 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
10899 ctx = _get_ctx(ctx)
10900 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
10901
10902
10903def String(name, ctx=None):
10904 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10905
10906 >>> x = String('x')
10907 """
10908 ctx = _get_ctx(ctx)
10909 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10910
10911
10912def Strings(names, ctx=None):
10913 """Return a tuple of String constants. """
10914 ctx = _get_ctx(ctx)
10915 if isinstance(names, str):
10916 names = names.split(" ")
10917 return [String(name, ctx) for name in names]
10918
10919
10920def SubString(s, offset, length):
10921 """Extract substring or subsequence starting at offset"""
10922 return Extract(s, offset, length)
10923
10924
10925def SubSeq(s, offset, length):
10926 """Extract substring or subsequence starting at offset"""
10927 return Extract(s, offset, length)
10928
10929
10930def Empty(s):
10931 """Create the empty sequence of the given sort
10932 >>> e = Empty(StringSort())
10933 >>> e2 = StringVal("")
10934 >>> print(e.eq(e2))
10935 True
10936 >>> e3 = Empty(SeqSort(IntSort()))
10937 >>> print(e3)
10938 Empty(Seq(Int))
10939 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10940 >>> print(e4)
10941 Empty(ReSort(Seq(Int)))
10942 """
10943 if isinstance(s, SeqSortRef):
10944 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10945 if isinstance(s, ReSortRef):
10946 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10947 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10948
10949
10950def Full(s):
10951 """Create the regular expression that accepts the universal language
10952 >>> e = Full(ReSort(SeqSort(IntSort())))
10953 >>> print(e)
10954 Full(ReSort(Seq(Int)))
10955 >>> e1 = Full(ReSort(StringSort()))
10956 >>> print(e1)
10957 Full(ReSort(String))
10958 """
10959 if isinstance(s, ReSortRef):
10960 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10961 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10962
10963
10964
10965def Unit(a):
10966 """Create a singleton sequence"""
10967 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10968
10969
10970def PrefixOf(a, b):
10971 """Check if 'a' is a prefix of 'b'
10972 >>> s1 = PrefixOf("ab", "abc")
10973 >>> simplify(s1)
10974 True
10975 >>> s2 = PrefixOf("bc", "abc")
10976 >>> simplify(s2)
10977 False
10978 """
10979 ctx = _get_ctx2(a, b)
10980 a = _coerce_seq(a, ctx)
10981 b = _coerce_seq(b, ctx)
10982 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10983
10984
10985def SuffixOf(a, b):
10986 """Check if 'a' is a suffix of 'b'
10987 >>> s1 = SuffixOf("ab", "abc")
10988 >>> simplify(s1)
10989 False
10990 >>> s2 = SuffixOf("bc", "abc")
10991 >>> simplify(s2)
10992 True
10993 """
10994 ctx = _get_ctx2(a, b)
10995 a = _coerce_seq(a, ctx)
10996 b = _coerce_seq(b, ctx)
10997 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10998
10999
11000def Contains(a, b):
11001 """Check if 'a' contains 'b'
11002 >>> s1 = Contains("abc", "ab")
11003 >>> simplify(s1)
11004 True
11005 >>> s2 = Contains("abc", "bc")
11006 >>> simplify(s2)
11007 True
11008 >>> x, y, z = Strings('x y z')
11009 >>> s3 = Contains(Concat(x,y,z), y)
11010 >>> simplify(s3)
11011 True
11012 """
11013 ctx = _get_ctx2(a, b)
11014 a = _coerce_seq(a, ctx)
11015 b = _coerce_seq(b, ctx)
11016 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11017
11018
11019def Replace(s, src, dst):
11020 """Replace the first occurrence of 'src' by 'dst' in 's'
11021 >>> r = Replace("aaa", "a", "b")
11022 >>> simplify(r)
11023 "baa"
11024 """
11025 ctx = _get_ctx2(dst, s)
11026 if ctx is None and is_expr(src):
11027 ctx = src.ctx
11028 src = _coerce_seq(src, ctx)
11029 dst = _coerce_seq(dst, ctx)
11030 s = _coerce_seq(s, ctx)
11031 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11032
11033
11034def IndexOf(s, substr, offset=None):
11035 """Retrieve the index of substring within a string starting at a specified offset.
11036 >>> simplify(IndexOf("abcabc", "bc", 0))
11037 1
11038 >>> simplify(IndexOf("abcabc", "bc", 2))
11039 4
11040 """
11041 if offset is None:
11042 offset = IntVal(0)
11043 ctx = None
11044 if is_expr(offset):
11045 ctx = offset.ctx
11046 ctx = _get_ctx2(s, substr, ctx)
11047 s = _coerce_seq(s, ctx)
11048 substr = _coerce_seq(substr, ctx)
11049 if _is_int(offset):
11050 offset = IntVal(offset, ctx)
11051 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11052
11053
11054def LastIndexOf(s, substr):
11055 """Retrieve the last index of substring within a string"""
11056 ctx = None
11057 ctx = _get_ctx2(s, substr, ctx)
11058 s = _coerce_seq(s, ctx)
11059 substr = _coerce_seq(substr, ctx)
11060 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11061
11062
11063def Length(s):
11064 """Obtain the length of a sequence 's'
11065 >>> l = Length(StringVal("abc"))
11066 >>> simplify(l)
11067 3
11068 """
11069 s = _coerce_seq(s)
11070 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11071
11072
11074 """Convert string expression to integer
11075 >>> a = StrToInt("1")
11076 >>> simplify(1 == a)
11077 True
11078 >>> b = StrToInt("2")
11079 >>> simplify(1 == b)
11080 False
11081 >>> c = StrToInt(IntToStr(2))
11082 >>> simplify(1 == c)
11083 False
11084 """
11085 s = _coerce_seq(s)
11086 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11087
11088
11090 """Convert integer expression to string"""
11091 if not is_expr(s):
11092 s = _py2expr(s)
11093 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11094
11095
11097 """Convert a unit length string to integer code"""
11098 if not is_expr(s):
11099 s = _py2expr(s)
11100 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
11101
11103 """Convert code to a string"""
11104 if not is_expr(c):
11105 c = _py2expr(c)
11106 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
11107
11108def Re(s, ctx=None):
11109 """The regular expression that accepts sequence 's'
11110 >>> s1 = Re("ab")
11111 >>> s2 = Re(StringVal("ab"))
11112 >>> s3 = Re(Unit(BoolVal(True)))
11113 """
11114 s = _coerce_seq(s, ctx)
11115 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
11116
11117
11118# Regular expressions
11119
11121 """Regular expression sort."""
11122
11123 def basis(self):
11124 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11125
11126
11127def ReSort(s):
11128 if is_ast(s):
11129 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
11130 if s is None or isinstance(s, Context):
11131 ctx = _get_ctx(s)
11132 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
11133 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
11134
11135
11137 """Regular expressions."""
11138
11139 def __add__(self, other):
11140 return Union(self, other)
11141
11142
11143def is_re(s):
11144 return isinstance(s, ReRef)
11145
11146
11147def InRe(s, re):
11148 """Create regular expression membership test
11149 >>> re = Union(Re("a"),Re("b"))
11150 >>> print (simplify(InRe("a", re)))
11151 True
11152 >>> print (simplify(InRe("b", re)))
11153 True
11154 >>> print (simplify(InRe("c", re)))
11155 False
11156 """
11157 s = _coerce_seq(s, re.ctx)
11158 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
11159
11160
11161def Union(*args):
11162 """Create union of regular expressions.
11163 >>> re = Union(Re("a"), Re("b"), Re("c"))
11164 >>> print (simplify(InRe("d", re)))
11165 False
11166 """
11167 args = _get_args(args)
11168 sz = len(args)
11169 if z3_debug():
11170 _z3_assert(sz > 0, "At least one argument expected.")
11171 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11172 if sz == 1:
11173 return args[0]
11174 ctx = args[0].ctx
11175 v = (Ast * sz)()
11176 for i in range(sz):
11177 v[i] = args[i].as_ast()
11178 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
11179
11180
11181def Intersect(*args):
11182 """Create intersection of regular expressions.
11183 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
11184 """
11185 args = _get_args(args)
11186 sz = len(args)
11187 if z3_debug():
11188 _z3_assert(sz > 0, "At least one argument expected.")
11189 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
11190 if sz == 1:
11191 return args[0]
11192 ctx = args[0].ctx
11193 v = (Ast * sz)()
11194 for i in range(sz):
11195 v[i] = args[i].as_ast()
11196 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
11197
11198
11199def Plus(re):
11200 """Create the regular expression accepting one or more repetitions of argument.
11201 >>> re = Plus(Re("a"))
11202 >>> print(simplify(InRe("aa", re)))
11203 True
11204 >>> print(simplify(InRe("ab", re)))
11205 False
11206 >>> print(simplify(InRe("", re)))
11207 False
11208 """
11209 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
11210
11211
11212def Option(re):
11213 """Create the regular expression that optionally accepts the argument.
11214 >>> re = Option(Re("a"))
11215 >>> print(simplify(InRe("a", re)))
11216 True
11217 >>> print(simplify(InRe("", re)))
11218 True
11219 >>> print(simplify(InRe("aa", re)))
11220 False
11221 """
11222 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
11223
11224
11226 """Create the complement regular expression."""
11227 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
11228
11229
11230def Star(re):
11231 """Create the regular expression accepting zero or more repetitions of argument.
11232 >>> re = Star(Re("a"))
11233 >>> print(simplify(InRe("aa", re)))
11234 True
11235 >>> print(simplify(InRe("ab", re)))
11236 False
11237 >>> print(simplify(InRe("", re)))
11238 True
11239 """
11240 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
11241
11242
11243def Loop(re, lo, hi=0):
11244 """Create the regular expression accepting between a lower and upper bound repetitions
11245 >>> re = Loop(Re("a"), 1, 3)
11246 >>> print(simplify(InRe("aa", re)))
11247 True
11248 >>> print(simplify(InRe("aaaa", re)))
11249 False
11250 >>> print(simplify(InRe("", re)))
11251 False
11252 """
11253 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
11254
11255
11256def Range(lo, hi, ctx=None):
11257 """Create the range regular expression over two sequences of length 1
11258 >>> range = Range("a","z")
11259 >>> print(simplify(InRe("b", range)))
11260 True
11261 >>> print(simplify(InRe("bb", range)))
11262 False
11263 """
11264 lo = _coerce_seq(lo, ctx)
11265 hi = _coerce_seq(hi, ctx)
11266 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
11267
11268def Diff(a, b, ctx=None):
11269 """Create the difference regular epression
11270 """
11271 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
11272
11273def AllChar(regex_sort, ctx=None):
11274 """Create a regular expression that accepts all single character strings
11275 """
11276 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
11277
11278# Special Relations
11279
11280
11281def PartialOrder(a, index):
11282 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
11283
11284
11285def LinearOrder(a, index):
11286 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11287
11288
11289def TreeOrder(a, index):
11290 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
11291
11292
11294 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
11295
11296
11298 """Given a binary relation R, such that the two arguments have the same sort
11299 create the transitive closure relation R+.
11300 The transitive closure R+ is a new relation.
11301 """
11302 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
11303
11304
11306 def __init__(self):
11307 self.bases = {}
11308 self.lock = None
11309
11310 def set_threaded(self):
11311 if self.lock is None:
11312 import threading
11313 self.lock = threading.Lock()
11314
11315 def get(self, ctx):
11316 if self.lock:
11317 with self.lock:
11318 r = self.bases[ctx]
11319 else:
11320 r = self.bases[ctx]
11321 return r
11322
11323 def set(self, ctx, r):
11324 if self.lock:
11325 with self.lock:
11326 self.bases[ctx] = r
11327 else:
11328 self.bases[ctx] = r
11329
11330 def insert(self, r):
11331 if self.lock:
11332 with self.lock:
11333 id = len(self.bases) + 3
11334 self.bases[id] = r
11335 else:
11336 id = len(self.bases) + 3
11337 self.bases[id] = r
11338 return id
11339
11340
11341_prop_closures = None
11342
11343
11345 global _prop_closures
11346 if _prop_closures is None:
11347 _prop_closures = PropClosures()
11348
11349
11350def user_prop_push(ctx, cb):
11351 prop = _prop_closures.get(ctx)
11352 prop.cb = cb
11353 prop.push()
11354
11355
11356def user_prop_pop(ctx, cb, num_scopes):
11357 prop = _prop_closures.get(ctx)
11358 prop.cb = cb
11359 prop.pop(num_scopes)
11360
11362 ctx = ContextObj(ptr)
11363 super(ctypes.c_void_p, ctx).__init__(ptr)
11364 return ctx
11365
11366
11367def user_prop_fresh(ctx, _new_ctx):
11368 _prop_closures.set_threaded()
11369 prop = _prop_closures.get(ctx)
11370 nctx = Context()
11371 Z3_del_context(nctx.ctx)
11372 new_ctx = to_ContextObj(_new_ctx)
11373 nctx.ctx = new_ctx
11374 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
11375 nctx.owner = False
11376 new_prop = prop.fresh(nctx)
11377 _prop_closures.set(new_prop.id, new_prop)
11378 return new_prop.id
11379
11380def to_Ast(ptr,):
11381 ast = Ast(ptr)
11382 super(ctypes.c_void_p, ast).__init__(ptr)
11383 return ast
11384
11385def user_prop_fixed(ctx, cb, id, value):
11386 prop = _prop_closures.get(ctx)
11387 prop.cb = cb
11388 id = _to_expr_ref(to_Ast(id), prop.ctx())
11389 value = _to_expr_ref(to_Ast(value), prop.ctx())
11390 prop.fixed(id, value)
11391 prop.cb = None
11392
11393def user_prop_created(ctx, cb, id):
11394 prop = _prop_closures.get(ctx)
11395 prop.cb = cb
11396 id = _to_expr_ref(to_Ast(id), prop.ctx())
11397 prop.created(id)
11398 prop.cb = None
11399
11400def user_prop_final(ctx, cb):
11401 prop = _prop_closures.get(ctx)
11402 prop.cb = cb
11403 prop.final()
11404 prop.cb = None
11405
11406def user_prop_eq(ctx, cb, x, y):
11407 prop = _prop_closures.get(ctx)
11408 prop.cb = cb
11409 x = _to_expr_ref(to_Ast(x), prop.ctx())
11410 y = _to_expr_ref(to_Ast(y), prop.ctx())
11411 prop.eq(x, y)
11412 prop.cb = None
11413
11414def user_prop_diseq(ctx, cb, x, y):
11415 prop = _prop_closures.get(ctx)
11416 prop.cb = cb
11417 x = _to_expr_ref(to_Ast(x), prop.ctx())
11418 y = _to_expr_ref(to_Ast(y), prop.ctx())
11419 prop.diseq(x, y)
11420 prop.cb = None
11421
11422# TODO The decision callback is not fully implemented.
11423# It needs to handle the ast*, unsigned* idx, and Z3_lbool*
11424def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref):
11425 prop = _prop_closures.get(ctx)
11426 prop.cb = cb
11427 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
11428 t, idx, phase = prop.decide(t, idx, phase)
11429 t_ref = t
11430 idx_ref = idx
11431 phase_ref = phase
11432 prop.cb = None
11433
11434
11435_user_prop_push = Z3_push_eh(user_prop_push)
11436_user_prop_pop = Z3_pop_eh(user_prop_pop)
11437_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
11438_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
11439_user_prop_created = Z3_created_eh(user_prop_created)
11440_user_prop_final = Z3_final_eh(user_prop_final)
11441_user_prop_eq = Z3_eq_eh(user_prop_eq)
11442_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
11443_user_prop_decide = Z3_decide_eh(user_prop_decide)
11444
11445def PropagateFunction(name, *sig):
11446 """Create a function that gets tracked by user propagator.
11447 Every term headed by this function symbol is tracked.
11448 If a term is fixed and the fixed callback is registered a
11449 callback is invoked that the term headed by this function is fixed.
11450 """
11451 sig = _get_args(sig)
11452 if z3_debug():
11453 _z3_assert(len(sig) > 0, "At least two arguments expected")
11454 arity = len(sig) - 1
11455 rng = sig[arity]
11456 if z3_debug():
11457 _z3_assert(is_sort(rng), "Z3 sort expected")
11458 dom = (Sort * arity)()
11459 for i in range(arity):
11460 if z3_debug():
11461 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
11462 dom[i] = sig[i].ast
11463 ctx = rng.ctx
11464 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
11465
11466
11468
11469 #
11470 # Either solver is set or ctx is set.
11471 # Propagators that are created throuh callbacks
11472 # to "fresh" inherit the context of that is supplied
11473 # as argument to the callback.
11474 # This context should not be deleted. It is owned by the solver.
11475 #
11476 def __init__(self, s, ctx=None):
11477 assert s is None or ctx is None
11479 self.solver = s
11480 self._ctx = None
11481 self.fresh_ctx = None
11482 self.cb = None
11483 self.id = _prop_closures.insert(self)
11484 self.fixed = None
11485 self.final = None
11486 self.eq = None
11487 self.diseq = None
11488 self.created = None
11489 if ctx:
11490 self.fresh_ctx = ctx
11491 if s:
11493 s.solver,
11494 ctypes.c_void_p(self.id),
11495 _user_prop_push,
11496 _user_prop_pop,
11497 _user_prop_fresh)
11498
11499 def __del__(self):
11500 if self._ctx:
11501 self._ctx.ctx = None
11502
11503 def ctx(self):
11504 if self.fresh_ctx:
11505 return self.fresh_ctx
11506 else:
11507 return self.solver.ctx
11508
11509 def ctx_ref(self):
11510 return self.ctx().ref()
11511
11512 def add_fixed(self, fixed):
11513 assert not self.fixed
11514 assert not self._ctx
11515 if self.solver:
11516 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
11517 self.fixed = fixed
11518
11519 def add_created(self, created):
11520 assert not self.created
11521 assert not self._ctx
11522 if self.solver:
11523 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
11524 self.created = created
11525
11526 def add_final(self, final):
11527 assert not self.final
11528 assert not self._ctx
11529 if self.solver:
11530 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
11531 self.final = final
11532
11533 def add_eq(self, eq):
11534 assert not self.eq
11535 assert not self._ctx
11536 if self.solver:
11537 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
11538 self.eq = eq
11539
11540 def add_diseq(self, diseq):
11541 assert not self.diseq
11542 assert not self._ctx
11543 if self.solver:
11544 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
11545 self.diseq = diseq
11546
11547 def add_decide(self, decide):
11548 assert not self.decide
11549 assert not self._ctx
11550 if self.solver:
11551 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
11552 self.decide = decide
11553
11554 def push(self):
11555 raise Z3Exception("push needs to be overwritten")
11556
11557 def pop(self, num_scopes):
11558 raise Z3Exception("pop needs to be overwritten")
11559
11560 def fresh(self, new_ctx):
11561 raise Z3Exception("fresh needs to be overwritten")
11562
11563 def add(self, e):
11564 assert not self._ctx
11565 if self.solver:
11566 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
11567 else:
11568 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
11569
11570 #
11571 # Tell the solver to perform the next split on a given term
11572 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
11573 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
11574 #
11575 def next_split(self, t, idx, phase):
11576 Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
11577
11578 #
11579 # Propagation can only be invoked as during a fixed or final callback.
11580 #
11581 def propagate(self, e, ids, eqs=[]):
11582 _ids, num_fixed = _to_ast_array(ids)
11583 num_eqs = len(eqs)
11584 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
11585 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
11586 Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
11587 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
11588
11589 def conflict(self, deps = [], eqs = []):
11590 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
def poly(self)
Definition: z3py.py:3107
def as_decimal(self, prec)
Definition: z3py.py:3095
def index(self)
Definition: z3py.py:3110
def approx(self, precision=10)
Definition: z3py.py:3083
def __del__(self)
Definition: z3py.py:8078
def __getitem__(self, idx)
Definition: z3py.py:8101
def __init__(self, result, ctx)
Definition: z3py.py:8070
def __len__(self)
Definition: z3py.py:8082
def as_expr(self)
Definition: z3py.py:8125
def __repr__(self)
Definition: z3py.py:8118
def sexpr(self)
Definition: z3py.py:8121
def __deepcopy__(self, memo={})
Definition: z3py.py:8075
def is_real(self)
Definition: z3py.py:2398
def __pos__(self)
Definition: z3py.py:2594
def sort(self)
Definition: z3py.py:2374
def __radd__(self, other)
Definition: z3py.py:2422
def __pow__(self, other)
Definition: z3py.py:2480
def __add__(self, other)
Definition: z3py.py:2409
def __lt__(self, other)
Definition: z3py.py:2616
def __neg__(self)
Definition: z3py.py:2583
def __rmul__(self, other)
Definition: z3py.py:2447
def __le__(self, other)
Definition: z3py.py:2603
def __mul__(self, other)
Definition: z3py.py:2432
def __mod__(self, other)
Definition: z3py.py:2556
def __rsub__(self, other)
Definition: z3py.py:2470
def __rtruediv__(self, other)
Definition: z3py.py:2552
def __rdiv__(self, other)
Definition: z3py.py:2535
def __ge__(self, other)
Definition: z3py.py:2642
def is_int(self)
Definition: z3py.py:2384
def __truediv__(self, other)
Definition: z3py.py:2531
def __gt__(self, other)
Definition: z3py.py:2629
def __sub__(self, other)
Definition: z3py.py:2457
def __rpow__(self, other)
Definition: z3py.py:2494
def __rmod__(self, other)
Definition: z3py.py:2571
def __div__(self, other)
Definition: z3py.py:2508
Arithmetic.
Definition: z3py.py:2279
def is_real(self)
Definition: z3py.py:2282
def subsort(self, other)
Definition: z3py.py:2313
def cast(self, val)
Definition: z3py.py:2317
def is_int(self)
Definition: z3py.py:2296
def is_bool(self)
Definition: z3py.py:2310
def sort(self)
Definition: z3py.py:4542
def domain_n(self, i)
Definition: z3py.py:4560
def default(self)
Definition: z3py.py:4585
def __getitem__(self, arg)
Definition: z3py.py:4573
def domain(self)
Definition: z3py.py:4551
def range(self)
Definition: z3py.py:4564
def domain_n(self, i)
Definition: z3py.py:4524
def domain(self)
Definition: z3py.py:4515
def range(self)
Definition: z3py.py:4529
def erase(self, k)
Definition: z3py.py:6083
def __del__(self)
Definition: z3py.py:6023
def reset(self)
Definition: z3py.py:6097
def __init__(self, m=None, ctx=None)
Definition: z3py.py:6009
def __len__(self)
Definition: z3py.py:6027
def keys(self)
Definition: z3py.py:6112
def __repr__(self)
Definition: z3py.py:6080
def __getitem__(self, key)
Definition: z3py.py:6053
def __deepcopy__(self, memo={})
Definition: z3py.py:6020
def __setitem__(self, k, v)
Definition: z3py.py:6064
def __contains__(self, key)
Definition: z3py.py:6040
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:5947
def resize(self, sz)
Definition: z3py.py:5934
def __del__(self)
Definition: z3py.py:5860
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5849
def __setitem__(self, i, v)
Definition: z3py.py:5906
def push(self, v)
Definition: z3py.py:5922
def __len__(self)
Definition: z3py.py:5864
def translate(self, other_ctx)
Definition: z3py.py:5970
def __repr__(self)
Definition: z3py.py:5992
def sexpr(self)
Definition: z3py.py:5995
def __deepcopy__(self, memo={})
Definition: z3py.py:5989
def __copy__(self)
Definition: z3py.py:5986
def __getitem__(self, i)
Definition: z3py.py:5877
def as_signed_long(self)
Definition: z3py.py:3905
def as_long(self)
Definition: z3py.py:3894
def as_binary_string(self)
Definition: z3py.py:3931
def as_string(self)
Definition: z3py.py:3928
def __rlshift__(self, other)
Definition: z3py.py:3876
def __pos__(self)
Definition: z3py.py:3641
def sort(self)
Definition: z3py.py:3481
def __radd__(self, other)
Definition: z3py.py:3516
def __rxor__(self, other)
Definition: z3py.py:3631
def __xor__(self, other)
Definition: z3py.py:3618
def __ror__(self, other)
Definition: z3py.py:3585
def __add__(self, other)
Definition: z3py.py:3503
def __rshift__(self, other)
Definition: z3py.py:3818
def __lt__(self, other)
Definition: z3py.py:3770
def __or__(self, other)
Definition: z3py.py:3572
def size(self)
Definition: z3py.py:3492
def __neg__(self)
Definition: z3py.py:3650
def __rand__(self, other)
Definition: z3py.py:3608
def __rmul__(self, other)
Definition: z3py.py:3539
def __le__(self, other)
Definition: z3py.py:3754
def __mul__(self, other)
Definition: z3py.py:3526
def __mod__(self, other)
Definition: z3py.py:3715
def __rsub__(self, other)
Definition: z3py.py:3562
def __invert__(self)
Definition: z3py.py:3661
def __rtruediv__(self, other)
Definition: z3py.py:3711
def __rdiv__(self, other)
Definition: z3py.py:3695
def __lshift__(self, other)
Definition: z3py.py:3848
def __ge__(self, other)
Definition: z3py.py:3802
def __and__(self, other)
Definition: z3py.py:3595
def __rrshift__(self, other)
Definition: z3py.py:3862
def __truediv__(self, other)
Definition: z3py.py:3691
def __gt__(self, other)
Definition: z3py.py:3786
def __sub__(self, other)
Definition: z3py.py:3549
def __rmod__(self, other)
Definition: z3py.py:3736
def __div__(self, other)
Definition: z3py.py:3672
Bit-Vectors.
Definition: z3py.py:3434
def subsort(self, other)
Definition: z3py.py:3446
def size(self)
Definition: z3py.py:3437
def cast(self, val)
Definition: z3py.py:3449
def sort(self)
Definition: z3py.py:1546
def __rmul__(self, other)
Definition: z3py.py:1549
def __mul__(self, other)
Definition: z3py.py:1552
Booleans.
Definition: z3py.py:1507
def subsort(self, other)
Definition: z3py.py:1533
def cast(self, val)
Definition: z3py.py:1510
def is_int(self)
Definition: z3py.py:1536
def is_bool(self)
Definition: z3py.py:1539
def to_int(self)
Definition: z3py.py:10813
def is_digit(self)
Definition: z3py.py:10819
def __le__(self, other)
Definition: z3py.py:10809
def to_bv(self)
Definition: z3py.py:10816
def __repr__(self)
Definition: z3py.py:6859
def __ne__(self, other)
Definition: z3py.py:6856
def __init__(self, r)
Definition: z3py.py:6847
def __deepcopy__(self, memo={})
Definition: z3py.py:6850
def __eq__(self, other)
Definition: z3py.py:6853
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:5108
def __init__(self, name, ctx=None)
Definition: z3py.py:5064
def declare(self, name, *args)
Definition: z3py.py:5084
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:5074
def __repr__(self)
Definition: z3py.py:5105
def __deepcopy__(self, memo={})
Definition: z3py.py:5069
def sort(self)
Definition: z3py.py:5345
def recognizer(self, idx)
Definition: z3py.py:5280
def num_constructors(self)
Definition: z3py.py:5248
def constructor(self, idx)
Definition: z3py.py:5261
def accessor(self, i, j)
Definition: z3py.py:5308
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:9816
def exponent(self, biased=True)
Definition: z3py.py:9775
def significand(self)
Definition: z3py.py:9744
def sign_as_bv(self)
Definition: z3py.py:9734
def isNegative(self)
Definition: z3py.py:9831
def significand_as_bv(self)
Definition: z3py.py:9765
def exponent_as_long(self, biased=True)
Definition: z3py.py:9785
def isInf(self)
Definition: z3py.py:9806
def isNaN(self)
Definition: z3py.py:9801
def sign(self)
Definition: z3py.py:9722
def isZero(self)
Definition: z3py.py:9811
def significand_as_long(self)
Definition: z3py.py:9754
def isSubnormal(self)
Definition: z3py.py:9821
def isPositive(self)
Definition: z3py.py:9826
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9796
def as_string(self)
Definition: z3py.py:9842
def as_string(self)
Definition: z3py.py:9636
def __pos__(self)
Definition: z3py.py:9575
def sort(self)
Definition: z3py.py:9458
def __radd__(self, other)
Definition: z3py.py:9514
def __add__(self, other)
Definition: z3py.py:9501
def sbits(self)
Definition: z3py.py:9477
def __lt__(self, other)
Definition: z3py.py:9492
def __neg__(self)
Definition: z3py.py:9579
def ebits(self)
Definition: z3py.py:9469
def __rmul__(self, other)
Definition: z3py.py:9562
def __le__(self, other)
Definition: z3py.py:9489
def __mul__(self, other)
Definition: z3py.py:9547
def __mod__(self, other)
Definition: z3py.py:9624
def __rsub__(self, other)
Definition: z3py.py:9537
def __rtruediv__(self, other)
Definition: z3py.py:9620
def __rdiv__(self, other)
Definition: z3py.py:9603
def __ge__(self, other)
Definition: z3py.py:9495
def __truediv__(self, other)
Definition: z3py.py:9616
def __gt__(self, other)
Definition: z3py.py:9498
def __sub__(self, other)
Definition: z3py.py:9524
def as_string(self)
Definition: z3py.py:9485
def __rmod__(self, other)
Definition: z3py.py:9628
def __div__(self, other)
Definition: z3py.py:9588
def sbits(self)
Definition: z3py.py:9355
def ebits(self)
Definition: z3py.py:9347
def cast(self, val)
Definition: z3py.py:9363
def as_long(self)
Definition: z3py.py:7738
def as_string(self)
Definition: z3py.py:7750
def sort(self)
Definition: z3py.py:7713
def as_string(self)
Definition: z3py.py:7717
Fixedpoint.
Definition: z3py.py:7413
def insert(self, *args)
Definition: z3py.py:7474
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7664
def fact(self, head, name=None)
Definition: z3py.py:7505
def reason_unknown(self)
Definition: z3py.py:7650
def rule(self, head, body=None, name=None)
Definition: z3py.py:7501
def to_string(self, queries)
Definition: z3py.py:7637
def add_cover(self, level, predicate, property)
Definition: z3py.py:7589
def add(self, *args)
Definition: z3py.py:7462
def __del__(self)
Definition: z3py.py:7430
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7478
def param_descrs(self)
Definition: z3py.py:7444
def assert_exprs(self, *args)
Definition: z3py.py:7448
def get_answer(self)
Definition: z3py.py:7556
def statistics(self)
Definition: z3py.py:7645
def update_rule(self, head, body, name)
Definition: z3py.py:7547
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7531
def append(self, *args)
Definition: z3py.py:7470
def query(self, *query)
Definition: z3py.py:7509
def parse_string(self, s)
Definition: z3py.py:7611
def help(self)
Definition: z3py.py:7440
def get_rules_along_trace(self)
Definition: z3py.py:7566
def get_ground_sat_answer(self)
Definition: z3py.py:7561
def __repr__(self)
Definition: z3py.py:7627
def get_rules(self)
Definition: z3py.py:7619
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7601
def sexpr(self)
Definition: z3py.py:7631
def get_assertions(self)
Definition: z3py.py:7623
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7582
def __deepcopy__(self, memo={})
Definition: z3py.py:7427
def get_num_levels(self, predicate)
Definition: z3py.py:7578
def declare_var(self, *vars)
Definition: z3py.py:7655
def parse_file(self, f)
Definition: z3py.py:7615
def set(self, *args, **keys)
Definition: z3py.py:7434
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:7416
def register_relation(self, *relations)
Definition: z3py.py:7595
def get_rule_names_along_trace(self)
Definition: z3py.py:7570
def __iadd__(self, fml)
Definition: z3py.py:7466
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:6131
def __del__(self)
Definition: z3py.py:6142
ctx
Definition: z3py.py:6136
def value(self)
Definition: z3py.py:6195
def __init__(self, entry, ctx)
Definition: z3py.py:6134
def arg_value(self, idx)
Definition: z3py.py:6164
entry
Definition: z3py.py:6135
def __repr__(self)
Definition: z3py.py:6236
def num_args(self)
Definition: z3py.py:6146
def __deepcopy__(self, memo={})
Definition: z3py.py:6139
def as_list(self)
Definition: z3py.py:6217
def __del__(self)
Definition: z3py.py:6249
def arity(self)
Definition: z3py.py:6292
def __init__(self, f, ctx)
Definition: z3py.py:6243
def translate(self, other_ctx)
Definition: z3py.py:6326
def __repr__(self)
Definition: z3py.py:6354
def num_entries(self)
Definition: z3py.py:6276
def __deepcopy__(self, memo={})
Definition: z3py.py:6334
def else_value(self)
Definition: z3py.py:6253
def __copy__(self)
Definition: z3py.py:6331
def as_list(self)
Definition: z3py.py:6337
def entry(self, idx)
Definition: z3py.py:6306
def insert(self, *args)
Definition: z3py.py:5706
def dimacs(self, include_names=True)
Definition: z3py.py:5764
def get(self, i)
Definition: z3py.py:5652
def depth(self)
Definition: z3py.py:5560
def convert_model(self, model)
Definition: z3py.py:5728
def add(self, *args)
Definition: z3py.py:5717
def __del__(self)
Definition: z3py.py:5556
def assert_exprs(self, *args)
Definition: z3py.py:5680
def __getitem__(self, arg)
Definition: z3py.py:5665
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5546
def size(self)
Definition: z3py.py:5626
def append(self, *args)
Definition: z3py.py:5695
def __len__(self)
Definition: z3py.py:5639
def as_expr(self)
Definition: z3py.py:5817
def __repr__(self)
Definition: z3py.py:5757
def sexpr(self)
Definition: z3py.py:5760
def precision(self)
Definition: z3py.py:5617
def translate(self, target)
Definition: z3py.py:5768
def __deepcopy__(self, memo={})
Definition: z3py.py:5794
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5797
def __copy__(self)
Definition: z3py.py:5791
def inconsistent(self)
Definition: z3py.py:5578
def prec(self)
Definition: z3py.py:5596
def as_long(self)
Definition: z3py.py:2953
def as_binary_string(self)
Definition: z3py.py:2974
def as_string(self)
Definition: z3py.py:2966
def decls(self)
Definition: z3py.py:6624
def get_universe(self, s)
Definition: z3py.py:6559
def __del__(self)
Definition: z3py.py:6367
def eval(self, t, model_completion=False)
Definition: z3py.py:6378
def __init__(self, m, ctx)
Definition: z3py.py:6361
def sorts(self)
Definition: z3py.py:6542
def __getitem__(self, idx)
Definition: z3py.py:6579
def __len__(self)
Definition: z3py.py:6435
def update_value(self, x, value)
Definition: z3py.py:6643
def num_sorts(self)
Definition: z3py.py:6504
def __repr__(self)
Definition: z3py.py:6371
def sexpr(self)
Definition: z3py.py:6374
def translate(self, target)
Definition: z3py.py:6665
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6409
def __deepcopy__(self, memo={})
Definition: z3py.py:6676
def __copy__(self)
Definition: z3py.py:6673
def get_interp(self, decl)
Definition: z3py.py:6452
def get_sort(self, idx)
Definition: z3py.py:6519
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7923
def reason_unknown(self)
Definition: z3py.py:7980
def objectives(self)
Definition: z3py.py:8026
def pop(self)
Definition: z3py.py:7967
def maximize(self, arg)
Definition: z3py.py:7947
def unsat_core(self)
Definition: z3py.py:7991
def from_string(self, s)
Definition: z3py.py:8018
def add(self, *args)
Definition: z3py.py:7886
def __del__(self)
Definition: z3py.py:7853
def param_descrs(self)
Definition: z3py.py:7870
def assert_exprs(self, *args)
Definition: z3py.py:7874
def model(self)
Definition: z3py.py:7984
def statistics(self)
Definition: z3py.py:8040
def help(self)
Definition: z3py.py:7866
def upper_values(self, obj)
Definition: z3py.py:8009
def __repr__(self)
Definition: z3py.py:8030
def from_file(self, filename)
Definition: z3py.py:8014
def set_on_model(self, on_model)
Definition: z3py.py:8045
def sexpr(self)
Definition: z3py.py:8034
def check(self, *assumptions)
Definition: z3py.py:7971
def push(self)
Definition: z3py.py:7963
def __deepcopy__(self, memo={})
Definition: z3py.py:7850
def minimize(self, arg)
Definition: z3py.py:7955
def lower(self, obj)
Definition: z3py.py:7994
def assert_and_track(self, a, p)
Definition: z3py.py:7894
def set(self, *args, **keys)
Definition: z3py.py:7859
def upper(self, obj)
Definition: z3py.py:7999
def lower_values(self, obj)
Definition: z3py.py:8004
def __init__(self, ctx=None)
Definition: z3py.py:7844
def assertions(self)
Definition: z3py.py:8022
def __iadd__(self, fml)
Definition: z3py.py:7890
def __str__(self)
Definition: z3py.py:7826
def upper(self)
Definition: z3py.py:7808
def value(self)
Definition: z3py.py:7820
def lower_values(self)
Definition: z3py.py:7812
def __init__(self, opt, value, is_max)
Definition: z3py.py:7799
def lower(self)
Definition: z3py.py:7804
def upper_values(self)
Definition: z3py.py:7816
def get_name(self, i)
Definition: z3py.py:5507
def get_kind(self, n)
Definition: z3py.py:5512
def __del__(self)
Definition: z3py.py:5493
def __getitem__(self, arg)
Definition: z3py.py:5522
def size(self)
Definition: z3py.py:5497
def __init__(self, descr, ctx=None)
Definition: z3py.py:5484
def __len__(self)
Definition: z3py.py:5502
def __repr__(self)
Definition: z3py.py:5528
def get_documentation(self, n)
Definition: z3py.py:5517
def __deepcopy__(self, memo={})
Definition: z3py.py:5490
Parameter Sets.
Definition: z3py.py:5411
def validate(self, ds)
Definition: z3py.py:5452
def __del__(self)
Definition: z3py.py:5428
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5417
def __repr__(self)
Definition: z3py.py:5449
def __deepcopy__(self, memo={})
Definition: z3py.py:5425
def set(self, name, val)
Definition: z3py.py:5432
def from_string(self, s)
Definition: z3py.py:9217
def __del__(self)
Definition: z3py.py:9206
def add_sort(self, sort)
Definition: z3py.py:9211
def add_decl(self, decl)
Definition: z3py.py:9214
def __init__(self, ctx=None)
Definition: z3py.py:9201
Patterns.
Definition: z3py.py:1912
def get_id(self)
Definition: z3py.py:1920
def as_ast(self)
Definition: z3py.py:1917
def __del__(self)
Definition: z3py.py:8494
def __call__(self, goal)
Definition: z3py.py:8583
def __lt__(self, other)
Definition: z3py.py:8498
def __le__(self, other)
Definition: z3py.py:8526
def __init__(self, probe, ctx=None)
Definition: z3py.py:8468
def __ne__(self, other)
Definition: z3py.py:8568
def __ge__(self, other)
Definition: z3py.py:8540
def __deepcopy__(self, memo={})
Definition: z3py.py:8491
def __eq__(self, other)
Definition: z3py.py:8554
def __gt__(self, other)
Definition: z3py.py:8512
def set(self, ctx, r)
Definition: z3py.py:11323
def insert(self, r)
Definition: z3py.py:11330
def set_threaded(self)
Definition: z3py.py:11310
def get(self, ctx)
Definition: z3py.py:11315
def __init__(self)
Definition: z3py.py:11306
Quantifiers.
Definition: z3py.py:1979
def pattern(self, idx)
Definition: z3py.py:2069
def sort(self)
Definition: z3py.py:1988
def var_name(self, idx)
Definition: z3py.py:2120
def no_pattern(self, idx)
Definition: z3py.py:2091
def is_forall(self)
Definition: z3py.py:1994
def num_no_patterns(self)
Definition: z3py.py:2087
def body(self)
Definition: z3py.py:2097
def num_vars(self)
Definition: z3py.py:2108
def get_id(self)
Definition: z3py.py:1985
def __getitem__(self, arg)
Definition: z3py.py:2036
def children(self)
Definition: z3py.py:2152
def weight(self)
Definition: z3py.py:2043
def is_lambda(self)
Definition: z3py.py:2022
def as_ast(self)
Definition: z3py.py:1982
def var_sort(self, idx)
Definition: z3py.py:2136
def num_patterns(self)
Definition: z3py.py:2057
def is_exists(self)
Definition: z3py.py:2008
def is_real(self)
Definition: z3py.py:3039
def as_decimal(self, prec)
Definition: z3py.py:3049
def as_fraction(self)
Definition: z3py.py:3070
def is_int_value(self)
Definition: z3py.py:3042
def numerator_as_long(self)
Definition: z3py.py:3012
def as_long(self)
Definition: z3py.py:3045
def denominator(self)
Definition: z3py.py:3001
def denominator_as_long(self)
Definition: z3py.py:3025
def is_int(self)
Definition: z3py.py:3036
def numerator(self)
Definition: z3py.py:2986
def as_string(self)
Definition: z3py.py:3061
def __add__(self, other)
Definition: z3py.py:11139
def basis(self)
Definition: z3py.py:11123
def __del__(self)
Definition: z3py.py:5132
def __init__(self, c, ctx)
Definition: z3py.py:5128
def __init__(self, c, ctx)
Definition: z3py.py:5140
def sort(self)
Definition: z3py.py:10752
def __radd__(self, other)
Definition: z3py.py:10758
def at(self, i)
Definition: z3py.py:10766
def __add__(self, other)
Definition: z3py.py:10755
def __lt__(self, other)
Definition: z3py.py:10788
def is_string_value(self)
Definition: z3py.py:10774
def __le__(self, other)
Definition: z3py.py:10785
def __ge__(self, other)
Definition: z3py.py:10791
def __gt__(self, other)
Definition: z3py.py:10794
def is_string(self)
Definition: z3py.py:10771
def as_string(self)
Definition: z3py.py:10777
def __getitem__(self, i)
Definition: z3py.py:10761
Strings, Sequences and Regular expressions.
Definition: z3py.py:10700
def basis(self)
Definition: z3py.py:10714
def is_string(self)
Definition: z3py.py:10703
def insert(self, *args)
Definition: z3py.py:7045
def dimacs(self, include_names=True)
Definition: z3py.py:7350
def non_units(self)
Definition: z3py.py:7258
def reason_unknown(self)
Definition: z3py.py:7294
backtrack_level
Definition: z3py.py:6897
def num_scopes(self)
Definition: z3py.py:6968
def unsat_core(self)
Definition: z3py.py:7138
def trail_levels(self)
Definition: z3py.py:7263
def trail(self)
Definition: z3py.py:7271
def from_string(self, s)
Definition: z3py.py:7203
def add(self, *args)
Definition: z3py.py:7019
def __del__(self)
Definition: z3py.py:6907
def import_model_converter(self, other)
Definition: z3py.py:7134
def param_descrs(self)
Definition: z3py.py:7311
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6894
def reset(self)
Definition: z3py.py:6986
def assert_exprs(self, *args)
Definition: z3py.py:7000
def pop(self, num=1)
Definition: z3py.py:6946
def units(self)
Definition: z3py.py:7253
def cube(self, vars=None)
Definition: z3py.py:7207
def cube_vars(self)
Definition: z3py.py:7228
def model(self)
Definition: z3py.py:7115
def statistics(self)
Definition: z3py.py:7276
def append(self, *args)
Definition: z3py.py:7034
def to_smt2(self)
Definition: z3py.py:7354
def help(self)
Definition: z3py.py:7307
def __repr__(self)
Definition: z3py.py:7315
def from_file(self, filename)
Definition: z3py.py:7199
def proof(self)
Definition: z3py.py:7235
def sexpr(self)
Definition: z3py.py:7338
def check(self, *assumptions)
Definition: z3py.py:7086
def translate(self, target)
Definition: z3py.py:7319
def push(self)
Definition: z3py.py:6924
def __deepcopy__(self, memo={})
Definition: z3py.py:7335
def consequences(self, assumptions, variables)
Definition: z3py.py:7170
def assert_and_track(self, a, p)
Definition: z3py.py:7056
def set(self, *args, **keys)
Definition: z3py.py:6911
def __copy__(self)
Definition: z3py.py:7332
def assertions(self)
Definition: z3py.py:7239
def __iadd__(self, fml)
Definition: z3py.py:7030
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:6703
def __getattr__(self, name)
Definition: z3py.py:6806
def __del__(self)
Definition: z3py.py:6714
def __getitem__(self, idx)
Definition: z3py.py:6750
def __len__(self)
Definition: z3py.py:6736
def keys(self)
Definition: z3py.py:6774
def __init__(self, stats, ctx)
Definition: z3py.py:6706
def __repr__(self)
Definition: z3py.py:6718
def get_key_value(self, key)
Definition: z3py.py:6786
def __deepcopy__(self, memo={})
Definition: z3py.py:6711
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:8221
def __del__(self)
Definition: z3py.py:8183
def param_descrs(self)
Definition: z3py.py:8235
def solver(self, logFile=None)
Definition: z3py.py:8187
def __init__(self, tactic, ctx=None)
Definition: z3py.py:8166
def help(self)
Definition: z3py.py:8231
def __deepcopy__(self, memo={})
Definition: z3py.py:8180
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:8204
def ctx_ref(self)
Definition: z3py.py:11509
def add_fixed(self, fixed)
Definition: z3py.py:11512
def __del__(self)
Definition: z3py.py:11499
def add_diseq(self, diseq)
Definition: z3py.py:11540
def pop(self, num_scopes)
Definition: z3py.py:11557
def next_split(self, t, idx, phase)
Definition: z3py.py:11575
def add_eq(self, eq)
Definition: z3py.py:11533
def add(self, e)
Definition: z3py.py:11563
def __init__(self, s, ctx=None)
Definition: z3py.py:11476
def propagate(self, e, ids, eqs=[])
Definition: z3py.py:11581
def add_decide(self, decide)
Definition: z3py.py:11547
def add_created(self, created)
Definition: z3py.py:11519
def conflict(self, deps=[], eqs=[])
Definition: z3py.py:11589
def add_final(self, final)
Definition: z3py.py:11526
def fresh(self, new_ctx)
Definition: z3py.py:11560
ASTs base class.
Definition: z3py.py:328
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).
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_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
void Z3_API Z3_solver_propagate_final(Z3_context c, Z3_solver s, Z3_final_eh final_eh)
register a callback on final check. This provides freedom to the propagator to delay actions or imple...
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
Z3_ast_vector Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Parse the given string using the SMT-LIB2 parser.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast_vector Z3_API Z3_solver_get_non_units(Z3_context c, Z3_solver s)
Return the set of non units in the solver state.
Z3_ast Z3_API Z3_mk_seq_to_re(Z3_context c, Z3_ast seq)
Create a regular expression that accepts the sequence seq.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
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 bound variable.
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_ast Z3_API Z3_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.
void Z3_API Z3_solver_propagate_consequence(Z3_context c, Z3_solver_callback, unsigned num_fixed, Z3_ast const *fixed, unsigned num_eqs, Z3_ast const *eq_lhs, Z3_ast const *eq_rhs, Z3_ast conseq)
propagate a consequence based on fixed values. This is a callback a client may invoke during the fixe...
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
void Z3_API Z3_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_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_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
void Z3_API Z3_solver_propagate_eq(Z3_context c, Z3_solver s, Z3_eq_eh eq_eh)
register a callback on expression equalities.
Z3_ast Z3_API Z3_mk_string(Z3_context c, Z3_string s)
Create a string constant out of the string that is passed in The string may contain escape encoding f...
Z3_func_decl Z3_API Z3_mk_transitive_closure(Z3_context c, Z3_func_decl f)
create transitive closure of binary relation.
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_sort Z3_API Z3_mk_seq_sort(Z3_context c, Z3_sort s)
Create a sequence sort out of the sort for the elements.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
Z3_ast_vector Z3_API Z3_solver_get_units(Z3_context c, Z3_solver s)
Return the set of units modulo model conversion.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
Z3_ast Z3_API Z3_mk_seq_last_index(Z3_context c, Z3_ast, Z3_ast substr)
Return index of the last occurrence of substr in s. If s does not contain substr, then the value is -...
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
Z3_ast Z3_API Z3_mk_fpa_to_fp_float(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_even(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
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 free variables in a with the expressions in to. For every i smaller than num_exprs,...
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_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:2884
def Abs(arg)
Definition: z3py.py:8907
def PbEq(args, k, ctx=None)
Definition: z3py.py:8997
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:10503
def user_prop_created(ctx, cb, id)
Definition: z3py.py:11393
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:8394
def PropagateFunction(name, *sig)
Definition: z3py.py:11445
def is_app(a)
Definition: z3py.py:1260
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:10375
def Union(*args)
Definition: z3py.py:11161
def get_map_func(a)
Definition: z3py.py:4667
def RealVar(idx, ctx=None)
Definition: z3py.py:1478
def z3_debug()
Definition: z3py.py:62
def If(a, b, c, ctx=None)
Definition: z3py.py:1376
def StringSort(ctx=None)
Definition: z3py.py:10721
def is_string_value(a)
Definition: z3py.py:10887
def Float64(ctx=None)
Definition: z3py.py:9403
def fpIsPositive(a, ctx=None)
Definition: z3py.py:10352
def AndThen(*ts, **ks)
Definition: z3py.py:8272
def substitute_vars(t, *m)
Definition: z3py.py:8814
def ParOr(*ts, **ks)
Definition: z3py.py:8326
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8746
def is_and(a)
Definition: z3py.py:1612
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:10198
def FailIf(p, ctx=None)
Definition: z3py.py:8687
def is_array_sort(a)
Definition: z3py.py:4598
def PrefixOf(a, b)
Definition: z3py.py:10970
def fpPlusInfinity(s)
Definition: z3py.py:9952
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5457
def EnumSort(name, values, ctx=None)
Definition: z3py.py:5378
def prove(claim, show=False, **keywords)
Definition: z3py.py:9069
def RTZ(ctx=None)
Definition: z3py.py:9686
def RTN(ctx=None)
Definition: z3py.py:9676
def RecAddDefinition(f, args, body)
Definition: z3py.py:927
def IndexOf(s, substr, offset=None)
Definition: z3py.py:11034
def is_arith(a)
Definition: z3py.py:2656
def describe_probes()
Definition: z3py.py:8650
def is_arith_sort(s)
Definition: z3py.py:2355
def SetHasSize(a, k)
Definition: z3py.py:4871
def Distinct(*args)
Definition: z3py.py:1399
def get_version_string()
Definition: z3py.py:83
def is_to_int(a)
Definition: z3py.py:2935
def is_false(a)
Definition: z3py.py:1598
def is_bv(a)
Definition: z3py.py:3935
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:9651
def simplify_param_descrs()
Definition: z3py.py:8776
def Not(a, ctx=None)
Definition: z3py.py:1806
def is_func_decl(a)
Definition: z3py.py:850
def Update(a, *args)
Definition: z3py.py:4738
def fpMax(a, b, ctx=None)
Definition: z3py.py:10272
def SignExt(n, a)
Definition: z3py.py:4354
def disable_trace(msg)
Definition: z3py.py:79
def RotateLeft(a, b)
Definition: z3py.py:4322
def is_mul(a)
Definition: z3py.py:2795
def is_re(s)
Definition: z3py.py:11143
def RecFunction(name, *sig)
Definition: z3py.py:909
def EmptySet(s)
Definition: z3py.py:4913
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:11293
def is_K(a)
Definition: z3py.py:4629
def When(p, t, ctx=None)
Definition: z3py.py:8709
def is_not(a)
Definition: z3py.py:1648
def is_bool(a)
Definition: z3py.py:1562
def is_sort(s)
Definition: z3py.py:647
def Float128(ctx=None)
Definition: z3py.py:9415
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10540
def fpNaN(s)
Definition: z3py.py:9935
def is_le(a)
Definition: z3py.py:2860
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:7394
def StrFromCode(c)
Definition: z3py.py:11102
def is_ast(a)
Definition: z3py.py:451
def get_var_index(a)
Definition: z3py.py:1330
def user_prop_fresh(ctx, _new_ctx)
Definition: z3py.py:11367
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:10594
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4499
def is_eq(a)
Definition: z3py.py:1660
def Map(f, *args)
Definition: z3py.py:4814
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:10213
def is_app_of(a, k)
Definition: z3py.py:1363
def is_rational_value(a)
Definition: z3py.py:2747
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:10001
def Complement(re)
Definition: z3py.py:11225
def FreshFunction(*sig)
Definition: z3py.py:886
def RoundTowardPositive(ctx=None)
Definition: z3py.py:9661
def is_fprm(a)
Definition: z3py.py:9691
def fpIsNormal(a, ctx=None)
Definition: z3py.py:10334
def get_default_fp_sort(ctx=None)
Definition: z3py.py:9298
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:10228
def Implies(a, b, ctx=None)
Definition: z3py.py:1776
def UGE(a, b)
Definition: z3py.py:4191
def probe_description(name, ctx=None)
Definition: z3py.py:8641
def IsSubset(a, b)
Definition: z3py.py:5011
def SRem(a, b)
Definition: z3py.py:4269
def DatatypeSort(name, ctx=None)
Definition: z3py.py:5349
def BVSubNoOverflow(a, b)
Definition: z3py.py:4464
def tactic_description(name, ctx=None)
Definition: z3py.py:8435
def get_as_array_func(n)
Definition: z3py.py:6690
def FloatSingle(ctx=None)
Definition: z3py.py:9397
def is_bv_value(a)
Definition: z3py.py:3949
def Bool(name, ctx=None)
Definition: z3py.py:1719
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9671
def Plus(re)
Definition: z3py.py:11199
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:5354
def fpIsZero(a, ctx=None)
Definition: z3py.py:10328
def RNE(ctx=None)
Definition: z3py.py:9646
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:8361
def RTP(ctx=None)
Definition: z3py.py:9666
def is_is_int(a)
Definition: z3py.py:2908
def reset_params()
Definition: z3py.py:295
def BVRedOr(a)
Definition: z3py.py:4443
def Product(*args)
Definition: z3py.py:8882
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:4011
def is_mod(a)
Definition: z3py.py:2848
def FloatQuadruple(ctx=None)
Definition: z3py.py:9421
def UGT(a, b)
Definition: z3py.py:4209
def RNA(ctx=None)
Definition: z3py.py:9656
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2231
def is_fp_value(a)
Definition: z3py.py:9861
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:10399
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:10181
def IsMember(e, s)
Definition: z3py.py:5000
def Store(a, *args)
Definition: z3py.py:4781
def user_prop_final(ctx, cb)
Definition: z3py.py:11400
def Var(idx, s)
Definition: z3py.py:1465
def Xor(a, b, ctx=None)
Definition: z3py.py:1790
def CharVal(ch, ctx=None)
Definition: z3py.py:10823
def eq(a, b)
Definition: z3py.py:472
def solve_using(s, *args, **keywords)
Definition: z3py.py:9038
def SubString(s, offset, length)
Definition: z3py.py:10920
def user_prop_diseq(ctx, cb, x, y)
Definition: z3py.py:11414
def Empty(s)
Definition: z3py.py:10930
def to_ContextObj(ptr)
Definition: z3py.py:11361
def SetUnion(*args)
Definition: z3py.py:4931
def Float16(ctx=None)
Definition: z3py.py:9379
def With(t, *args, **keys)
Definition: z3py.py:8366
def FullSet(s)
Definition: z3py.py:4922
def Length(s)
Definition: z3py.py:11063
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:5366
def is_select(a)
Definition: z3py.py:4877
def is_finite_domain(a)
Definition: z3py.py:7722
def is_const_array(a)
Definition: z3py.py:4616
def ToReal(a)
Definition: z3py.py:3349
def BVSNegNoOverflow(a)
Definition: z3py.py:4485
def Array(name, *sorts)
Definition: z3py.py:4724
def PartialOrder(a, index)
Definition: z3py.py:11281
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:10299
def LShR(a, b)
Definition: z3py.py:4290
def set_option(*args, **kws)
Definition: z3py.py:301
def Const(name, sort)
Definition: z3py.py:1432
def fpAbs(a, ctx=None)
Definition: z3py.py:10090
def is_gt(a)
Definition: z3py.py:2896
def OrElse(*ts, **ks)
Definition: z3py.py:8305
def And(*args)
Definition: z3py.py:1840
def CharSort(ctx=None)
Definition: z3py.py:10730
def TransitiveClosure(f)
Definition: z3py.py:11297
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10576
def RotateRight(a, b)
Definition: z3py.py:4338
def user_prop_decide(ctx, cb, t_ref, idx_ref, phase_ref)
Definition: z3py.py:11424
def ToInt(a)
Definition: z3py.py:3367
def user_prop_pop(ctx, cb, num_scopes)
Definition: z3py.py:11356
def fpZero(s, negative)
Definition: z3py.py:9994
def solve(*args, **keywords)
Definition: z3py.py:9008
def is_algebraic_value(a)
Definition: z3py.py:2769
def Int(name, ctx=None)
Definition: z3py.py:3239
def FloatHalf(ctx=None)
Definition: z3py.py:9385
def WithParams(t, p)
Definition: z3py.py:8380
def deserialize(st)
Definition: z3py.py:1119
def is_lt(a)
Definition: z3py.py:2872
def Q(a, b, ctx=None)
Definition: z3py.py:3226
def String(name, ctx=None)
Definition: z3py.py:10903
def BVRedAnd(a)
Definition: z3py.py:4436
def user_prop_eq(ctx, cb, x, y)
Definition: z3py.py:11406
def is_expr(a)
Definition: z3py.py:1237
def tactics(ctx=None)
Definition: z3py.py:8424
def Sum(*args)
Definition: z3py.py:8856
def SetComplement(s)
Definition: z3py.py:4979
def fpEQ(a, b, ctx=None)
Definition: z3py.py:10411
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:9265
def is_default(a)
Definition: z3py.py:4658
def UDiv(a, b)
Definition: z3py.py:4227
def user_prop_fixed(ctx, cb, id, value)
Definition: z3py.py:11385
def Concat(*args)
Definition: z3py.py:4073
def fpIsInf(a, ctx=None)
Definition: z3py.py:10317
def fpMinusZero(s)
Definition: z3py.py:9988
def CharIsDigit(ch, ctx=None)
Definition: z3py.py:10844
def Contains(a, b)
Definition: z3py.py:11000
def AtLeast(*args)
Definition: z3py.py:8930
def URem(a, b)
Definition: z3py.py:4248
def is_to_real(a)
Definition: z3py.py:2920
def fpMin(a, b, ctx=None)
Definition: z3py.py:10257
def is_const(a)
Definition: z3py.py:1286
def SetDel(s, e)
Definition: z3py.py:4968
def describe_tactics()
Definition: z3py.py:8444
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:10435
def RealVal(val, ctx=None)
Definition: z3py.py:3191
def CharToBv(ch, ctx=None)
Definition: z3py.py:10836
def set_param(*args, **kws)
Definition: z3py.py:271
def IntToStr(s)
Definition: z3py.py:11089
def get_full_version()
Definition: z3py.py:101
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:10340
def BoolVal(val, ctx=None)
Definition: z3py.py:1700
def fpInfinity(s, negative)
Definition: z3py.py:9975
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:7373
def Bools(names, ctx=None)
Definition: z3py.py:1731
def FP(name, fpsort, ctx=None)
Definition: z3py.py:10047
def is_bv_sort(s)
Definition: z3py.py:3467
def Range(lo, hi, ctx=None)
Definition: z3py.py:11256
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4492
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:10293
def StringVal(s, ctx=None)
Definition: z3py.py:10896
def is_idiv(a)
Definition: z3py.py:2836
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10558
def probes(ctx=None)
Definition: z3py.py:8630
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4450
def TryFor(t, ms, ctx=None)
Definition: z3py.py:8415
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9876
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7761
def is_string(a)
Definition: z3py.py:10879
def TreeOrder(a, index)
Definition: z3py.py:11289
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3265
def Function(name, *sig)
Definition: z3py.py:863
def Real(name, ctx=None)
Definition: z3py.py:3292
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:10604
def Full(s)
Definition: z3py.py:10950
def is_fp(a)
Definition: z3py.py:9847
def Diff(a, b, ctx=None)
Definition: z3py.py:11268
def is_array(a)
Definition: z3py.py:4602
def IsInt(a)
Definition: z3py.py:3385
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4457
def StrToInt(s)
Definition: z3py.py:11073
def is_add(a)
Definition: z3py.py:2783
def substitute_funs(t, *m)
Definition: z3py.py:8834
def LastIndexOf(s, substr)
Definition: z3py.py:11054
def fpIsNaN(a, ctx=None)
Definition: z3py.py:10305
def is_or(a)
Definition: z3py.py:1624
def is_distinct(a)
Definition: z3py.py:1670
def FloatDouble(ctx=None)
Definition: z3py.py:9409
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1747
def BoolSort(ctx=None)
Definition: z3py.py:1682
def is_seq(a)
Definition: z3py.py:10869
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7691
def Strings(names, ctx=None)
Definition: z3py.py:10912
def RealSort(ctx=None)
Definition: z3py.py:3146
def Ext(a, b)
Definition: z3py.py:4859
def IntSort(ctx=None)
Definition: z3py.py:3129
def Re(s, ctx=None)
Definition: z3py.py:11108
def is_int(a)
Definition: z3py.py:2677
def append_log(s)
Definition: z3py.py:119
def is_pattern(a)
Definition: z3py.py:1924
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:10668
def main_ctx()
Definition: z3py.py:239
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:4052
def Intersect(*args)
Definition: z3py.py:11181
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8729
def enable_trace(msg)
Definition: z3py.py:75
def is_as_array(n)
Definition: z3py.py:6685
def user_prop_push(ctx, cb)
Definition: z3py.py:11350
def Select(a, *args)
Definition: z3py.py:4798
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:10520
def is_finite_domain_sort(s)
Definition: z3py.py:7699
def IntVal(val, ctx=None)
Definition: z3py.py:3179
def CharFromBv(ch, ctx=None)
Definition: z3py.py:10831
def RatVal(a, b, ctx=None)
Definition: z3py.py:3210
def DeclareSort(name, ctx=None)
Definition: z3py.py:693
def Loop(re, lo, hi=0)
Definition: z3py.py:11243
def is_probe(p)
Definition: z3py.py:8612
def ArraySort(*sig)
Definition: z3py.py:4691
def Sqrt(a, ctx=None)
Definition: z3py.py:3402
def Replace(s, src, dst)
Definition: z3py.py:11019
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2213
def substitute(t, *m)
Definition: z3py.py:8781
def is_map(a)
Definition: z3py.py:4642
def BV2Int(a, is_signed=False)
Definition: z3py.py:3964
def SubSeq(s, offset, length)
Definition: z3py.py:10925
def ReSort(s)
Definition: z3py.py:11127
def fpPlusZero(s)
Definition: z3py.py:9982
def mk_not(a)
Definition: z3py.py:1825
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3320
def Int2BV(a, num_bits)
Definition: z3py.py:3987
def help_simplify()
Definition: z3py.py:8771
def SeqSort(s)
Definition: z3py.py:10740
def get_version()
Definition: z3py.py:92
def StrToCode(s)
Definition: z3py.py:11096
def fpIsNegative(a, ctx=None)
Definition: z3py.py:10346
def PbLe(args, k)
Definition: z3py.py:8975
def K(dom, v)
Definition: z3py.py:4837
def get_ctx(ctx)
Definition: z3py.py:267
def fpMinusInfinity(s)
Definition: z3py.py:9969
def is_true(a)
Definition: z3py.py:1580
def is_fprm_sort(s)
Definition: z3py.py:9442
def Reals(names, ctx=None)
Definition: z3py.py:3305
def BitVec(name, bv, ctx=None)
Definition: z3py.py:4028
def is_implies(a)
Definition: z3py.py:1636
def Ints(names, ctx=None)
Definition: z3py.py:3252
def SetDifference(a, b)
Definition: z3py.py:4989
def FreshInt(prefix="x", ctx=None)
Definition: z3py.py:3278
def LinearOrder(a, index)
Definition: z3py.py:11285
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:10071
def fpNeg(a, ctx=None)
Definition: z3py.py:10113
def CreateDatatypes(*ds)
Definition: z3py.py:5149
def fpGT(a, b, ctx=None)
Definition: z3py.py:10387
def Cbrt(a, ctx=None)
Definition: z3py.py:3415
def is_fp_sort(s)
Definition: z3py.py:9431
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4471
def fpLT(a, b, ctx=None)
Definition: z3py.py:10363
def get_param(name)
Definition: z3py.py:307
def MultiPattern(*args)
Definition: z3py.py:1942
def AllChar(regex_sort, ctx=None)
Definition: z3py.py:11273
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:8345
def AtMost(*args)
Definition: z3py.py:8912
def RealVarVector(n, ctx=None)
Definition: z3py.py:1489
def FreshReal(prefix="b", ctx=None)
Definition: z3py.py:3335
def SetSort(s)
Sets.
Definition: z3py.py:4908
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3996
def is_quantifier(a)
Definition: z3py.py:2164
def SetIntersect(*args)
Definition: z3py.py:4944
def fpRem(a, b, ctx=None)
Definition: z3py.py:10243
def Lambda(vs, body)
Definition: z3py.py:2252
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:9289
def Star(re)
Definition: z3py.py:11230
def Model(ctx=None)
Definition: z3py.py:6680
def Default(a)
Definition: z3py.py:4770
def Or(*args)
Definition: z3py.py:1873
def ZeroExt(n, a)
Definition: z3py.py:4384
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9241
def SetAdd(s, e)
Definition: z3py.py:4957
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4478
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:9220
def open_log(fname)
Definition: z3py.py:114
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:10287
def is_store(a)
Definition: z3py.py:4890
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:9641
def to_Ast(ptr)
Definition: z3py.py:11380
def Float32(ctx=None)
Definition: z3py.py:9391
def is_fprm_value(a)
Definition: z3py.py:9704
def is_real(a)
Definition: z3py.py:2696
def Extract(high, low, a)
Definition: z3py.py:4119
def to_symbol(s, ctx=None)
Definition: z3py.py:124
def is_div(a)
Definition: z3py.py:2819
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:9302
def CharToInt(ch, ctx=None)
Definition: z3py.py:10840
def FreshBool(prefix="b", ctx=None)
Definition: z3py.py:1762
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:10626
def is_finite_domain_value(a)
Definition: z3py.py:7776
def ULE(a, b)
Definition: z3py.py:4155
def FreshConst(sort, prefix="c")
Definition: z3py.py:1459
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:10423
def RoundTowardZero(ctx=None)
Definition: z3py.py:9681
def is_sub(a)
Definition: z3py.py:2807
def ULT(a, b)
Definition: z3py.py:4173
def ensure_prop_closures()
Definition: z3py.py:11344
def InRe(s, re)
Definition: z3py.py:11147
def is_int_value(a)
Definition: z3py.py:2723
def is_var(a)
Definition: z3py.py:1305
def SuffixOf(a, b)
Definition: z3py.py:10985
def Then(*ts, **ks)
Definition: z3py.py:8292
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:10464
def Option(re)
Definition: z3py.py:11212
def PbGe(args, k)
Definition: z3py.py:8986
def z3_error_handler(c, e)
Definition: z3py.py:174
def Unit(a)
Definition: z3py.py:10965
def RepeatBitVec(n, a)
Definition: z3py.py:4412
def Consts(names, sort)
Definition: z3py.py:1444
def fpToReal(x, ctx=None)
Definition: z3py.py:10648