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, Iterator
58
59from collections.abc import Callable
60from typing import (
61 Any,
62 Iterable,
63 Sequence
64)
65
66
67Z3_DEBUG = __debug__
68
69
71 global Z3_DEBUG
72 return Z3_DEBUG
73
74
75if sys.version_info.major < 3:
76 def _is_int(v):
77 return isinstance(v, (int, long))
78else:
79 def _is_int(v):
80 return isinstance(v, int)
81
82
83def enable_trace(msg):
85
86
89
90
92 major = ctypes.c_uint(0)
93 minor = ctypes.c_uint(0)
94 build = ctypes.c_uint(0)
95 rev = ctypes.c_uint(0)
96 Z3_get_version(major, minor, build, rev)
97 return "%s.%s.%s" % (major.value, minor.value, build.value)
98
99
101 major = ctypes.c_uint(0)
102 minor = ctypes.c_uint(0)
103 build = ctypes.c_uint(0)
104 rev = ctypes.c_uint(0)
105 Z3_get_version(major, minor, build, rev)
106 return (major.value, minor.value, build.value, rev.value)
107
108
110 return Z3_get_full_version()
111
112
113def _z3_assert(cond, msg):
114 if not cond:
115 raise Z3Exception(msg)
116
117
119 _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
120
121
122def open_log(fname):
123 """Log interaction to a file. This function must be invoked immediately after init(). """
124 Z3_open_log(fname)
125
126
128 """Append user-defined string to interaction log. """
130
131
132def to_symbol(s, ctx = None):
133 """Convert an integer or string into a Z3 symbol."""
134 if _is_int(s):
135 return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
136 else:
137 return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
138
139
140def _symbol2py(ctx, s):
141 """Convert a Z3 symbol back into a Python object. """
142 if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
143 return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
144 else:
145 return Z3_get_symbol_string(ctx.ref(), s)
146
147# Hack for having nary functions that can receive one argument that is the
148# list of arguments.
149# Use this when function takes a single list of arguments
150
151
152def _get_args(args):
153 try:
154 if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
155 return args[0]
156 elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
157 return [arg for arg in args[0]]
158 elif len(args) == 1 and isinstance(args[0], Iterator):
159 return list(args[0])
160 else:
161 return args
162 except TypeError: # len is not necessarily defined when args is not a sequence (use reflection?)
163 return args
164
165# Use this when function takes multiple arguments
166
167
169 try:
170 if isinstance(args, (set, AstVector, tuple)):
171 return [arg for arg in args]
172 else:
173 return args
174 except Exception:
175 return args
176
177
179 if isinstance(val, bool):
180 return "true" if val else "false"
181 return str(val)
182
183
185 # Do nothing error handler, just avoid exit(0)
186 # The wrappers in z3core.py will raise a Z3Exception if an error is detected
187 return
188
189
190class Context:
191 """A Context manages all other Z3 objects, global configuration options, etc.
192
193 Z3Py uses a default global context. For most applications this is sufficient.
194 An application may use multiple Z3 contexts. Objects created in one context
195 cannot be used in another one. However, several objects may be "translated" from
196 one context to another. It is not safe to access Z3 objects from multiple threads.
197 The only exception is the method `interrupt()` that can be used to interrupt() a long
198 computation.
199 The initialization method receives global configuration options for the new context.
200 """
201
202 def __init__(self, *args, **kws):
203 if z3_debug():
204 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
205 conf = Z3_mk_config()
206 for key in kws:
207 value = kws[key]
208 Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
209 prev = None
210 for a in args:
211 if prev is None:
212 prev = a
213 else:
214 Z3_set_param_value(conf, str(prev), _to_param_value(a))
215 prev = None
217 self.owner = True
218 self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
219 Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
220 Z3_del_config(conf)
221
222 def __del__(self):
223 if Z3_del_context is not None and self.owner:
224 Z3_del_context(self.ctx)
225 self.ctx = None
226 self.eh = None
227
228 def ref(self):
229 """Return a reference to the actual C pointer to the Z3 context."""
230 return self.ctx
231
232 def interrupt(self):
233 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
234
235 This method can be invoked from a thread different from the one executing the
236 interruptible procedure.
237 """
238 Z3_interrupt(self.ref())
239
240 def param_descrs(self):
241 """Return the global parameter description set."""
242 return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self)
243
244 def set_ast_print_mode(self, mode):
245 """Set the pretty printing mode for ASTs.
246
247 The following modes are available:
248 - Z3_PRINT_SMTLIB_FULL (0): Print AST nodes in SMTLIB verbose format.
249 - Z3_PRINT_LOW_LEVEL (1): Print AST nodes using a low-level format.
250 - Z3_PRINT_SMTLIB2_COMPLIANT (2): Print AST nodes in SMTLIB 2.x compliant format.
251
252 Example:
253 >>> c = Context()
254 >>> x = Int('x', c)
255 >>> c.set_ast_print_mode(Z3_PRINT_SMTLIB2_COMPLIANT)
256 >>> print(x)
257 x
258 """
259 Z3_set_ast_print_mode(self.ref(), mode)
260
261
262# Global Z3 context
263_main_ctx = None
264
265
266def main_ctx() -> Context:
267 """Return a reference to the global Z3 context.
268
269 >>> x = Real('x')
270 >>> x.ctx == main_ctx()
271 True
272 >>> c = Context()
273 >>> c == main_ctx()
274 False
275 >>> x2 = Real('x', c)
276 >>> x2.ctx == c
277 True
278 >>> eq(x, x2)
279 False
280 """
281 global _main_ctx
282 if _main_ctx is None:
283 _main_ctx = Context()
284 return _main_ctx
285
286
287def _get_ctx(ctx) -> Context:
288 if ctx is None:
289 return main_ctx()
290 else:
291 return ctx
292
293
294def get_ctx(ctx) -> Context:
295 return _get_ctx(ctx)
296
297
298def set_param(*args, **kws):
299 """Set Z3 global (or module) parameters.
300
301 >>> set_param(precision=10)
302 """
303 if z3_debug():
304 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
305 new_kws = {}
306 for k in kws:
307 v = kws[k]
308 if not set_pp_option(k, v):
309 new_kws[k] = v
310 for key in new_kws:
311 value = new_kws[key]
312 Z3_global_param_set(str(key).upper(), _to_param_value(value))
313 prev = None
314 for a in args:
315 if prev is None:
316 prev = a
317 else:
319 prev = None
320
321
322def reset_params() -> None:
323 """Reset all global (or module) parameters.
324 """
326
327
328def set_option(*args, **kws):
329 """Alias for 'set_param' for backward compatibility.
330 """
331 return set_param(*args, **kws)
332
333
334def get_param(name):
335 """Return the value of a Z3 global (or module) parameter
336
337 >>> get_param('nlsat.reorder')
338 'true'
339 """
340 ptr = (ctypes.c_char_p * 1)()
341 if Z3_global_param_get(str(name), ptr):
342 r = z3core._to_pystr(ptr[0])
343 return r
344 raise Z3Exception("failed to retrieve value for '%s'" % name)
345
346
351
352# Mark objects that use pretty printer
353
354
356 """Superclass for all Z3 objects that have support for pretty printing."""
357
358 def use_pp(self):
359 return True
360
361 def _repr_html_(self):
362 in_html = in_html_mode()
363 set_html_mode(True)
364 res = repr(self)
365 set_html_mode(in_html)
366 return res
367
368
370 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
371
372 def __init__(self, ast, ctx=None):
373 self.ast = ast
374 self.ctx = _get_ctx(ctx)
375 Z3_inc_ref(self.ctx.ref(), self.as_ast())
376
377 def __del__(self):
378 if self.ctx.ref() is not None and self.ast is not None and Z3_dec_ref is not None:
379 Z3_dec_ref(self.ctx.ref(), self.as_ast())
380 self.ast = None
381
382 def __deepcopy__(self, memo={}):
383 return _to_ast_ref(self.ast, self.ctx)
384
385 def __str__(self):
386 return obj_to_string(self)
387
388 def __repr__(self):
389 return obj_to_string(self)
390
391 def __eq__(self, other):
392 return self.eq(other)
393
394 def __hash__(self):
395 return self.hash()
396
397 def __nonzero__(self):
398 return self.__bool__()
399
400 def __bool__(self):
401 if is_true(self):
402 return True
403 elif is_false(self):
404 return False
405 elif is_eq(self) and self.num_args() == 2:
406 return self.arg(0).eq(self.arg(1))
407 else:
408 raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
409
410 def sexpr(self):
411 """Return a string representing the AST node in s-expression notation.
412
413 >>> x = Int('x')
414 >>> ((x + 1)*x).sexpr()
415 '(* (+ x 1) x)'
416 """
417 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
418
419 def as_ast(self):
420 """Return a pointer to the corresponding C Z3_ast object."""
421 return self.ast
422
423 def get_id(self):
424 """Return unique identifier for object. It can be used for hash-tables and maps."""
425 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
426
427 def ctx_ref(self):
428 """Return a reference to the C context where this AST node is stored."""
429 return self.ctx.ref()
430
431 def eq(self, other):
432 """Return `True` if `self` and `other` are structurally identical.
433
434 >>> x = Int('x')
435 >>> n1 = x + 1
436 >>> n2 = 1 + x
437 >>> n1.eq(n2)
438 False
439 >>> n1 = simplify(n1)
440 >>> n2 = simplify(n2)
441 >>> n1.eq(n2)
442 True
443 """
444 if z3_debug():
445 _z3_assert(is_ast(other), "Z3 AST expected")
446 return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
447
448 def translate(self, target):
449 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
450
451 >>> c1 = Context()
452 >>> c2 = Context()
453 >>> x = Int('x', c1)
454 >>> y = Int('y', c2)
455 >>> # Nodes in different contexts can't be mixed.
456 >>> # However, we can translate nodes from one context to another.
457 >>> x.translate(c2) + y
458 x + y
459 """
460 if z3_debug():
461 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
462 return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
463
464 def __copy__(self):
465 return self.translate(self.ctx)
466
467 def hash(self):
468 """Return a hashcode for the `self`.
469
470 >>> n1 = simplify(Int('x') + 1)
471 >>> n2 = simplify(2 + Int('x') - 1)
472 >>> n1.hash() == n2.hash()
473 True
474 """
475 return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
476
477 def py_value(self):
478 """Return a Python value that is equivalent to `self`."""
479 return None
480
481
482def is_ast(a : Any) -> bool:
483 """Return `True` if `a` is an AST node.
484
485 >>> is_ast(10)
486 False
487 >>> is_ast(IntVal(10))
488 True
489 >>> is_ast(Int('x'))
490 True
491 >>> is_ast(BoolSort())
492 True
493 >>> is_ast(Function('f', IntSort(), IntSort()))
494 True
495 >>> is_ast("x")
496 False
497 >>> is_ast(Solver())
498 False
499 """
500 return isinstance(a, AstRef)
501
502
503def eq(a : AstRef, b : AstRef) -> bool:
504 """Return `True` if `a` and `b` are structurally identical AST nodes.
505
506 >>> x = Int('x')
507 >>> y = Int('y')
508 >>> eq(x, y)
509 False
510 >>> eq(x + 1, x + 1)
511 True
512 >>> eq(x + 1, 1 + x)
513 False
514 >>> eq(simplify(x + 1), simplify(1 + x))
515 True
516 """
517 if z3_debug():
518 _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
519 return a.eq(b)
520
521
522def _ast_kind(ctx : Context, a : Any) -> int:
523 if is_ast(a):
524 a = a.as_ast()
525 return Z3_get_ast_kind(ctx.ref(), a)
526
527
528def _ctx_from_ast_arg_list(args, default_ctx=None):
529 ctx = None
530 for a in args:
531 if is_ast(a) or is_probe(a):
532 if ctx is None:
533 ctx = a.ctx
534 else:
535 if z3_debug():
536 _z3_assert(ctx == a.ctx, "Context mismatch")
537 if ctx is None:
538 ctx = default_ctx
539 return ctx
540
541
543 return _ctx_from_ast_arg_list(args)
544
545
547 sz = len(args)
548 _args = (FuncDecl * sz)()
549 for i in range(sz):
550 _args[i] = args[i].as_func_decl()
551 return _args, sz
552
553
555 sz = len(args)
556 _args = (Ast * sz)()
557 for i in range(sz):
558 _args[i] = args[i].as_ast()
559 return _args, sz
560
561
562def _to_ref_array(ref, args):
563 sz = len(args)
564 _args = (ref * sz)()
565 for i in range(sz):
566 _args[i] = args[i].as_ast()
567 return _args, sz
568
569
570def _to_ast_ref(a, ctx):
571 k = _ast_kind(ctx, a)
572 if k == Z3_SORT_AST:
573 return _to_sort_ref(a, ctx)
574 elif k == Z3_FUNC_DECL_AST:
575 return _to_func_decl_ref(a, ctx)
576 else:
577 return _to_expr_ref(a, ctx)
578
579
580
585
586def _sort_kind(ctx, s):
587 return Z3_get_sort_kind(ctx.ref(), s)
588
589
591 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
592
593 def as_ast(self):
594 return Z3_sort_to_ast(self.ctx_ref(), self.ast)
595
596 def get_id(self):
597 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
598
599 def kind(self):
600 """Return the Z3 internal kind of a sort.
601 This method can be used to test if `self` is one of the Z3 builtin sorts.
602
603 >>> b = BoolSort()
604 >>> b.kind() == Z3_BOOL_SORT
605 True
606 >>> b.kind() == Z3_INT_SORT
607 False
608 >>> A = ArraySort(IntSort(), IntSort())
609 >>> A.kind() == Z3_ARRAY_SORT
610 True
611 >>> A.kind() == Z3_INT_SORT
612 False
613 """
614 return _sort_kind(self.ctx, self.ast)
615
616 def subsort(self, other):
617 """Return `True` if `self` is a subsort of `other`.
618
619 >>> IntSort().subsort(RealSort())
620 True
621 """
622 return False
623
624 def cast(self, val):
625 """Try to cast `val` as an element of sort `self`.
626
627 This method is used in Z3Py to convert Python objects such as integers,
628 floats, longs and strings into Z3 expressions.
629
630 >>> x = Int('x')
631 >>> RealSort().cast(x)
632 ToReal(x)
633 """
634 if z3_debug():
635 _z3_assert(is_expr(val), "Z3 expression expected")
636 _z3_assert(self.eq(val.sort()), "Sort mismatch")
637 return val
638
639 def name(self):
640 """Return the name (string) of sort `self`.
641
642 >>> BoolSort().name()
643 'Bool'
644 >>> ArraySort(IntSort(), IntSort()).name()
645 'Array'
646 """
647 return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
648
649 def __eq__(self, other):
650 """Return `True` if `self` and `other` are the same Z3 sort.
651
652 >>> p = Bool('p')
653 >>> p.sort() == BoolSort()
654 True
655 >>> p.sort() == IntSort()
656 False
657 """
658 if other is None:
659 return False
660 return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
661
662 def __ne__(self, other):
663 """Return `True` if `self` and `other` are not the same Z3 sort.
664
665 >>> p = Bool('p')
666 >>> p.sort() != BoolSort()
667 False
668 >>> p.sort() != IntSort()
669 True
670 """
671 return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
672
673 def __gt__(self, other):
674 """Create the function space Array(self, other)"""
675 return ArraySort(self, other)
676
677 def __hash__(self):
678 """ Hash code. """
679 return AstRef.__hash__(self)
680
681
682def is_sort(s : Any) -> bool:
683 """Return `True` if `s` is a Z3 sort.
684
685 >>> is_sort(IntSort())
686 True
687 >>> is_sort(Int('x'))
688 False
689 >>> is_expr(Int('x'))
690 True
691 """
692 return isinstance(s, SortRef)
693
694
695def _to_sort_ref(s, ctx):
696 if z3_debug():
697 _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
698 if Z3_is_finite_set_sort(ctx.ref(), s):
699 return FiniteSetSortRef(s, ctx)
700 k = _sort_kind(ctx, s)
701 if k == Z3_BOOL_SORT:
702 return BoolSortRef(s, ctx)
703 elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
704 return ArithSortRef(s, ctx)
705 elif k == Z3_BV_SORT:
706 return BitVecSortRef(s, ctx)
707 elif k == Z3_ARRAY_SORT:
708 return ArraySortRef(s, ctx)
709 elif k == Z3_DATATYPE_SORT:
710 return DatatypeSortRef(s, ctx)
711 elif k == Z3_FINITE_DOMAIN_SORT:
712 return FiniteDomainSortRef(s, ctx)
713 elif k == Z3_FLOATING_POINT_SORT:
714 return FPSortRef(s, ctx)
715 elif k == Z3_ROUNDING_MODE_SORT:
716 return FPRMSortRef(s, ctx)
717 elif k == Z3_RE_SORT:
718 return ReSortRef(s, ctx)
719 elif k == Z3_SEQ_SORT:
720 return SeqSortRef(s, ctx)
721 elif k == Z3_CHAR_SORT:
722 return CharSortRef(s, ctx)
723 elif k == Z3_TYPE_VAR:
724 return TypeVarRef(s, ctx)
725 return SortRef(s, ctx)
726
727
728def _sort(ctx : Context, a : Any) -> SortRef:
729 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
730
731
732def DeclareSort(name, ctx= None) -> SortRef:
733 """Create a new uninterpreted sort named `name`.
734
735 If `ctx=None`, then the new sort is declared in the global Z3Py context.
736
737 >>> A = DeclareSort('A')
738 >>> a = Const('a', A)
739 >>> b = Const('b', A)
740 >>> a.sort() == A
741 True
742 >>> b.sort() == A
743 True
744 >>> a == b
745 a == b
746 """
747 ctx = _get_ctx(ctx)
748 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
749
751 """Type variable reference"""
752
753 def subsort(self, other):
754 return True
755
756 def cast(self, val):
757 return val
758
759
760def DeclareTypeVar(name, ctx=None):
761 """Create a new type variable named `name`.
762
763 If `ctx=None`, then the new sort is declared in the global Z3Py context.
764
765 """
766 ctx = _get_ctx(ctx)
767 return TypeVarRef(Z3_mk_type_variable(ctx.ref(), to_symbol(name, ctx)), ctx)
768
769
770
775
776
778 """Function declaration. Every constant and function have an associated declaration.
779
780 The declaration assigns a name, a sort (i.e., type), and for function
781 the sort (i.e., type) of each of its arguments. Note that, in Z3,
782 a constant is a function with 0 arguments.
783 """
784
785 def as_ast(self):
786 return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
787
788 def get_id(self):
789 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
790
791 def as_func_decl(self):
792 return self.ast
793
794 def name(self):
795 """Return the name of the function declaration `self`.
796
797 >>> f = Function('f', IntSort(), IntSort())
798 >>> f.name()
799 'f'
800 >>> isinstance(f.name(), str)
801 True
802 """
803 return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
804
805 def arity(self):
806 """Return the number of arguments of a function declaration.
807 If `self` is a constant, then `self.arity()` is 0.
808
809 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
810 >>> f.arity()
811 2
812 """
813 return int(Z3_get_arity(self.ctx_ref(), self.ast))
814
815 def domain(self, i):
816 """Return the sort of the argument `i` of a function declaration.
817 This method assumes that `0 <= i < self.arity()`.
818
819 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
820 >>> f.domain(0)
821 Int
822 >>> f.domain(1)
823 Real
824 """
825 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
826
827 def range(self):
828 """Return the sort of the range of a function declaration.
829 For constants, this is the sort of the constant.
830
831 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
832 >>> f.range()
833 Bool
834 """
835 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
836
837 def kind(self):
838 """Return the internal kind of a function declaration.
839 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
840
841 >>> x = Int('x')
842 >>> d = (x + 1).decl()
843 >>> d.kind() == Z3_OP_ADD
844 True
845 >>> d.kind() == Z3_OP_MUL
846 False
847 """
848 return Z3_get_decl_kind(self.ctx_ref(), self.ast)
849
850 def params(self):
851 ctx = self.ctx
852 n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
853 result = [None for i in range(n)]
854 for i in range(n):
855 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
856 if k == Z3_PARAMETER_INT:
857 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
858 elif k == Z3_PARAMETER_DOUBLE:
859 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
860 elif k == Z3_PARAMETER_RATIONAL:
861 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
862 elif k == Z3_PARAMETER_SYMBOL:
863 result[i] = _symbol2py(ctx, Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i))
864 elif k == Z3_PARAMETER_SORT:
865 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
866 elif k == Z3_PARAMETER_AST:
867 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
868 elif k == Z3_PARAMETER_FUNC_DECL:
869 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
870 elif k == Z3_PARAMETER_INTERNAL:
871 result[i] = "internal parameter"
872 elif k == Z3_PARAMETER_ZSTRING:
873 result[i] = "internal string"
874 else:
875 raise Z3Exception("Unexpected parameter kind")
876 return result
877
878 def __call__(self, *args):
879 """Create a Z3 application expression using the function `self`, and the given arguments.
880
881 The arguments must be Z3 expressions. This method assumes that
882 the sorts of the elements in `args` match the sorts of the
883 domain. Limited coercion is supported. For example, if
884 args[0] is a Python integer, and the function expects a Z3
885 integer, then the argument is automatically converted into a
886 Z3 integer.
887
888 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
889 >>> x = Int('x')
890 >>> y = Real('y')
891 >>> f(x, y)
892 f(x, y)
893 >>> f(x, x)
894 f(x, ToReal(x))
895 """
896 args = _get_args(args)
897 num = len(args)
898 _args = (Ast * num)()
899 saved = []
900 for i in range(num):
901 # self.domain(i).cast(args[i]) may create a new Z3 expression,
902 # then we must save in 'saved' to prevent it from being garbage collected.
903 tmp = self.domain(i).cast(args[i])
904 saved.append(tmp)
905 _args[i] = tmp.as_ast()
906 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
907
908
910 """Return `True` if `a` is a Z3 function declaration.
911
912 >>> f = Function('f', IntSort(), IntSort())
913 >>> is_func_decl(f)
914 True
915 >>> x = Real('x')
916 >>> is_func_decl(x)
917 False
918 """
919 return isinstance(a, FuncDeclRef)
920
921
922def Function(name, *sig):
923 """Create a new Z3 uninterpreted function with the given sorts.
924
925 >>> f = Function('f', IntSort(), IntSort())
926 >>> f(f(0))
927 f(f(0))
928 """
929 sig = _get_args(sig)
930 if z3_debug():
931 _z3_assert(len(sig) > 0, "At least two arguments expected")
932 arity = len(sig) - 1
933 rng = sig[arity]
934 if z3_debug():
935 _z3_assert(is_sort(rng), "Z3 sort expected")
936 dom = (Sort * arity)()
937 for i in range(arity):
938 if z3_debug():
939 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
940 dom[i] = sig[i].ast
941 ctx = rng.ctx
942 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
943
944
946 """Create a new fresh Z3 uninterpreted function with the given sorts.
947 """
948 sig = _get_args(sig)
949 if z3_debug():
950 _z3_assert(len(sig) > 0, "At least two arguments expected")
951 arity = len(sig) - 1
952 rng = sig[arity]
953 if z3_debug():
954 _z3_assert(is_sort(rng), "Z3 sort expected")
955 dom = (z3.Sort * arity)()
956 for i in range(arity):
957 if z3_debug():
958 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
959 dom[i] = sig[i].ast
960 ctx = rng.ctx
961 return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
962
963
965 return FuncDeclRef(a, ctx)
966
967
968def RecFunction(name, *sig):
969 """Create a new Z3 recursive with the given sorts."""
970 sig = _get_args(sig)
971 if z3_debug():
972 _z3_assert(len(sig) > 0, "At least two arguments expected")
973 arity = len(sig) - 1
974 rng = sig[arity]
975 if z3_debug():
976 _z3_assert(is_sort(rng), "Z3 sort expected")
977 dom = (Sort * arity)()
978 for i in range(arity):
979 if z3_debug():
980 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
981 dom[i] = sig[i].ast
982 ctx = rng.ctx
983 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
984
985
986def RecAddDefinition(f, args, body):
987 """Set the body of a recursive function.
988 Recursive definitions can be simplified if they are applied to ground
989 arguments.
990 >>> ctx = Context()
991 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
992 >>> n = Int('n', ctx)
993 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
994 >>> simplify(fac(5))
995 120
996 >>> s = Solver(ctx=ctx)
997 >>> s.add(fac(n) < 3)
998 >>> s.check()
999 sat
1000 >>> s.model().eval(fac(5))
1001 120
1002 """
1003 if is_app(args):
1004 args = [args]
1005 ctx = body.ctx
1006 args = _get_args(args)
1007 n = len(args)
1008 _args = (Ast * n)()
1009 for i in range(n):
1010 _args[i] = args[i].ast
1011 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
1012
1013
1018
1019
1021 """Constraints, formulas and terms are expressions in Z3.
1022
1023 Expressions are ASTs. Every expression has a sort.
1024 There are three main kinds of expressions:
1025 function applications, quantifiers and bounded variables.
1026 A constant is a function application with 0 arguments.
1027 For quantifier free problems, all expressions are
1028 function applications.
1029 """
1030
1031 def as_ast(self):
1032 return self.ast
1033
1034 def get_id(self):
1035 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
1036
1037 def sort(self):
1038 """Return the sort of expression `self`.
1039
1040 >>> x = Int('x')
1041 >>> (x + 1).sort()
1042 Int
1043 >>> y = Real('y')
1044 >>> (x + y).sort()
1045 Real
1046 """
1047 return _sort(self.ctx, self.as_ast())
1048
1049 def sort_kind(self):
1050 """Shorthand for `self.sort().kind()`.
1051
1052 >>> a = Array('a', IntSort(), IntSort())
1053 >>> a.sort_kind() == Z3_ARRAY_SORT
1054 True
1055 >>> a.sort_kind() == Z3_INT_SORT
1056 False
1057 """
1058 return self.sort().kind()
1059
1060 def __eq__(self, other):
1061 """Return a Z3 expression that represents the constraint `self == other`.
1062
1063 If `other` is `None`, then this method simply returns `False`.
1064
1065 >>> a = Int('a')
1066 >>> b = Int('b')
1067 >>> a == b
1068 a == b
1069 >>> a is None
1070 False
1071 """
1072 if other is None:
1073 return False
1074 a, b = _coerce_exprs(self, other)
1075 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
1076
1077 def __hash__(self):
1078 """ Hash code. """
1079 return AstRef.__hash__(self)
1080
1081 def __ne__(self, other):
1082 """Return a Z3 expression that represents the constraint `self != other`.
1083
1084 If `other` is `None`, then this method simply returns `True`.
1085
1086 >>> a = Int('a')
1087 >>> b = Int('b')
1088 >>> a != b
1089 a != b
1090 >>> a is not None
1091 True
1092 """
1093 if other is None:
1094 return True
1095 a, b = _coerce_exprs(self, other)
1096 _args, sz = _to_ast_array((a, b))
1097 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
1098
1099 def params(self):
1100 return self.decl().params()
1101
1102 def decl(self):
1103 """Return the Z3 function declaration associated with a Z3 application.
1104
1105 >>> f = Function('f', IntSort(), IntSort())
1106 >>> a = Int('a')
1107 >>> t = f(a)
1108 >>> eq(t.decl(), f)
1109 True
1110 >>> (a + 1).decl()
1111 +
1112 """
1113 if z3_debug():
1114 _z3_assert(is_app(self), "Z3 application expected")
1115 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
1116
1117 def kind(self):
1118 """Return the Z3 internal kind of a function application."""
1119 if z3_debug():
1120 _z3_assert(is_app(self), "Z3 application expected")
1122
1123
1124 def num_args(self):
1125 """Return the number of arguments of a Z3 application.
1126
1127 >>> a = Int('a')
1128 >>> b = Int('b')
1129 >>> (a + b).num_args()
1130 2
1131 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1132 >>> t = f(a, b, 0)
1133 >>> t.num_args()
1134 3
1135 """
1136 if z3_debug():
1137 _z3_assert(is_app(self), "Z3 application expected")
1138 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
1139
1140 def arg(self, idx):
1141 """Return argument `idx` of the application `self`.
1142
1143 This method assumes that `self` is a function application with at least `idx+1` arguments.
1144
1145 >>> a = Int('a')
1146 >>> b = Int('b')
1147 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1148 >>> t = f(a, b, 0)
1149 >>> t.arg(0)
1150 a
1151 >>> t.arg(1)
1152 b
1153 >>> t.arg(2)
1154 0
1155 """
1156 if z3_debug():
1157 _z3_assert(is_app(self), "Z3 application expected")
1158 _z3_assert(idx < self.num_args(), "Invalid argument index")
1159 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
1160
1161 def children(self):
1162 """Return a list containing the children of the given expression
1163
1164 >>> a = Int('a')
1165 >>> b = Int('b')
1166 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1167 >>> t = f(a, b, 0)
1168 >>> t.children()
1169 [a, b, 0]
1170 """
1171 if is_app(self):
1172 return [self.arg(i) for i in range(self.num_args())]
1173 else:
1174 return []
1175
1176 def update(self, *args):
1177 """Update the arguments of the expression.
1178
1179 Return a new expression with the same function declaration and updated arguments.
1180 The number of new arguments must match the current number of arguments.
1181
1182 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1183 >>> a = Int('a')
1184 >>> b = Int('b')
1185 >>> c = Int('c')
1186 >>> t = f(a, b)
1187 >>> t.update(c, c)
1188 f(c, c)
1189 """
1190 if z3_debug():
1191 _z3_assert(is_app(self), "Z3 application expected")
1192 _z3_assert(len(args) == self.num_args(), "Number of arguments does not match")
1193 _z3_assert(all([is_expr(arg) for arg in args]), "Z3 expressions expected")
1194 num = len(args)
1195 _args = (Ast * num)()
1196 for i in range(num):
1197 _args[i] = args[i].as_ast()
1198 return _to_expr_ref(Z3_update_term(self.ctx_ref(), self.as_ast(), num, _args), self.ctx)
1199
1200 def from_string(self, s):
1201 pass
1202
1203 def serialize(self):
1204 s = Solver()
1205 f = Function('F', self.sort(), BoolSort(self.ctx))
1206 s.add(f(self))
1207 return s.sexpr()
1208
1210 """inverse function to the serialize method on ExprRef.
1211 It is made available to make it easier for users to serialize expressions back and forth between
1212 strings. Solvers can be serialized using the 'sexpr()' method.
1213 """
1214 s = Solver()
1215 s.from_string(st)
1216 if len(s.assertions()) != 1:
1217 raise Z3Exception("single assertion expected")
1218 fml = s.assertions()[0]
1219 if fml.num_args() != 1:
1220 raise Z3Exception("dummy function 'F' expected")
1221 return fml.arg(0)
1222
1223def _to_expr_ref(a, ctx):
1224 if isinstance(a, Pattern):
1225 return PatternRef(a, ctx)
1226 ctx_ref = ctx.ref()
1227 k = Z3_get_ast_kind(ctx_ref, a)
1228 if k == Z3_QUANTIFIER_AST:
1229 return QuantifierRef(a, ctx)
1230 # Check for finite set sort before checking sort kind
1231 s = Z3_get_sort(ctx_ref, a)
1232 if Z3_is_finite_set_sort(ctx_ref, s):
1233 return FiniteSetRef(a, ctx)
1234 sk = Z3_get_sort_kind(ctx_ref, s)
1235 if sk == Z3_BOOL_SORT:
1236 return BoolRef(a, ctx)
1237 if sk == Z3_INT_SORT:
1238 if k == Z3_NUMERAL_AST:
1239 return IntNumRef(a, ctx)
1240 return ArithRef(a, ctx)
1241 if sk == Z3_REAL_SORT:
1242 if k == Z3_NUMERAL_AST:
1243 return RatNumRef(a, ctx)
1244 if _is_algebraic(ctx, a):
1245 return AlgebraicNumRef(a, ctx)
1246 return ArithRef(a, ctx)
1247 if sk == Z3_BV_SORT:
1248 if k == Z3_NUMERAL_AST:
1249 return BitVecNumRef(a, ctx)
1250 else:
1251 return BitVecRef(a, ctx)
1252 if sk == Z3_ARRAY_SORT:
1253 return ArrayRef(a, ctx)
1254 if sk == Z3_DATATYPE_SORT:
1255 return DatatypeRef(a, ctx)
1256 if sk == Z3_FLOATING_POINT_SORT:
1257 if k == Z3_APP_AST and _is_numeral(ctx, a):
1258 return FPNumRef(a, ctx)
1259 else:
1260 return FPRef(a, ctx)
1261 if sk == Z3_FINITE_DOMAIN_SORT:
1262 if k == Z3_NUMERAL_AST:
1263 return FiniteDomainNumRef(a, ctx)
1264 else:
1265 return FiniteDomainRef(a, ctx)
1266 if sk == Z3_ROUNDING_MODE_SORT:
1267 return FPRMRef(a, ctx)
1268 if sk == Z3_SEQ_SORT:
1269 return SeqRef(a, ctx)
1270 if sk == Z3_CHAR_SORT:
1271 return CharRef(a, ctx)
1272 if sk == Z3_RE_SORT:
1273 return ReRef(a, ctx)
1274 return ExprRef(a, ctx)
1275
1276
1278 if is_expr(a):
1279 s1 = a.sort()
1280 if s is None:
1281 return s1
1282 if s1.eq(s):
1283 return s
1284 elif s.subsort(s1):
1285 return s1
1286 elif s1.subsort(s):
1287 return s
1288 else:
1289 if z3_debug():
1290 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1291 _z3_assert(False, "sort mismatch")
1292 else:
1293 return s
1294
1295def _check_same_sort(a, b, ctx=None):
1296 if not isinstance(a, ExprRef):
1297 return False
1298 if not isinstance(b, ExprRef):
1299 return False
1300 if ctx is None:
1301 ctx = a.ctx
1302
1303 a_sort = Z3_get_sort(ctx.ctx, a.ast)
1304 b_sort = Z3_get_sort(ctx.ctx, b.ast)
1305 return Z3_is_eq_sort(ctx.ctx, a_sort, b_sort)
1306
1307
1308def _coerce_exprs(a, b, ctx=None):
1309 if not is_expr(a) and not is_expr(b):
1310 a = _py2expr(a, ctx)
1311 b = _py2expr(b, ctx)
1312 if isinstance(a, str) and isinstance(b, SeqRef):
1313 a = StringVal(a, b.ctx)
1314 if isinstance(b, str) and isinstance(a, SeqRef):
1315 b = StringVal(b, a.ctx)
1316 if isinstance(a, float) and isinstance(b, ArithRef):
1317 a = RealVal(a, b.ctx)
1318 if isinstance(b, float) and isinstance(a, ArithRef):
1319 b = RealVal(b, a.ctx)
1320
1321 if _check_same_sort(a, b, ctx):
1322 return (a, b)
1323
1324 s = None
1325 s = _coerce_expr_merge(s, a)
1326 s = _coerce_expr_merge(s, b)
1327 a = s.cast(a)
1328 b = s.cast(b)
1329 return (a, b)
1330
1331
1332def _reduce(func, sequence, initial):
1333 result = initial
1334 for element in sequence:
1335 result = func(result, element)
1336 return result
1337
1338
1339def _coerce_expr_list(alist, ctx=None):
1340 has_expr = False
1341 for a in alist:
1342 if is_expr(a):
1343 has_expr = True
1344 break
1345 if not has_expr:
1346 alist = [_py2expr(a, ctx) for a in alist]
1347 s = _reduce(_coerce_expr_merge, alist, None)
1348 return [s.cast(a) for a in alist]
1349
1350
1351def is_expr(a):
1352 """Return `True` if `a` is a Z3 expression.
1353
1354 >>> a = Int('a')
1355 >>> is_expr(a)
1356 True
1357 >>> is_expr(a + 1)
1358 True
1359 >>> is_expr(IntSort())
1360 False
1361 >>> is_expr(1)
1362 False
1363 >>> is_expr(IntVal(1))
1364 True
1365 >>> x = Int('x')
1366 >>> is_expr(ForAll(x, x >= 0))
1367 True
1368 >>> is_expr(FPVal(1.0))
1369 True
1370 """
1371 return isinstance(a, ExprRef)
1372
1373
1374def is_app(a):
1375 """Return `True` if `a` is a Z3 function application.
1376
1377 Note that, constants are function applications with 0 arguments.
1378
1379 >>> a = Int('a')
1380 >>> is_app(a)
1381 True
1382 >>> is_app(a + 1)
1383 True
1384 >>> is_app(IntSort())
1385 False
1386 >>> is_app(1)
1387 False
1388 >>> is_app(IntVal(1))
1389 True
1390 >>> x = Int('x')
1391 >>> is_app(ForAll(x, x >= 0))
1392 False
1393 """
1394 if not isinstance(a, ExprRef):
1395 return False
1396 k = _ast_kind(a.ctx, a)
1397 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1398
1399
1401 """Return `True` if `a` is Z3 constant/variable expression.
1402
1403 >>> a = Int('a')
1404 >>> is_const(a)
1405 True
1406 >>> is_const(a + 1)
1407 False
1408 >>> is_const(1)
1409 False
1410 >>> is_const(IntVal(1))
1411 True
1412 >>> x = Int('x')
1413 >>> is_const(ForAll(x, x >= 0))
1414 False
1415 """
1416 return is_app(a) and a.num_args() == 0
1417
1418
1419def is_var(a):
1420 """Return `True` if `a` is variable.
1421
1422 Z3 uses de-Bruijn indices for representing bound variables in
1423 quantifiers.
1424
1425 >>> x = Int('x')
1426 >>> is_var(x)
1427 False
1428 >>> is_const(x)
1429 True
1430 >>> f = Function('f', IntSort(), IntSort())
1431 >>> # Z3 replaces x with bound variables when ForAll is executed.
1432 >>> q = ForAll(x, f(x) == x)
1433 >>> b = q.body()
1434 >>> b
1435 f(Var(0)) == Var(0)
1436 >>> b.arg(1)
1437 Var(0)
1438 >>> is_var(b.arg(1))
1439 True
1440 """
1441 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1442
1443
1445 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1446
1447 >>> x = Int('x')
1448 >>> y = Int('y')
1449 >>> is_var(x)
1450 False
1451 >>> is_const(x)
1452 True
1453 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1454 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1455 >>> q = ForAll([x, y], f(x, y) == x + y)
1456 >>> q.body()
1457 f(Var(1), Var(0)) == Var(1) + Var(0)
1458 >>> b = q.body()
1459 >>> b.arg(0)
1460 f(Var(1), Var(0))
1461 >>> v1 = b.arg(0).arg(0)
1462 >>> v2 = b.arg(0).arg(1)
1463 >>> v1
1464 Var(1)
1465 >>> v2
1466 Var(0)
1467 >>> get_var_index(v1)
1468 1
1469 >>> get_var_index(v2)
1470 0
1471 """
1472 if z3_debug():
1473 _z3_assert(is_var(a), "Z3 bound variable expected")
1474 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1475
1476
1477def is_app_of(a, k):
1478 """Return `True` if `a` is an application of the given kind `k`.
1479
1480 >>> x = Int('x')
1481 >>> n = x + 1
1482 >>> is_app_of(n, Z3_OP_ADD)
1483 True
1484 >>> is_app_of(n, Z3_OP_MUL)
1485 False
1486 """
1487 return is_app(a) and a.kind() == k
1488
1489
1490def If(a, b, c, ctx=None):
1491 """Create a Z3 if-then-else expression.
1492
1493 >>> x = Int('x')
1494 >>> y = Int('y')
1495 >>> max = If(x > y, x, y)
1496 >>> max
1497 If(x > y, x, y)
1498 >>> simplify(max)
1499 If(x <= y, y, x)
1500 """
1501 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1502 return Cond(a, b, c, ctx)
1503 else:
1504 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1505 s = BoolSort(ctx)
1506 a = s.cast(a)
1507 b, c = _coerce_exprs(b, c, ctx)
1508 if z3_debug():
1509 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1510 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1511
1512
1513def Distinct(*args):
1514 """Create a Z3 distinct expression.
1515
1516 >>> x = Int('x')
1517 >>> y = Int('y')
1518 >>> Distinct(x, y)
1519 x != y
1520 >>> z = Int('z')
1521 >>> Distinct(x, y, z)
1522 Distinct(x, y, z)
1523 >>> simplify(Distinct(x, y, z))
1524 Distinct(x, y, z)
1525 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1526 And(Not(x == y), Not(x == z), Not(y == z))
1527 """
1528 args = _get_args(args)
1529 ctx = _ctx_from_ast_arg_list(args)
1530 if z3_debug():
1531 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1532 args = _coerce_expr_list(args, ctx)
1533 _args, sz = _to_ast_array(args)
1534 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1535
1536
1537def _mk_bin(f, a, b):
1538 args = (Ast * 2)()
1539 if z3_debug():
1540 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1541 args[0] = a.as_ast()
1542 args[1] = b.as_ast()
1543 return f(a.ctx.ref(), 2, args)
1544
1545
1546def Const(name, sort):
1547 """Create a constant of the given sort.
1548
1549 >>> Const('x', IntSort())
1550 x
1551 """
1552 if z3_debug():
1553 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1554 ctx = sort.ctx
1555 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1556
1557
1558def Consts(names, sort):
1559 """Create several constants of the given sort.
1560
1561 `names` is a string containing the names of all constants to be created.
1562 Blank spaces separate the names of different constants.
1563
1564 >>> x, y, z = Consts('x y z', IntSort())
1565 >>> x + y + z
1566 x + y + z
1567 """
1568 if isinstance(names, str):
1569 names = names.split(" ")
1570 return [Const(name, sort) for name in names]
1571
1572
1573def FreshConst(sort, prefix="c"):
1574 """Create a fresh constant of a specified sort"""
1575 if z3_debug():
1576 _z3_assert(is_sort(sort), f"Z3 sort expected, got {type(sort)}")
1577 ctx = _get_ctx(sort.ctx)
1578 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1579
1580
1581def Var(idx : int, s : SortRef) -> ExprRef:
1582 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1583 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1584 declarations.
1585
1586 >>> Var(0, IntSort())
1587 Var(0)
1588 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1589 False
1590 """
1591 if z3_debug():
1592 _z3_assert(is_sort(s), "Z3 sort expected")
1593 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1594
1595
1596def RealVar(idx: int, ctx=None) -> ExprRef:
1597 """
1598 Create a real free variable. Free variables are used to create quantified formulas.
1599 They are also used to create polynomials.
1600
1601 >>> RealVar(0)
1602 Var(0)
1603 """
1604 return Var(idx, RealSort(ctx))
1605
1606def RealVarVector(n: int, ctx= None):
1607 """
1608 Create a list of Real free variables.
1609 The variables have ids: 0, 1, ..., n-1
1610
1611 >>> x0, x1, x2, x3 = RealVarVector(4)
1612 >>> x2
1613 Var(2)
1614 """
1615 return [RealVar(i, ctx) for i in range(n)]
1616
1617
1622
1623
1625 """Boolean sort."""
1626
1627 def cast(self, val):
1628 """Try to cast `val` as a Boolean.
1629
1630 >>> x = BoolSort().cast(True)
1631 >>> x
1632 True
1633 >>> is_expr(x)
1634 True
1635 >>> is_expr(True)
1636 False
1637 >>> x.sort()
1638 Bool
1639 """
1640 if isinstance(val, bool):
1641 return BoolVal(val, self.ctx)
1642 if z3_debug():
1643 if not is_expr(val):
1644 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1645 _z3_assert(is_expr(val), msg % (val, type(val)))
1646 if not self.eq(val.sort()):
1647 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1648 return val
1649
1650 def subsort(self, other):
1651 return isinstance(other, ArithSortRef)
1652
1653 def is_int(self):
1654 return True
1655
1656 def is_bool(self):
1657 return True
1658
1659
1661 """All Boolean expressions are instances of this class."""
1662
1663 def sort(self):
1664 return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
1665
1666 def __add__(self, other):
1667 if isinstance(other, BoolRef):
1668 other = If(other, 1, 0)
1669 return If(self, 1, 0) + other
1670
1671 def __radd__(self, other):
1672 return self + other
1673
1674 def __rmul__(self, other):
1675 return self * other
1676
1677 def __mul__(self, other):
1678 """Create the Z3 expression `self * other`.
1679 """
1680 if isinstance(other, int) and other == 1:
1681 return If(self, 1, 0)
1682 if isinstance(other, int) and other == 0:
1683 return IntVal(0, self.ctx)
1684 if isinstance(other, BoolRef):
1685 other = If(other, 1, 0)
1686 return If(self, other, 0)
1687
1688 def __and__(self, other):
1689 return And(self, other)
1690
1691 def __or__(self, other):
1692 return Or(self, other)
1693
1694 def __xor__(self, other):
1695 return Xor(self, other)
1696
1697 def __invert__(self):
1698 return Not(self)
1699
1700 def py_value(self):
1701 if is_true(self):
1702 return True
1703 if is_false(self):
1704 return False
1705 return None
1706
1707
1708
1709
1710def is_bool(a : Any) -> bool:
1711 """Return `True` if `a` is a Z3 Boolean expression.
1712
1713 >>> p = Bool('p')
1714 >>> is_bool(p)
1715 True
1716 >>> q = Bool('q')
1717 >>> is_bool(And(p, q))
1718 True
1719 >>> x = Real('x')
1720 >>> is_bool(x)
1721 False
1722 >>> is_bool(x == 0)
1723 True
1724 """
1725 return isinstance(a, BoolRef)
1726
1727
1728def is_true(a : Any) -> bool:
1729 """Return `True` if `a` is the Z3 true expression.
1730
1731 >>> p = Bool('p')
1732 >>> is_true(p)
1733 False
1734 >>> is_true(simplify(p == p))
1735 True
1736 >>> x = Real('x')
1737 >>> is_true(x == 0)
1738 False
1739 >>> # True is a Python Boolean expression
1740 >>> is_true(True)
1741 False
1742 """
1743 return is_app_of(a, Z3_OP_TRUE)
1744
1745
1746def is_false(a : Any) -> bool:
1747 """Return `True` if `a` is the Z3 false expression.
1748
1749 >>> p = Bool('p')
1750 >>> is_false(p)
1751 False
1752 >>> is_false(False)
1753 False
1754 >>> is_false(BoolVal(False))
1755 True
1756 """
1757 return is_app_of(a, Z3_OP_FALSE)
1758
1759
1760def is_and(a : Any) -> bool:
1761 """Return `True` if `a` is a Z3 and expression.
1762
1763 >>> p, q = Bools('p q')
1764 >>> is_and(And(p, q))
1765 True
1766 >>> is_and(Or(p, q))
1767 False
1768 """
1769 return is_app_of(a, Z3_OP_AND)
1770
1771
1772def is_or(a : Any) -> bool:
1773 """Return `True` if `a` is a Z3 or expression.
1774
1775 >>> p, q = Bools('p q')
1776 >>> is_or(Or(p, q))
1777 True
1778 >>> is_or(And(p, q))
1779 False
1780 """
1781 return is_app_of(a, Z3_OP_OR)
1782
1783
1784def is_implies(a : Any) -> bool:
1785 """Return `True` if `a` is a Z3 implication expression.
1786
1787 >>> p, q = Bools('p q')
1788 >>> is_implies(Implies(p, q))
1789 True
1790 >>> is_implies(And(p, q))
1791 False
1792 """
1793 return is_app_of(a, Z3_OP_IMPLIES)
1794
1795
1796def is_not(a : Any) -> bool:
1797 """Return `True` if `a` is a Z3 not expression.
1798
1799 >>> p = Bool('p')
1800 >>> is_not(p)
1801 False
1802 >>> is_not(Not(p))
1803 True
1804 """
1805 return is_app_of(a, Z3_OP_NOT)
1806
1807
1808def is_eq(a : Any) -> bool:
1809 """Return `True` if `a` is a Z3 equality expression.
1810
1811 >>> x, y = Ints('x y')
1812 >>> is_eq(x == y)
1813 True
1814 """
1815 return is_app_of(a, Z3_OP_EQ)
1816
1817
1818def is_distinct(a : Any) -> bool:
1819 """Return `True` if `a` is a Z3 distinct expression.
1820
1821 >>> x, y, z = Ints('x y z')
1822 >>> is_distinct(x == y)
1823 False
1824 >>> is_distinct(Distinct(x, y, z))
1825 True
1826 """
1827 return is_app_of(a, Z3_OP_DISTINCT)
1828
1829
1830def BoolSort(ctx=None):
1831 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1832
1833 >>> BoolSort()
1834 Bool
1835 >>> p = Const('p', BoolSort())
1836 >>> is_bool(p)
1837 True
1838 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1839 >>> r(0, 1)
1840 r(0, 1)
1841 >>> is_bool(r(0, 1))
1842 True
1843 """
1844 ctx = _get_ctx(ctx)
1845 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1846
1847
1848def BoolVal(val, ctx=None):
1849 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1850
1851 >>> BoolVal(True)
1852 True
1853 >>> is_true(BoolVal(True))
1854 True
1855 >>> is_true(True)
1856 False
1857 >>> is_false(BoolVal(False))
1858 True
1859 """
1860 ctx = _get_ctx(ctx)
1861 if val:
1862 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1863 else:
1864 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1865
1866
1867def Bool(name, ctx=None):
1868 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1869
1870 >>> p = Bool('p')
1871 >>> q = Bool('q')
1872 >>> And(p, q)
1873 And(p, q)
1874 """
1875 ctx = _get_ctx(ctx)
1876 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1877
1878
1879def Bools(names, ctx=None):
1880 """Return a tuple of Boolean constants.
1881
1882 `names` is a single string containing all names separated by blank spaces.
1883 If `ctx=None`, then the global context is used.
1884
1885 >>> p, q, r = Bools('p q r')
1886 >>> And(p, Or(q, r))
1887 And(p, Or(q, r))
1888 """
1889 ctx = _get_ctx(ctx)
1890 if isinstance(names, str):
1891 names = names.split(" ")
1892 return [Bool(name, ctx) for name in names]
1893
1894
1895def BoolVector(prefix, sz, ctx=None):
1896 """Return a list of Boolean constants of size `sz`.
1897
1898 The constants are named using the given prefix.
1899 If `ctx=None`, then the global context is used.
1900
1901 >>> P = BoolVector('p', 3)
1902 >>> P
1903 [p__0, p__1, p__2]
1904 >>> And(P)
1905 And(p__0, p__1, p__2)
1906 """
1907 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1908
1909
1910def FreshBool(prefix="b", ctx=None):
1911 """Return a fresh Boolean constant in the given context using the given prefix.
1912
1913 If `ctx=None`, then the global context is used.
1914
1915 >>> b1 = FreshBool()
1916 >>> b2 = FreshBool()
1917 >>> eq(b1, b2)
1918 False
1919 """
1920 ctx = _get_ctx(ctx)
1921 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1922
1923
1924def Implies(a, b, ctx=None):
1925 """Create a Z3 implies expression.
1926
1927 >>> p, q = Bools('p q')
1928 >>> Implies(p, q)
1929 Implies(p, q)
1930 """
1931 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1932 s = BoolSort(ctx)
1933 a = s.cast(a)
1934 b = s.cast(b)
1935 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1936
1937
1938def Xor(a, b, ctx=None):
1939 """Create a Z3 Xor expression.
1940
1941 >>> p, q = Bools('p q')
1942 >>> Xor(p, q)
1943 Xor(p, q)
1944 >>> simplify(Xor(p, q))
1945 Not(p == q)
1946 """
1947 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1948 s = BoolSort(ctx)
1949 a = s.cast(a)
1950 b = s.cast(b)
1951 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1952
1953
1954def Not(a, ctx=None):
1955 """Create a Z3 not expression or probe.
1956
1957 >>> p = Bool('p')
1958 >>> Not(Not(p))
1959 Not(Not(p))
1960 >>> simplify(Not(Not(p)))
1961 p
1962 """
1963 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1964 if is_probe(a):
1965 # Not is also used to build probes
1966 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1967 else:
1968 s = BoolSort(ctx)
1969 a = s.cast(a)
1970 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1971
1972
1973def mk_not(a):
1974 if is_not(a):
1975 return a.arg(0)
1976 else:
1977 return Not(a)
1978
1979
1980def _has_probe(args):
1981 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1982 for arg in args:
1983 if is_probe(arg):
1984 return True
1985 return False
1986
1987
1988def And(*args):
1989 """Create a Z3 and-expression or and-probe.
1990
1991 >>> p, q, r = Bools('p q r')
1992 >>> And(p, q, r)
1993 And(p, q, r)
1994 >>> P = BoolVector('p', 5)
1995 >>> And(P)
1996 And(p__0, p__1, p__2, p__3, p__4)
1997 """
1998 last_arg = None
1999 if len(args) > 0:
2000 last_arg = args[len(args) - 1]
2001 if isinstance(last_arg, Context):
2002 ctx = args[len(args) - 1]
2003 args = args[:len(args) - 1]
2004 elif len(args) == 1 and isinstance(args[0], AstVector):
2005 ctx = args[0].ctx
2006 args = [a for a in args[0]]
2007 else:
2008 ctx = None
2009 args = _get_args(args)
2010 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2011 if z3_debug():
2012 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2013 if _has_probe(args):
2014 return _probe_and(args, ctx)
2015 else:
2016 args = _coerce_expr_list(args, ctx)
2017 _args, sz = _to_ast_array(args)
2018 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
2019
2020
2021def Or(*args):
2022 """Create a Z3 or-expression or or-probe.
2023
2024 >>> p, q, r = Bools('p q r')
2025 >>> Or(p, q, r)
2026 Or(p, q, r)
2027 >>> P = BoolVector('p', 5)
2028 >>> Or(P)
2029 Or(p__0, p__1, p__2, p__3, p__4)
2030 """
2031 last_arg = None
2032 if len(args) > 0:
2033 last_arg = args[len(args) - 1]
2034 if isinstance(last_arg, Context):
2035 ctx = args[len(args) - 1]
2036 args = args[:len(args) - 1]
2037 elif len(args) == 1 and isinstance(args[0], AstVector):
2038 ctx = args[0].ctx
2039 args = [a for a in args[0]]
2040 else:
2041 ctx = None
2042 args = _get_args(args)
2043 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2044 if z3_debug():
2045 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2046 if _has_probe(args):
2047 return _probe_or(args, ctx)
2048 else:
2049 args = _coerce_expr_list(args, ctx)
2050 _args, sz = _to_ast_array(args)
2051 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
2052
2053
2058
2059
2061 """Patterns are hints for quantifier instantiation.
2062
2063 """
2064
2065 def as_ast(self):
2066 return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
2067
2068 def get_id(self):
2069 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
2070
2071
2073 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2074
2075 >>> f = Function('f', IntSort(), IntSort())
2076 >>> x = Int('x')
2077 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2078 >>> q
2079 ForAll(x, f(x) == 0)
2080 >>> q.num_patterns()
2081 1
2082 >>> is_pattern(q.pattern(0))
2083 True
2084 >>> q.pattern(0)
2085 f(Var(0))
2086 """
2087 return isinstance(a, PatternRef)
2088
2089
2090def MultiPattern(*args):
2091 """Create a Z3 multi-pattern using the given expressions `*args`
2092
2093 >>> f = Function('f', IntSort(), IntSort())
2094 >>> g = Function('g', IntSort(), IntSort())
2095 >>> x = Int('x')
2096 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2097 >>> q
2098 ForAll(x, f(x) != g(x))
2099 >>> q.num_patterns()
2100 1
2101 >>> is_pattern(q.pattern(0))
2102 True
2103 >>> q.pattern(0)
2104 MultiPattern(f(Var(0)), g(Var(0)))
2105 """
2106 if z3_debug():
2107 _z3_assert(len(args) > 0, "At least one argument expected")
2108 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
2109 ctx = args[0].ctx
2110 args, sz = _to_ast_array(args)
2111 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
2112
2113
2115 if is_pattern(arg):
2116 return arg
2117 else:
2118 return MultiPattern(arg)
2119
2120
2125
2126
2128 """Universally and Existentially quantified formulas."""
2129
2130 def as_ast(self):
2131 return self.ast
2132
2133 def get_id(self):
2134 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
2135
2136 def sort(self):
2137 """Return the Boolean sort or sort of Lambda."""
2138 if self.is_lambda():
2139 return _sort(self.ctx, self.as_ast())
2140 return BoolSort(self.ctx)
2141
2142 def is_forall(self):
2143 """Return `True` if `self` is a universal quantifier.
2144
2145 >>> f = Function('f', IntSort(), IntSort())
2146 >>> x = Int('x')
2147 >>> q = ForAll(x, f(x) == 0)
2148 >>> q.is_forall()
2149 True
2150 >>> q = Exists(x, f(x) != 0)
2151 >>> q.is_forall()
2152 False
2153 """
2155
2156 def is_exists(self):
2157 """Return `True` if `self` is an existential quantifier.
2158
2159 >>> f = Function('f', IntSort(), IntSort())
2160 >>> x = Int('x')
2161 >>> q = ForAll(x, f(x) == 0)
2162 >>> q.is_exists()
2163 False
2164 >>> q = Exists(x, f(x) != 0)
2165 >>> q.is_exists()
2166 True
2167 """
2168 return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
2169
2170 def is_lambda(self):
2171 """Return `True` if `self` is a lambda expression.
2172
2173 >>> f = Function('f', IntSort(), IntSort())
2174 >>> x = Int('x')
2175 >>> q = Lambda(x, f(x))
2176 >>> q.is_lambda()
2177 True
2178 >>> q = Exists(x, f(x) != 0)
2179 >>> q.is_lambda()
2180 False
2181 """
2182 return Z3_is_lambda(self.ctx_ref(), self.ast)
2183
2184 def __getitem__(self, arg):
2185 """Return the Z3 expression `self[arg]`.
2186 """
2187 if z3_debug():
2188 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2189 return _array_select(self, arg)
2190
2191 def weight(self):
2192 """Return the weight annotation of `self`.
2193
2194 >>> f = Function('f', IntSort(), IntSort())
2195 >>> x = Int('x')
2196 >>> q = ForAll(x, f(x) == 0)
2197 >>> q.weight()
2198 1
2199 >>> q = ForAll(x, f(x) == 0, weight=10)
2200 >>> q.weight()
2201 10
2202 """
2203 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
2204
2205 def skolem_id(self):
2206 """Return the skolem id of `self`.
2207 """
2208 return _symbol2py(self.ctx, Z3_get_quantifier_skolem_id(self.ctx_ref(), self.ast))
2209
2210 def qid(self):
2211 """Return the quantifier id of `self`.
2212 """
2213 return _symbol2py(self.ctx, Z3_get_quantifier_id(self.ctx_ref(), self.ast))
2214
2215 def num_patterns(self):
2216 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2217
2218 >>> f = Function('f', IntSort(), IntSort())
2219 >>> g = Function('g', IntSort(), IntSort())
2220 >>> x = Int('x')
2221 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2222 >>> q.num_patterns()
2223 2
2224 """
2225 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
2226
2227 def pattern(self, idx):
2228 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2229
2230 >>> f = Function('f', IntSort(), IntSort())
2231 >>> g = Function('g', IntSort(), IntSort())
2232 >>> x = Int('x')
2233 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2234 >>> q.num_patterns()
2235 2
2236 >>> q.pattern(0)
2237 f(Var(0))
2238 >>> q.pattern(1)
2239 g(Var(0))
2240 """
2241 if z3_debug():
2242 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2243 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2244
2246 """Return the number of no-patterns."""
2247 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
2248
2249 def no_pattern(self, idx):
2250 """Return a no-pattern."""
2251 if z3_debug():
2252 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2253 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
2254
2255 def body(self):
2256 """Return the expression being quantified.
2257
2258 >>> f = Function('f', IntSort(), IntSort())
2259 >>> x = Int('x')
2260 >>> q = ForAll(x, f(x) == 0)
2261 >>> q.body()
2262 f(Var(0)) == 0
2263 """
2264 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
2265
2266 def num_vars(self):
2267 """Return the number of variables bounded by this quantifier.
2268
2269 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2270 >>> x = Int('x')
2271 >>> y = Int('y')
2272 >>> q = ForAll([x, y], f(x, y) >= x)
2273 >>> q.num_vars()
2274 2
2275 """
2276 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
2277
2278 def var_name(self, idx):
2279 """Return a string representing a name used when displaying the quantifier.
2280
2281 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2282 >>> x = Int('x')
2283 >>> y = Int('y')
2284 >>> q = ForAll([x, y], f(x, y) >= x)
2285 >>> q.var_name(0)
2286 'x'
2287 >>> q.var_name(1)
2288 'y'
2289 """
2290 if z3_debug():
2291 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2292 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
2293
2294 def var_sort(self, idx):
2295 """Return the sort of a bound variable.
2296
2297 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2298 >>> x = Int('x')
2299 >>> y = Real('y')
2300 >>> q = ForAll([x, y], f(x, y) >= x)
2301 >>> q.var_sort(0)
2302 Int
2303 >>> q.var_sort(1)
2304 Real
2305 """
2306 if z3_debug():
2307 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2308 return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
2309
2310 def children(self):
2311 """Return a list containing a single element self.body()
2312
2313 >>> f = Function('f', IntSort(), IntSort())
2314 >>> x = Int('x')
2315 >>> q = ForAll(x, f(x) == 0)
2316 >>> q.children()
2317 [f(Var(0)) == 0]
2318 """
2319 return [self.body()]
2320
2321
2323 """Return `True` if `a` is a Z3 quantifier.
2324
2325 >>> f = Function('f', IntSort(), IntSort())
2326 >>> x = Int('x')
2327 >>> q = ForAll(x, f(x) == 0)
2328 >>> is_quantifier(q)
2329 True
2330 >>> is_quantifier(f(x))
2331 False
2332 """
2333 return isinstance(a, QuantifierRef)
2334
2335
2336def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2337 if z3_debug():
2338 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2339 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2340 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2341 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2342 if is_app(vs):
2343 ctx = vs.ctx
2344 vs = [vs]
2345 else:
2346 ctx = vs[0].ctx
2347 if not is_expr(body):
2348 body = BoolVal(body, ctx)
2349 num_vars = len(vs)
2350 if num_vars == 0:
2351 return body
2352 _vs = (Ast * num_vars)()
2353 for i in range(num_vars):
2354 # TODO: Check if is constant
2355 _vs[i] = vs[i].as_ast()
2356 patterns = [_to_pattern(p) for p in patterns]
2357 num_pats = len(patterns)
2358 _pats = (Pattern * num_pats)()
2359 for i in range(num_pats):
2360 _pats[i] = patterns[i].ast
2361 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2362 qid = to_symbol(qid, ctx)
2363 skid = to_symbol(skid, ctx)
2364 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2365 num_vars, _vs,
2366 num_pats, _pats,
2367 num_no_pats, _no_pats,
2368 body.as_ast()), ctx)
2369
2370
2371def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2372 """Create a Z3 forall formula.
2373
2374 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2375
2376 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2377 >>> x = Int('x')
2378 >>> y = Int('y')
2379 >>> ForAll([x, y], f(x, y) >= x)
2380 ForAll([x, y], f(x, y) >= x)
2381 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2382 ForAll([x, y], f(x, y) >= x)
2383 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2384 ForAll([x, y], f(x, y) >= x)
2385 """
2386 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2387
2388
2389def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2390 """Create a Z3 exists formula.
2391
2392 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2393
2394
2395 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2396 >>> x = Int('x')
2397 >>> y = Int('y')
2398 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2399 >>> q
2400 Exists([x, y], f(x, y) >= x)
2401 >>> is_quantifier(q)
2402 True
2403 >>> r = Tactic('nnf')(q).as_expr()
2404 >>> is_quantifier(r)
2405 False
2406 """
2407 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2408
2409
2410def Lambda(vs, body):
2411 """Create a Z3 lambda expression.
2412
2413 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2414 >>> mem0 = Array('mem0', IntSort(), IntSort())
2415 >>> lo, hi, e, i = Ints('lo hi e i')
2416 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2417 >>> mem1
2418 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2419 """
2420 ctx = body.ctx
2421 if is_app(vs):
2422 vs = [vs]
2423 num_vars = len(vs)
2424 _vs = (Ast * num_vars)()
2425 for i in range(num_vars):
2426 # TODO: Check if is constant
2427 _vs[i] = vs[i].as_ast()
2428 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2429
2430
2435
2436
2438 """Real and Integer sorts."""
2439
2440 def is_real(self):
2441 """Return `True` if `self` is of the sort Real.
2442
2443 >>> x = Real('x')
2444 >>> x.is_real()
2445 True
2446 >>> (x + 1).is_real()
2447 True
2448 >>> x = Int('x')
2449 >>> x.is_real()
2450 False
2451 """
2452 return self.kind() == Z3_REAL_SORT
2453
2454 def is_int(self):
2455 """Return `True` if `self` is of the sort Integer.
2456
2457 >>> x = Int('x')
2458 >>> x.is_int()
2459 True
2460 >>> (x + 1).is_int()
2461 True
2462 >>> x = Real('x')
2463 >>> x.is_int()
2464 False
2465 """
2466 return self.kind() == Z3_INT_SORT
2467
2468 def is_bool(self):
2469 return False
2470
2471 def subsort(self, other):
2472 """Return `True` if `self` is a subsort of `other`."""
2473 return self.is_int() and is_arith_sort(other) and other.is_real()
2474
2475 def cast(self, val):
2476 """Try to cast `val` as an Integer or Real.
2477
2478 >>> IntSort().cast(10)
2479 10
2480 >>> is_int(IntSort().cast(10))
2481 True
2482 >>> is_int(10)
2483 False
2484 >>> RealSort().cast(10)
2485 10
2486 >>> is_real(RealSort().cast(10))
2487 True
2488 """
2489 if is_expr(val):
2490 if z3_debug():
2491 _z3_assert(self.ctx == val.ctx, "Context mismatch")
2492 val_s = val.sort()
2493 if self.eq(val_s):
2494 return val
2495 if val_s.is_int() and self.is_real():
2496 return ToReal(val)
2497 if val_s.is_bool() and self.is_int():
2498 return If(val, 1, 0)
2499 if val_s.is_bool() and self.is_real():
2500 return ToReal(If(val, 1, 0))
2501 if z3_debug():
2502 _z3_assert(False, "Z3 Integer/Real expression expected")
2503 else:
2504 if self.is_int():
2505 return IntVal(val, self.ctx)
2506 if self.is_real():
2507 return RealVal(val, self.ctx)
2508 if z3_debug():
2509 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2510 _z3_assert(False, msg % self)
2511
2512
2513def is_arith_sort(s : Any) -> bool:
2514 """Return `True` if s is an arithmetical sort (type).
2515
2516 >>> is_arith_sort(IntSort())
2517 True
2518 >>> is_arith_sort(RealSort())
2519 True
2520 >>> is_arith_sort(BoolSort())
2521 False
2522 >>> n = Int('x') + 1
2523 >>> is_arith_sort(n.sort())
2524 True
2525 """
2526 return isinstance(s, ArithSortRef)
2527
2528
2530 """Integer and Real expressions."""
2531
2532 def sort(self):
2533 """Return the sort (type) of the arithmetical expression `self`.
2534
2535 >>> Int('x').sort()
2536 Int
2537 >>> (Real('x') + 1).sort()
2538 Real
2539 """
2540 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
2541
2542 def is_int(self):
2543 """Return `True` if `self` is an integer expression.
2544
2545 >>> x = Int('x')
2546 >>> x.is_int()
2547 True
2548 >>> (x + 1).is_int()
2549 True
2550 >>> y = Real('y')
2551 >>> (x + y).is_int()
2552 False
2553 """
2554 return self.sort().is_int()
2555
2556 def is_real(self):
2557 """Return `True` if `self` is an real expression.
2558
2559 >>> x = Real('x')
2560 >>> x.is_real()
2561 True
2562 >>> (x + 1).is_real()
2563 True
2564 """
2565 return self.sort().is_real()
2566
2567 def __add__(self, other):
2568 """Create the Z3 expression `self + other`.
2569
2570 >>> x = Int('x')
2571 >>> y = Int('y')
2572 >>> x + y
2573 x + y
2574 >>> (x + y).sort()
2575 Int
2576 """
2577 a, b = _coerce_exprs(self, other)
2578 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2579
2580 def __radd__(self, other):
2581 """Create the Z3 expression `other + self`.
2582
2583 >>> x = Int('x')
2584 >>> 10 + x
2585 10 + x
2586 """
2587 a, b = _coerce_exprs(self, other)
2588 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2589
2590 def __mul__(self, other):
2591 """Create the Z3 expression `self * other`.
2592
2593 >>> x = Real('x')
2594 >>> y = Real('y')
2595 >>> x * y
2596 x*y
2597 >>> (x * y).sort()
2598 Real
2599 """
2600 if isinstance(other, BoolRef):
2601 return If(other, self, 0)
2602 a, b = _coerce_exprs(self, other)
2603 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2604
2605 def __rmul__(self, other):
2606 """Create the Z3 expression `other * self`.
2607
2608 >>> x = Real('x')
2609 >>> 10 * x
2610 10*x
2611 """
2612 a, b = _coerce_exprs(self, other)
2613 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2614
2615 def __sub__(self, other):
2616 """Create the Z3 expression `self - other`.
2617
2618 >>> x = Int('x')
2619 >>> y = Int('y')
2620 >>> x - y
2621 x - y
2622 >>> (x - y).sort()
2623 Int
2624 """
2625 a, b = _coerce_exprs(self, other)
2626 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2627
2628 def __rsub__(self, other):
2629 """Create the Z3 expression `other - self`.
2630
2631 >>> x = Int('x')
2632 >>> 10 - x
2633 10 - x
2634 """
2635 a, b = _coerce_exprs(self, other)
2636 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2637
2638 def __pow__(self, other):
2639 """Create the Z3 expression `self**other` (** is the power operator).
2640
2641 >>> x = Real('x')
2642 >>> x**3
2643 x**3
2644 >>> (x**3).sort()
2645 Real
2646 >>> simplify(IntVal(2)**8)
2647 256
2648 """
2649 a, b = _coerce_exprs(self, other)
2650 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2651
2652 def __rpow__(self, other):
2653 """Create the Z3 expression `other**self` (** is the power operator).
2654
2655 >>> x = Real('x')
2656 >>> 2**x
2657 2**x
2658 >>> (2**x).sort()
2659 Real
2660 >>> simplify(2**IntVal(8))
2661 256
2662 """
2663 a, b = _coerce_exprs(self, other)
2664 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2665
2666 def __div__(self, other):
2667 """Create the Z3 expression `other/self`.
2668
2669 >>> x = Int('x')
2670 >>> y = Int('y')
2671 >>> x/y
2672 x/y
2673 >>> (x/y).sort()
2674 Int
2675 >>> (x/y).sexpr()
2676 '(div x y)'
2677 >>> x = Real('x')
2678 >>> y = Real('y')
2679 >>> x/y
2680 x/y
2681 >>> (x/y).sort()
2682 Real
2683 >>> (x/y).sexpr()
2684 '(/ x y)'
2685 """
2686 a, b = _coerce_exprs(self, other)
2687 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2688
2689 def __truediv__(self, other):
2690 """Create the Z3 expression `other/self`."""
2691 return self.__div__(other)
2692
2693 def __rdiv__(self, other):
2694 """Create the Z3 expression `other/self`.
2695
2696 >>> x = Int('x')
2697 >>> 10/x
2698 10/x
2699 >>> (10/x).sexpr()
2700 '(div 10 x)'
2701 >>> x = Real('x')
2702 >>> 10/x
2703 10/x
2704 >>> (10/x).sexpr()
2705 '(/ 10.0 x)'
2706 """
2707 a, b = _coerce_exprs(self, other)
2708 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2709
2710 def __rtruediv__(self, other):
2711 """Create the Z3 expression `other/self`."""
2712 return self.__rdiv__(other)
2713
2714 def __mod__(self, other):
2715 """Create the Z3 expression `other%self`.
2716
2717 >>> x = Int('x')
2718 >>> y = Int('y')
2719 >>> x % y
2720 x%y
2721 >>> simplify(IntVal(10) % IntVal(3))
2722 1
2723 """
2724 a, b = _coerce_exprs(self, other)
2725 if z3_debug():
2726 _z3_assert(a.is_int(), "Z3 integer expression expected")
2727 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2728
2729 def __rmod__(self, other):
2730 """Create the Z3 expression `other%self`.
2731
2732 >>> x = Int('x')
2733 >>> 10 % x
2734 10%x
2735 """
2736 a, b = _coerce_exprs(self, other)
2737 if z3_debug():
2738 _z3_assert(a.is_int(), "Z3 integer expression expected")
2739 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2740
2741 def __neg__(self):
2742 """Return an expression representing `-self`.
2743
2744 >>> x = Int('x')
2745 >>> -x
2746 -x
2747 >>> simplify(-(-x))
2748 x
2749 """
2750 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
2751
2752 def __pos__(self):
2753 """Return `self`.
2754
2755 >>> x = Int('x')
2756 >>> +x
2757 x
2758 """
2759 return self
2760
2761 def __le__(self, other):
2762 """Create the Z3 expression `other <= self`.
2763
2764 >>> x, y = Ints('x y')
2765 >>> x <= y
2766 x <= y
2767 >>> y = Real('y')
2768 >>> x <= y
2769 ToReal(x) <= y
2770 """
2771 a, b = _coerce_exprs(self, other)
2772 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2773
2774 def __lt__(self, other):
2775 """Create the Z3 expression `other < self`.
2776
2777 >>> x, y = Ints('x y')
2778 >>> x < y
2779 x < y
2780 >>> y = Real('y')
2781 >>> x < y
2782 ToReal(x) < y
2783 """
2784 a, b = _coerce_exprs(self, other)
2785 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2786
2787 def __gt__(self, other):
2788 """Create the Z3 expression `other > self`.
2789
2790 >>> x, y = Ints('x y')
2791 >>> x > y
2792 x > y
2793 >>> y = Real('y')
2794 >>> x > y
2795 ToReal(x) > y
2796 """
2797 a, b = _coerce_exprs(self, other)
2798 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2799
2800 def __ge__(self, other):
2801 """Create the Z3 expression `other >= self`.
2802
2803 >>> x, y = Ints('x y')
2804 >>> x >= y
2805 x >= y
2806 >>> y = Real('y')
2807 >>> x >= y
2808 ToReal(x) >= y
2809 """
2810 a, b = _coerce_exprs(self, other)
2811 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2812
2813 def __abs__(self):
2814 """Return an expression representing `abs(self)`.
2815
2816 >>> x = Int('x')
2817 >>> abs(x)
2818 If(x > 0, x, -x)
2819 >>> eq(abs(x), Abs(x))
2820 True
2821 """
2822 return Abs(self)
2823
2824
2826 """Return `True` if `a` is an arithmetical expression.
2827
2828 >>> x = Int('x')
2829 >>> is_arith(x)
2830 True
2831 >>> is_arith(x + 1)
2832 True
2833 >>> is_arith(1)
2834 False
2835 >>> is_arith(IntVal(1))
2836 True
2837 >>> y = Real('y')
2838 >>> is_arith(y)
2839 True
2840 >>> is_arith(y + 1)
2841 True
2842 """
2843 return isinstance(a, ArithRef)
2844
2845
2846def is_int(a) -> bool:
2847 """Return `True` if `a` is an integer expression.
2848
2849 >>> x = Int('x')
2850 >>> is_int(x + 1)
2851 True
2852 >>> is_int(1)
2853 False
2854 >>> is_int(IntVal(1))
2855 True
2856 >>> y = Real('y')
2857 >>> is_int(y)
2858 False
2859 >>> is_int(y + 1)
2860 False
2861 """
2862 return is_arith(a) and a.is_int()
2863
2864
2865def is_real(a):
2866 """Return `True` if `a` is a real expression.
2867
2868 >>> x = Int('x')
2869 >>> is_real(x + 1)
2870 False
2871 >>> y = Real('y')
2872 >>> is_real(y)
2873 True
2874 >>> is_real(y + 1)
2875 True
2876 >>> is_real(1)
2877 False
2878 >>> is_real(RealVal(1))
2879 True
2880 """
2881 return is_arith(a) and a.is_real()
2882
2883
2884def _is_numeral(ctx, a):
2885 return Z3_is_numeral_ast(ctx.ref(), a)
2886
2887
2888def _is_algebraic(ctx, a):
2889 return Z3_is_algebraic_number(ctx.ref(), a)
2890
2891
2893 """Return `True` if `a` is an integer value of sort Int.
2894
2895 >>> is_int_value(IntVal(1))
2896 True
2897 >>> is_int_value(1)
2898 False
2899 >>> is_int_value(Int('x'))
2900 False
2901 >>> n = Int('x') + 1
2902 >>> n
2903 x + 1
2904 >>> n.arg(1)
2905 1
2906 >>> is_int_value(n.arg(1))
2907 True
2908 >>> is_int_value(RealVal("1/3"))
2909 False
2910 >>> is_int_value(RealVal(1))
2911 False
2912 """
2913 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2914
2915
2917 """Return `True` if `a` is rational value of sort Real.
2918
2919 >>> is_rational_value(RealVal(1))
2920 True
2921 >>> is_rational_value(RealVal("3/5"))
2922 True
2923 >>> is_rational_value(IntVal(1))
2924 False
2925 >>> is_rational_value(1)
2926 False
2927 >>> n = Real('x') + 1
2928 >>> n.arg(1)
2929 1
2930 >>> is_rational_value(n.arg(1))
2931 True
2932 >>> is_rational_value(Real('x'))
2933 False
2934 """
2935 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2936
2937
2939 """Return `True` if `a` is an algebraic value of sort Real.
2940
2941 >>> is_algebraic_value(RealVal("3/5"))
2942 False
2943 >>> n = simplify(Sqrt(2))
2944 >>> n
2945 1.4142135623?
2946 >>> is_algebraic_value(n)
2947 True
2948 """
2949 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2950
2951
2952def is_add(a : Any) -> bool:
2953 """Return `True` if `a` is an expression of the form b + c.
2954
2955 >>> x, y = Ints('x y')
2956 >>> is_add(x + y)
2957 True
2958 >>> is_add(x - y)
2959 False
2960 """
2961 return is_app_of(a, Z3_OP_ADD)
2962
2963
2964def is_mul(a : Any) -> bool:
2965 """Return `True` if `a` is an expression of the form b * c.
2966
2967 >>> x, y = Ints('x y')
2968 >>> is_mul(x * y)
2969 True
2970 >>> is_mul(x - y)
2971 False
2972 """
2973 return is_app_of(a, Z3_OP_MUL)
2974
2975
2976def is_sub(a : Any) -> bool:
2977 """Return `True` if `a` is an expression of the form b - c.
2978
2979 >>> x, y = Ints('x y')
2980 >>> is_sub(x - y)
2981 True
2982 >>> is_sub(x + y)
2983 False
2984 """
2985 return is_app_of(a, Z3_OP_SUB)
2986
2987
2988def is_div(a : Any) -> bool:
2989 """Return `True` if `a` is an expression of the form b / c.
2990
2991 >>> x, y = Reals('x y')
2992 >>> is_div(x / y)
2993 True
2994 >>> is_div(x + y)
2995 False
2996 >>> x, y = Ints('x y')
2997 >>> is_div(x / y)
2998 False
2999 >>> is_idiv(x / y)
3000 True
3001 """
3002 return is_app_of(a, Z3_OP_DIV)
3003
3004
3005def is_idiv(a : Any) -> bool:
3006 """Return `True` if `a` is an expression of the form b div c.
3007
3008 >>> x, y = Ints('x y')
3009 >>> is_idiv(x / y)
3010 True
3011 >>> is_idiv(x + y)
3012 False
3013 """
3014 return is_app_of(a, Z3_OP_IDIV)
3015
3016
3017def is_mod(a : Any) -> bool:
3018 """Return `True` if `a` is an expression of the form b % c.
3019
3020 >>> x, y = Ints('x y')
3021 >>> is_mod(x % y)
3022 True
3023 >>> is_mod(x + y)
3024 False
3025 """
3026 return is_app_of(a, Z3_OP_MOD)
3027
3028
3029def is_le(a : Any) -> bool:
3030 """Return `True` if `a` is an expression of the form b <= c.
3031
3032 >>> x, y = Ints('x y')
3033 >>> is_le(x <= y)
3034 True
3035 >>> is_le(x < y)
3036 False
3037 """
3038 return is_app_of(a, Z3_OP_LE)
3039
3040
3041def is_lt(a : Any) -> bool:
3042 """Return `True` if `a` is an expression of the form b < c.
3043
3044 >>> x, y = Ints('x y')
3045 >>> is_lt(x < y)
3046 True
3047 >>> is_lt(x == y)
3048 False
3049 """
3050 return is_app_of(a, Z3_OP_LT)
3051
3052
3053def is_ge(a : Any) -> bool:
3054 """Return `True` if `a` is an expression of the form b >= c.
3055
3056 >>> x, y = Ints('x y')
3057 >>> is_ge(x >= y)
3058 True
3059 >>> is_ge(x == y)
3060 False
3061 """
3062 return is_app_of(a, Z3_OP_GE)
3063
3064
3065def is_gt(a : Any) -> bool:
3066 """Return `True` if `a` is an expression of the form b > c.
3067
3068 >>> x, y = Ints('x y')
3069 >>> is_gt(x > y)
3070 True
3071 >>> is_gt(x == y)
3072 False
3073 """
3074 return is_app_of(a, Z3_OP_GT)
3075
3076
3077def is_is_int(a : Any) -> bool:
3078 """Return `True` if `a` is an expression of the form IsInt(b).
3079
3080 >>> x = Real('x')
3081 >>> is_is_int(IsInt(x))
3082 True
3083 >>> is_is_int(x)
3084 False
3085 """
3086 return is_app_of(a, Z3_OP_IS_INT)
3087
3088
3089def is_to_real(a : Any) -> bool:
3090 """Return `True` if `a` is an expression of the form ToReal(b).
3091
3092 >>> x = Int('x')
3093 >>> n = ToReal(x)
3094 >>> n
3095 ToReal(x)
3096 >>> is_to_real(n)
3097 True
3098 >>> is_to_real(x)
3099 False
3100 """
3101 return is_app_of(a, Z3_OP_TO_REAL)
3102
3103
3104def is_to_int(a : Any) -> bool:
3105 """Return `True` if `a` is an expression of the form ToInt(b).
3106
3107 >>> x = Real('x')
3108 >>> n = ToInt(x)
3109 >>> n
3110 ToInt(x)
3111 >>> is_to_int(n)
3112 True
3113 >>> is_to_int(x)
3114 False
3115 """
3116 return is_app_of(a, Z3_OP_TO_INT)
3117
3118
3120 """Integer values."""
3121
3122 def as_long(self):
3123 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3124
3125 >>> v = IntVal(1)
3126 >>> v + 1
3127 1 + 1
3128 >>> v.as_long() + 1
3129 2
3130 """
3131 if z3_debug():
3132 _z3_assert(self.is_int(), "Integer value expected")
3133 return int(self.as_string())
3134
3135 def as_string(self):
3136 """Return a Z3 integer numeral as a Python string.
3137 >>> v = IntVal(100)
3138 >>> v.as_string()
3139 '100'
3140 """
3141 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3142
3144 """Return a Z3 integer numeral as a Python binary string.
3145 >>> v = IntVal(10)
3146 >>> v.as_binary_string()
3147 '1010'
3148 """
3149 return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast())
3150
3151 def py_value(self):
3152 return self.as_long()
3153
3154
3156 """Rational values."""
3157
3158 def numerator(self):
3159 """ Return the numerator of a Z3 rational numeral.
3160
3161 >>> is_rational_value(RealVal("3/5"))
3162 True
3163 >>> n = RealVal("3/5")
3164 >>> n.numerator()
3165 3
3166 >>> is_rational_value(Q(3,5))
3167 True
3168 >>> Q(3,5).numerator()
3169 3
3170 """
3171 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
3172
3173 def denominator(self):
3174 """ Return the denominator of a Z3 rational numeral.
3175
3176 >>> is_rational_value(Q(3,5))
3177 True
3178 >>> n = Q(3,5)
3179 >>> n.denominator()
3180 5
3181 """
3182 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
3183
3185 """ Return the numerator as a Python long.
3186
3187 >>> v = RealVal(10000000000)
3188 >>> v
3189 10000000000
3190 >>> v + 1
3191 10000000000 + 1
3192 >>> v.numerator_as_long() + 1 == 10000000001
3193 True
3194 """
3195 return self.numerator().as_long()
3196
3198 """ Return the denominator as a Python long.
3199
3200 >>> v = RealVal("1/3")
3201 >>> v
3202 1/3
3203 >>> v.denominator_as_long()
3204 3
3205 """
3206 return self.denominator().as_long()
3207
3208 def is_int(self):
3209 return False
3210
3211 def is_real(self):
3212 return True
3213
3214 def is_int_value(self):
3215 return self.denominator().is_int() and self.denominator_as_long() == 1
3216
3217 def as_long(self):
3218 _z3_assert(self.is_int_value(), "Expected integer fraction")
3219 return self.numerator_as_long()
3220
3221 def as_decimal(self, prec):
3222 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3223
3224 >>> v = RealVal("1/5")
3225 >>> v.as_decimal(3)
3226 '0.2'
3227 >>> v = RealVal("1/3")
3228 >>> v.as_decimal(3)
3229 '0.333?'
3230 """
3231 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
3232
3233 def as_string(self):
3234 """Return a Z3 rational numeral as a Python string.
3235
3236 >>> v = Q(3,6)
3237 >>> v.as_string()
3238 '1/2'
3239 """
3240 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
3241
3242 def as_fraction(self):
3243 """Return a Z3 rational as a Python Fraction object.
3244
3245 >>> v = RealVal("1/5")
3246 >>> v.as_fraction()
3247 Fraction(1, 5)
3248 """
3249 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3250
3251 def py_value(self):
3252 return Z3_get_numeral_double(self.ctx_ref(), self.as_ast())
3253
3254
3256 """Algebraic irrational values."""
3257
3258 def approx(self, precision=10):
3259 """Return a Z3 rational number that approximates the algebraic number `self`.
3260 The result `r` is such that |r - self| <= 1/10^precision
3261
3262 >>> x = simplify(Sqrt(2))
3263 >>> x.approx(20)
3264 6838717160008073720548335/4835703278458516698824704
3265 >>> x.approx(5)
3266 2965821/2097152
3267 """
3268 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
3269
3270 def as_decimal(self, prec):
3271 """Return a string representation of the algebraic number `self` in decimal notation
3272 using `prec` decimal places.
3273
3274 >>> x = simplify(Sqrt(2))
3275 >>> x.as_decimal(10)
3276 '1.4142135623?'
3277 >>> x.as_decimal(20)
3278 '1.41421356237309504880?'
3279 """
3280 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
3281
3282 def poly(self):
3283 return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_ast()), self.ctx)
3284
3285 def index(self):
3286 return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast())
3287
3288
3289def _py2expr(a, ctx=None):
3290 if isinstance(a, bool):
3291 return BoolVal(a, ctx)
3292 if _is_int(a):
3293 return IntVal(a, ctx)
3294 if isinstance(a, float):
3295 return RealVal(a, ctx)
3296 if isinstance(a, str):
3297 return StringVal(a, ctx)
3298 if is_expr(a):
3299 return a
3300 if z3_debug():
3301 _z3_assert(False, "Python bool, int, long or float expected")
3302
3303
3304def IntSort(ctx=None):
3305 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3306
3307 >>> IntSort()
3308 Int
3309 >>> x = Const('x', IntSort())
3310 >>> is_int(x)
3311 True
3312 >>> x.sort() == IntSort()
3313 True
3314 >>> x.sort() == BoolSort()
3315 False
3316 """
3317 ctx = _get_ctx(ctx)
3318 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3319
3320
3321def RealSort(ctx=None):
3322 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3323
3324 >>> RealSort()
3325 Real
3326 >>> x = Const('x', RealSort())
3327 >>> is_real(x)
3328 True
3329 >>> is_int(x)
3330 False
3331 >>> x.sort() == RealSort()
3332 True
3333 """
3334 ctx = _get_ctx(ctx)
3335 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3336
3337
3339 if isinstance(val, float):
3340 return str(int(val))
3341 elif isinstance(val, bool):
3342 if val:
3343 return "1"
3344 else:
3345 return "0"
3346 else:
3347 return str(val)
3348
3349
3350def IntVal(val, ctx=None):
3351 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3352
3353 >>> IntVal(1)
3354 1
3355 >>> IntVal("100")
3356 100
3357 """
3358 ctx = _get_ctx(ctx)
3359 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3360
3361
3362def RealVal(val, ctx=None):
3363 """Return a Z3 real value.
3364
3365 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3366 If `ctx=None`, then the global context is used.
3367
3368 >>> RealVal(1)
3369 1
3370 >>> RealVal(1).sort()
3371 Real
3372 >>> RealVal("3/5")
3373 3/5
3374 >>> RealVal("1.5")
3375 3/2
3376 """
3377 ctx = _get_ctx(ctx)
3378 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3379
3380
3381def RatVal(a, b, ctx=None):
3382 """Return a Z3 rational a/b.
3383
3384 If `ctx=None`, then the global context is used.
3385
3386 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3387 Z3 can reason about such expressions symbolically.
3388
3389 >>> RatVal(3,5)
3390 3/5
3391 >>> RatVal(3,5).sort()
3392 Real
3393 """
3394 if z3_debug():
3395 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3396 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3397 # Division by 0 is intentionally allowed - Z3 handles it symbolically
3398 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3399
3400
3401def Q(a, b, ctx=None):
3402 """Return a Z3 rational a/b.
3403
3404 If `ctx=None`, then the global context is used.
3405
3406 >>> Q(3,5)
3407 3/5
3408 >>> Q(3,5).sort()
3409 Real
3410 """
3411 return simplify(RatVal(a, b, ctx=ctx))
3412
3413
3414def Int(name, ctx=None):
3415 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3416
3417 >>> x = Int('x')
3418 >>> is_int(x)
3419 True
3420 >>> is_int(x + 1)
3421 True
3422 """
3423 ctx = _get_ctx(ctx)
3424 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3425
3426
3427def Ints(names, ctx=None):
3428 """Return a tuple of Integer constants.
3429
3430 >>> x, y, z = Ints('x y z')
3431 >>> Sum(x, y, z)
3432 x + y + z
3433 """
3434 ctx = _get_ctx(ctx)
3435 if isinstance(names, str):
3436 names = names.split(" ")
3437 return [Int(name, ctx) for name in names]
3438
3439
3440def IntVector(prefix, sz, ctx=None):
3441 """Return a list of integer constants of size `sz`.
3442
3443 >>> X = IntVector('x', 3)
3444 >>> X
3445 [x__0, x__1, x__2]
3446 >>> Sum(X)
3447 x__0 + x__1 + x__2
3448 """
3449 ctx = _get_ctx(ctx)
3450 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3451
3452
3453def FreshInt(prefix="x", ctx=None):
3454 """Return a fresh integer constant in the given context using the given prefix.
3455
3456 >>> x = FreshInt()
3457 >>> y = FreshInt()
3458 >>> eq(x, y)
3459 False
3460 >>> x.sort()
3461 Int
3462 """
3463 ctx = _get_ctx(ctx)
3464 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3465
3466
3467def Real(name, ctx=None):
3468 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3469
3470 >>> x = Real('x')
3471 >>> is_real(x)
3472 True
3473 >>> is_real(x + 1)
3474 True
3475 """
3476 ctx = _get_ctx(ctx)
3477 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3478
3479
3480def Reals(names, ctx=None):
3481 """Return a tuple of real constants.
3482
3483 >>> x, y, z = Reals('x y z')
3484 >>> Sum(x, y, z)
3485 x + y + z
3486 >>> Sum(x, y, z).sort()
3487 Real
3488 """
3489 ctx = _get_ctx(ctx)
3490 if isinstance(names, str):
3491 names = names.split(" ")
3492 return [Real(name, ctx) for name in names]
3493
3494
3495def RealVector(prefix, sz, ctx=None):
3496 """Return a list of real constants of size `sz`.
3497
3498 >>> X = RealVector('x', 3)
3499 >>> X
3500 [x__0, x__1, x__2]
3501 >>> Sum(X)
3502 x__0 + x__1 + x__2
3503 >>> Sum(X).sort()
3504 Real
3505 """
3506 ctx = _get_ctx(ctx)
3507 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3508
3509
3510def FreshReal(prefix="b", ctx=None):
3511 """Return a fresh real constant in the given context using the given prefix.
3512
3513 >>> x = FreshReal()
3514 >>> y = FreshReal()
3515 >>> eq(x, y)
3516 False
3517 >>> x.sort()
3518 Real
3519 """
3520 ctx = _get_ctx(ctx)
3521 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3522
3523
3524def ToReal(a):
3525 """ Return the Z3 expression ToReal(a).
3526
3527 >>> x = Int('x')
3528 >>> x.sort()
3529 Int
3530 >>> n = ToReal(x)
3531 >>> n
3532 ToReal(x)
3533 >>> n.sort()
3534 Real
3535 """
3536 ctx = a.ctx
3537 if isinstance(a, BoolRef):
3538 return If(a, RealVal(1, ctx), RealVal(0, ctx))
3539 if z3_debug():
3540 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3541 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3542
3543
3544def ToInt(a):
3545 """ Return the Z3 expression ToInt(a).
3546
3547 >>> x = Real('x')
3548 >>> x.sort()
3549 Real
3550 >>> n = ToInt(x)
3551 >>> n
3552 ToInt(x)
3553 >>> n.sort()
3554 Int
3555 """
3556 if z3_debug():
3557 _z3_assert(a.is_real(), "Z3 real expression expected.")
3558 ctx = a.ctx
3559 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3560
3561
3562def IsInt(a):
3563 """ Return the Z3 predicate IsInt(a).
3564
3565 >>> x = Real('x')
3566 >>> IsInt(x + "1/2")
3567 IsInt(x + 1/2)
3568 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3569 [x = 1/2]
3570 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3571 no solution
3572 """
3573 if z3_debug():
3574 _z3_assert(a.is_real(), "Z3 real expression expected.")
3575 ctx = a.ctx
3576 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3577
3578
3579def Sqrt(a, ctx=None):
3580 """ Return a Z3 expression which represents the square root of a.
3581
3582 >>> x = Real('x')
3583 >>> Sqrt(x)
3584 x**(1/2)
3585 """
3586 if not is_expr(a):
3587 ctx = _get_ctx(ctx)
3588 a = RealVal(a, ctx)
3589 return a ** "1/2"
3590
3591
3592def Cbrt(a, ctx=None):
3593 """ Return a Z3 expression which represents the cubic root of a.
3594
3595 >>> x = Real('x')
3596 >>> Cbrt(x)
3597 x**(1/3)
3598 """
3599 if not is_expr(a):
3600 ctx = _get_ctx(ctx)
3601 a = RealVal(a, ctx)
3602 return a ** "1/3"
3603
3604
3609
3610
3612 """Bit-vector sort."""
3613
3614 def size(self):
3615 """Return the size (number of bits) of the bit-vector sort `self`.
3616
3617 >>> b = BitVecSort(32)
3618 >>> b.size()
3619 32
3620 """
3621 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3622
3623 def subsort(self, other):
3624 return is_bv_sort(other) and self.size() < other.size()
3625
3626 def cast(self, val):
3627 """Try to cast `val` as a Bit-Vector.
3628
3629 >>> b = BitVecSort(32)
3630 >>> b.cast(10)
3631 10
3632 >>> b.cast(10).sexpr()
3633 '#x0000000a'
3634 """
3635 if is_expr(val):
3636 if z3_debug():
3637 _z3_assert(self.ctx == val.ctx, "Context mismatch")
3638 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3639 return val
3640 else:
3641 return BitVecVal(val, self)
3642
3643
3645 """Return True if `s` is a Z3 bit-vector sort.
3646
3647 >>> is_bv_sort(BitVecSort(32))
3648 True
3649 >>> is_bv_sort(IntSort())
3650 False
3651 """
3652 return isinstance(s, BitVecSortRef)
3653
3654
3656 """Bit-vector expressions."""
3657
3658 def sort(self):
3659 """Return the sort of the bit-vector expression `self`.
3660
3661 >>> x = BitVec('x', 32)
3662 >>> x.sort()
3663 BitVec(32)
3664 >>> x.sort() == BitVecSort(32)
3665 True
3666 """
3667 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
3668
3669 def size(self):
3670 """Return the number of bits of the bit-vector expression `self`.
3671
3672 >>> x = BitVec('x', 32)
3673 >>> (x + 1).size()
3674 32
3675 >>> Concat(x, x).size()
3676 64
3677 """
3678 return self.sort().size()
3679
3680 def __add__(self, other):
3681 """Create the Z3 expression `self + other`.
3682
3683 >>> x = BitVec('x', 32)
3684 >>> y = BitVec('y', 32)
3685 >>> x + y
3686 x + y
3687 >>> (x + y).sort()
3688 BitVec(32)
3689 """
3690 a, b = _coerce_exprs(self, other)
3691 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3692
3693 def __radd__(self, other):
3694 """Create the Z3 expression `other + self`.
3695
3696 >>> x = BitVec('x', 32)
3697 >>> 10 + x
3698 10 + x
3699 """
3700 a, b = _coerce_exprs(self, other)
3701 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3702
3703 def __mul__(self, other):
3704 """Create the Z3 expression `self * other`.
3705
3706 >>> x = BitVec('x', 32)
3707 >>> y = BitVec('y', 32)
3708 >>> x * y
3709 x*y
3710 >>> (x * y).sort()
3711 BitVec(32)
3712 """
3713 a, b = _coerce_exprs(self, other)
3714 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3715
3716 def __rmul__(self, other):
3717 """Create the Z3 expression `other * self`.
3718
3719 >>> x = BitVec('x', 32)
3720 >>> 10 * x
3721 10*x
3722 """
3723 a, b = _coerce_exprs(self, other)
3724 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3725
3726 def __sub__(self, other):
3727 """Create the Z3 expression `self - other`.
3728
3729 >>> x = BitVec('x', 32)
3730 >>> y = BitVec('y', 32)
3731 >>> x - y
3732 x - y
3733 >>> (x - y).sort()
3734 BitVec(32)
3735 """
3736 a, b = _coerce_exprs(self, other)
3737 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3738
3739 def __rsub__(self, other):
3740 """Create the Z3 expression `other - self`.
3741
3742 >>> x = BitVec('x', 32)
3743 >>> 10 - x
3744 10 - x
3745 """
3746 a, b = _coerce_exprs(self, other)
3747 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3748
3749 def __or__(self, other):
3750 """Create the Z3 expression bitwise-or `self | other`.
3751
3752 >>> x = BitVec('x', 32)
3753 >>> y = BitVec('y', 32)
3754 >>> x | y
3755 x | y
3756 >>> (x | y).sort()
3757 BitVec(32)
3758 """
3759 a, b = _coerce_exprs(self, other)
3760 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3761
3762 def __ror__(self, other):
3763 """Create the Z3 expression bitwise-or `other | self`.
3764
3765 >>> x = BitVec('x', 32)
3766 >>> 10 | x
3767 10 | x
3768 """
3769 a, b = _coerce_exprs(self, other)
3770 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3771
3772 def __and__(self, other):
3773 """Create the Z3 expression bitwise-and `self & other`.
3774
3775 >>> x = BitVec('x', 32)
3776 >>> y = BitVec('y', 32)
3777 >>> x & y
3778 x & y
3779 >>> (x & y).sort()
3780 BitVec(32)
3781 """
3782 a, b = _coerce_exprs(self, other)
3783 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3784
3785 def __rand__(self, other):
3786 """Create the Z3 expression bitwise-or `other & self`.
3787
3788 >>> x = BitVec('x', 32)
3789 >>> 10 & x
3790 10 & x
3791 """
3792 a, b = _coerce_exprs(self, other)
3793 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3794
3795 def __xor__(self, other):
3796 """Create the Z3 expression bitwise-xor `self ^ other`.
3797
3798 >>> x = BitVec('x', 32)
3799 >>> y = BitVec('y', 32)
3800 >>> x ^ y
3801 x ^ y
3802 >>> (x ^ y).sort()
3803 BitVec(32)
3804 """
3805 a, b = _coerce_exprs(self, other)
3806 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3807
3808 def __rxor__(self, other):
3809 """Create the Z3 expression bitwise-xor `other ^ self`.
3810
3811 >>> x = BitVec('x', 32)
3812 >>> 10 ^ x
3813 10 ^ x
3814 """
3815 a, b = _coerce_exprs(self, other)
3816 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3817
3818 def __pos__(self):
3819 """Return `self`.
3820
3821 >>> x = BitVec('x', 32)
3822 >>> +x
3823 x
3824 """
3825 return self
3826
3827 def __neg__(self):
3828 """Return an expression representing `-self`.
3829
3830 >>> x = BitVec('x', 32)
3831 >>> -x
3832 -x
3833 >>> simplify(-(-x))
3834 x
3835 """
3836 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
3837
3838 def __invert__(self):
3839 """Create the Z3 expression bitwise-not `~self`.
3840
3841 >>> x = BitVec('x', 32)
3842 >>> ~x
3843 ~x
3844 >>> simplify(~(~x))
3845 x
3846 """
3847 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
3848
3849 def __div__(self, other):
3850 """Create the Z3 expression (signed) division `self / other`.
3851
3852 Use the function UDiv() for unsigned division.
3853
3854 >>> x = BitVec('x', 32)
3855 >>> y = BitVec('y', 32)
3856 >>> x / y
3857 x/y
3858 >>> (x / y).sort()
3859 BitVec(32)
3860 >>> (x / y).sexpr()
3861 '(bvsdiv x y)'
3862 >>> UDiv(x, y).sexpr()
3863 '(bvudiv x y)'
3864 """
3865 a, b = _coerce_exprs(self, other)
3866 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3867
3868 def __truediv__(self, other):
3869 """Create the Z3 expression (signed) division `self / other`."""
3870 return self.__div__(other)
3871
3872 def __rdiv__(self, other):
3873 """Create the Z3 expression (signed) division `other / self`.
3874
3875 Use the function UDiv() for unsigned division.
3876
3877 >>> x = BitVec('x', 32)
3878 >>> 10 / x
3879 10/x
3880 >>> (10 / x).sexpr()
3881 '(bvsdiv #x0000000a x)'
3882 >>> UDiv(10, x).sexpr()
3883 '(bvudiv #x0000000a x)'
3884 """
3885 a, b = _coerce_exprs(self, other)
3886 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3887
3888 def __rtruediv__(self, other):
3889 """Create the Z3 expression (signed) division `other / self`."""
3890 return self.__rdiv__(other)
3891
3892 def __mod__(self, other):
3893 """Create the Z3 expression (signed) mod `self % other`.
3894
3895 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3896
3897 >>> x = BitVec('x', 32)
3898 >>> y = BitVec('y', 32)
3899 >>> x % y
3900 x%y
3901 >>> (x % y).sort()
3902 BitVec(32)
3903 >>> (x % y).sexpr()
3904 '(bvsmod x y)'
3905 >>> URem(x, y).sexpr()
3906 '(bvurem x y)'
3907 >>> SRem(x, y).sexpr()
3908 '(bvsrem x y)'
3909 """
3910 a, b = _coerce_exprs(self, other)
3911 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3912
3913 def __rmod__(self, other):
3914 """Create the Z3 expression (signed) mod `other % self`.
3915
3916 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3917
3918 >>> x = BitVec('x', 32)
3919 >>> 10 % x
3920 10%x
3921 >>> (10 % x).sexpr()
3922 '(bvsmod #x0000000a x)'
3923 >>> URem(10, x).sexpr()
3924 '(bvurem #x0000000a x)'
3925 >>> SRem(10, x).sexpr()
3926 '(bvsrem #x0000000a x)'
3927 """
3928 a, b = _coerce_exprs(self, other)
3929 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3930
3931 def __le__(self, other):
3932 """Create the Z3 expression (signed) `other <= self`.
3933
3934 Use the function ULE() for unsigned less than or equal to.
3935
3936 >>> x, y = BitVecs('x y', 32)
3937 >>> x <= y
3938 x <= y
3939 >>> (x <= y).sexpr()
3940 '(bvsle x y)'
3941 >>> ULE(x, y).sexpr()
3942 '(bvule x y)'
3943 """
3944 a, b = _coerce_exprs(self, other)
3945 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3946
3947 def __lt__(self, other):
3948 """Create the Z3 expression (signed) `other < self`.
3949
3950 Use the function ULT() for unsigned less than.
3951
3952 >>> x, y = BitVecs('x y', 32)
3953 >>> x < y
3954 x < y
3955 >>> (x < y).sexpr()
3956 '(bvslt x y)'
3957 >>> ULT(x, y).sexpr()
3958 '(bvult x y)'
3959 """
3960 a, b = _coerce_exprs(self, other)
3961 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3962
3963 def __gt__(self, other):
3964 """Create the Z3 expression (signed) `other > self`.
3965
3966 Use the function UGT() for unsigned greater than.
3967
3968 >>> x, y = BitVecs('x y', 32)
3969 >>> x > y
3970 x > y
3971 >>> (x > y).sexpr()
3972 '(bvsgt x y)'
3973 >>> UGT(x, y).sexpr()
3974 '(bvugt x y)'
3975 """
3976 a, b = _coerce_exprs(self, other)
3977 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3978
3979 def __ge__(self, other):
3980 """Create the Z3 expression (signed) `other >= self`.
3981
3982 Use the function UGE() for unsigned greater than or equal to.
3983
3984 >>> x, y = BitVecs('x y', 32)
3985 >>> x >= y
3986 x >= y
3987 >>> (x >= y).sexpr()
3988 '(bvsge x y)'
3989 >>> UGE(x, y).sexpr()
3990 '(bvuge x y)'
3991 """
3992 a, b = _coerce_exprs(self, other)
3993 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3994
3995 def __rshift__(self, other):
3996 """Create the Z3 expression (arithmetical) right shift `self >> other`
3997
3998 Use the function LShR() for the right logical shift
3999
4000 >>> x, y = BitVecs('x y', 32)
4001 >>> x >> y
4002 x >> y
4003 >>> (x >> y).sexpr()
4004 '(bvashr x y)'
4005 >>> LShR(x, y).sexpr()
4006 '(bvlshr x y)'
4007 >>> BitVecVal(4, 3)
4008 4
4009 >>> BitVecVal(4, 3).as_signed_long()
4010 -4
4011 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4012 -2
4013 >>> simplify(BitVecVal(4, 3) >> 1)
4014 6
4015 >>> simplify(LShR(BitVecVal(4, 3), 1))
4016 2
4017 >>> simplify(BitVecVal(2, 3) >> 1)
4018 1
4019 >>> simplify(LShR(BitVecVal(2, 3), 1))
4020 1
4021 """
4022 a, b = _coerce_exprs(self, other)
4023 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
4024
4025 def __lshift__(self, other):
4026 """Create the Z3 expression left shift `self << other`
4027
4028 >>> x, y = BitVecs('x y', 32)
4029 >>> x << y
4030 x << y
4031 >>> (x << y).sexpr()
4032 '(bvshl x y)'
4033 >>> simplify(BitVecVal(2, 3) << 1)
4034 4
4035 """
4036 a, b = _coerce_exprs(self, other)
4037 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
4038
4039 def __rrshift__(self, other):
4040 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4041
4042 Use the function LShR() for the right logical shift
4043
4044 >>> x = BitVec('x', 32)
4045 >>> 10 >> x
4046 10 >> x
4047 >>> (10 >> x).sexpr()
4048 '(bvashr #x0000000a x)'
4049 """
4050 a, b = _coerce_exprs(self, other)
4051 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
4052
4053 def __rlshift__(self, other):
4054 """Create the Z3 expression left shift `other << self`.
4055
4056 Use the function LShR() for the right logical shift
4057
4058 >>> x = BitVec('x', 32)
4059 >>> 10 << x
4060 10 << x
4061 >>> (10 << x).sexpr()
4062 '(bvshl #x0000000a x)'
4063 """
4064 a, b = _coerce_exprs(self, other)
4065 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
4066
4067
4069 """Bit-vector values."""
4070
4071 def as_long(self):
4072 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4073
4074 >>> v = BitVecVal(0xbadc0de, 32)
4075 >>> v
4076 195936478
4077 >>> print("0x%.8x" % v.as_long())
4078 0x0badc0de
4079 """
4080 return int(self.as_string())
4081
4083 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4084 The most significant bit is assumed to be the sign.
4085
4086 >>> BitVecVal(4, 3).as_signed_long()
4087 -4
4088 >>> BitVecVal(7, 3).as_signed_long()
4089 -1
4090 >>> BitVecVal(3, 3).as_signed_long()
4091 3
4092 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4093 -1
4094 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4095 -1
4096 """
4097 sz = self.size()
4098 val = self.as_long()
4099 if val >= 2**(sz - 1):
4100 val = val - 2**sz
4101 if val < -2**(sz - 1):
4102 val = val + 2**sz
4103 return int(val)
4104
4105 def as_string(self):
4106 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
4107
4109 return Z3_get_numeral_binary_string(self.ctx_ref(), self.as_ast())
4110
4111 def py_value(self):
4112 """Return the Python value of a Z3 bit-vector numeral."""
4113 return self.as_long()
4114
4115
4116
4117def is_bv(a):
4118 """Return `True` if `a` is a Z3 bit-vector expression.
4119
4120 >>> b = BitVec('b', 32)
4121 >>> is_bv(b)
4122 True
4123 >>> is_bv(b + 10)
4124 True
4125 >>> is_bv(Int('x'))
4126 False
4127 """
4128 return isinstance(a, BitVecRef)
4129
4130
4132 """Return `True` if `a` is a Z3 bit-vector numeral value.
4133
4134 >>> b = BitVec('b', 32)
4135 >>> is_bv_value(b)
4136 False
4137 >>> b = BitVecVal(10, 32)
4138 >>> b
4139 10
4140 >>> is_bv_value(b)
4141 True
4142 """
4143 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
4144
4145
4146def BV2Int(a, is_signed=False):
4147 """Return the Z3 expression BV2Int(a).
4148
4149 >>> b = BitVec('b', 3)
4150 >>> BV2Int(b).sort()
4151 Int
4152 >>> x = Int('x')
4153 >>> x > BV2Int(b)
4154 x > BV2Int(b)
4155 >>> x > BV2Int(b, is_signed=False)
4156 x > BV2Int(b)
4157 >>> x > BV2Int(b, is_signed=True)
4158 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4159 >>> solve(x > BV2Int(b), b == 1, x < 3)
4160 [x = 2, b = 1]
4161 """
4162 if z3_debug():
4163 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4164 ctx = a.ctx
4165 # investigate problem with bv2int
4166 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
4167
4168
4169def Int2BV(a, num_bits):
4170 """Return the z3 expression Int2BV(a, num_bits).
4171 It is a bit-vector of width num_bits and represents the
4172 modulo of a by 2^num_bits
4173 """
4174 ctx = a.ctx
4175 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
4176
4177
4178def BitVecSort(sz, ctx=None):
4179 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4180
4181 >>> Byte = BitVecSort(8)
4182 >>> Word = BitVecSort(16)
4183 >>> Byte
4184 BitVec(8)
4185 >>> x = Const('x', Byte)
4186 >>> eq(x, BitVec('x', 8))
4187 True
4188 """
4189 ctx = _get_ctx(ctx)
4190 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4191
4192
4193def BitVecVal(val, bv, ctx=None):
4194 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4195
4196 >>> v = BitVecVal(10, 32)
4197 >>> v
4198 10
4199 >>> print("0x%.8x" % v.as_long())
4200 0x0000000a
4201 """
4202 if is_bv_sort(bv):
4203 ctx = bv.ctx
4204 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4205 else:
4206 ctx = _get_ctx(ctx)
4207 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4208
4209
4210def BitVec(name, bv, ctx=None):
4211 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4212 If `ctx=None`, then the global context is used.
4213
4214 >>> x = BitVec('x', 16)
4215 >>> is_bv(x)
4216 True
4217 >>> x.size()
4218 16
4219 >>> x.sort()
4220 BitVec(16)
4221 >>> word = BitVecSort(16)
4222 >>> x2 = BitVec('x', word)
4223 >>> eq(x, x2)
4224 True
4225 """
4226 if isinstance(bv, BitVecSortRef):
4227 ctx = bv.ctx
4228 else:
4229 ctx = _get_ctx(ctx)
4230 bv = BitVecSort(bv, ctx)
4231 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4232
4233
4234def BitVecs(names, bv, ctx=None):
4235 """Return a tuple of bit-vector constants of size bv.
4236
4237 >>> x, y, z = BitVecs('x y z', 16)
4238 >>> x.size()
4239 16
4240 >>> x.sort()
4241 BitVec(16)
4242 >>> Sum(x, y, z)
4243 0 + x + y + z
4244 >>> Product(x, y, z)
4245 1*x*y*z
4246 >>> simplify(Product(x, y, z))
4247 x*y*z
4248 """
4249 ctx = _get_ctx(ctx)
4250 if isinstance(names, str):
4251 names = names.split(" ")
4252 return [BitVec(name, bv, ctx) for name in names]
4253
4254
4255def Concat(*args):
4256 """Create a Z3 bit-vector concatenation expression.
4257
4258 >>> v = BitVecVal(1, 4)
4259 >>> Concat(v, v+1, v)
4260 Concat(Concat(1, 1 + 1), 1)
4261 >>> simplify(Concat(v, v+1, v))
4262 289
4263 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4264 121
4265 """
4266 args = _get_args(args)
4267 sz = len(args)
4268 if z3_debug():
4269 _z3_assert(sz >= 2, "At least two arguments expected.")
4270
4271 ctx = None
4272 for a in args:
4273 if is_expr(a):
4274 ctx = a.ctx
4275 break
4276 if is_seq(args[0]) or isinstance(args[0], str):
4277 args = [_coerce_seq(s, ctx) for s in args]
4278 if z3_debug():
4279 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4280 v = (Ast * sz)()
4281 for i in range(sz):
4282 v[i] = args[i].as_ast()
4283 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4284
4285 if is_re(args[0]):
4286 if z3_debug():
4287 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4288 v = (Ast * sz)()
4289 for i in range(sz):
4290 v[i] = args[i].as_ast()
4291 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4292
4293 if z3_debug():
4294 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4295 r = args[0]
4296 for i in range(sz - 1):
4297 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4298 return r
4299
4300
4301def Extract(high, low, a):
4302 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4303
4304 Extract is overloaded to work with both bit-vectors and sequences:
4305
4306 **Bit-vector extraction**: Extract(high, low, bitvector)
4307 Extracts bits from position `high` down to position `low` (both inclusive).
4308 - high: int - the highest bit position to extract (0-indexed from right)
4309 - low: int - the lowest bit position to extract (0-indexed from right)
4310 - bitvector: BitVecRef - the bit-vector to extract from
4311 Returns a new bit-vector containing bits [high:low]
4312
4313 **Sequence extraction**: Extract(sequence, offset, length)
4314 Extracts a subsequence starting at the given offset with the specified length.
4315 The functions SubString and SubSeq are redirected to this form of Extract.
4316 - sequence: SeqRef or str - the sequence to extract from
4317 - offset: int - the starting position (0-indexed)
4318 - length: int - the number of elements to extract
4319 Returns a new sequence containing the extracted subsequence
4320
4321 >>> # Bit-vector extraction examples
4322 >>> x = BitVec('x', 8)
4323 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4324 Extract(6, 2, x)
4325 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4326 BitVec(5)
4327 >>> Extract(7, 0, x) # Extract all 8 bits
4328 Extract(7, 0, x)
4329 >>> Extract(3, 3, x) # Extract single bit at position 3
4330 Extract(3, 3, x)
4331
4332 >>> # Sequence extraction examples
4333 >>> s = StringVal("hello")
4334 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4335 str.substr("hello", 1, 3)
4336 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4337 "c"
4338 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4339 "ab"
4340 """
4341 if isinstance(high, str):
4342 high = StringVal(high)
4343 if is_seq(high):
4344 s = high
4345 offset, length = _coerce_exprs(low, a, s.ctx)
4346 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4347 if z3_debug():
4348 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4349 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4350 "First and second arguments must be non negative integers")
4351 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4352 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4353
4354
4356 if z3_debug():
4357 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4358
4359
4360def ULE(a, b):
4361 """Create the Z3 expression (unsigned) `other <= self`.
4362
4363 Use the operator <= for signed less than or equal to.
4364
4365 >>> x, y = BitVecs('x y', 32)
4366 >>> ULE(x, y)
4367 ULE(x, y)
4368 >>> (x <= y).sexpr()
4369 '(bvsle x y)'
4370 >>> ULE(x, y).sexpr()
4371 '(bvule x y)'
4372 """
4373 _check_bv_args(a, b)
4374 a, b = _coerce_exprs(a, b)
4375 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4376
4377
4378def ULT(a, b):
4379 """Create the Z3 expression (unsigned) `other < self`.
4380
4381 Use the operator < for signed less than.
4382
4383 >>> x, y = BitVecs('x y', 32)
4384 >>> ULT(x, y)
4385 ULT(x, y)
4386 >>> (x < y).sexpr()
4387 '(bvslt x y)'
4388 >>> ULT(x, y).sexpr()
4389 '(bvult x y)'
4390 """
4391 _check_bv_args(a, b)
4392 a, b = _coerce_exprs(a, b)
4393 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4394
4395
4396def UGE(a, b):
4397 """Create the Z3 expression (unsigned) `other >= self`.
4398
4399 Use the operator >= for signed greater than or equal to.
4400
4401 >>> x, y = BitVecs('x y', 32)
4402 >>> UGE(x, y)
4403 UGE(x, y)
4404 >>> (x >= y).sexpr()
4405 '(bvsge x y)'
4406 >>> UGE(x, y).sexpr()
4407 '(bvuge x y)'
4408 """
4409 _check_bv_args(a, b)
4410 a, b = _coerce_exprs(a, b)
4411 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4412
4413
4414def UGT(a, b):
4415 """Create the Z3 expression (unsigned) `other > self`.
4416
4417 Use the operator > for signed greater than.
4418
4419 >>> x, y = BitVecs('x y', 32)
4420 >>> UGT(x, y)
4421 UGT(x, y)
4422 >>> (x > y).sexpr()
4423 '(bvsgt x y)'
4424 >>> UGT(x, y).sexpr()
4425 '(bvugt x y)'
4426 """
4427 _check_bv_args(a, b)
4428 a, b = _coerce_exprs(a, b)
4429 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4430
4431
4432def UDiv(a, b):
4433 """Create the Z3 expression (unsigned) division `self / other`.
4434
4435 Use the operator / for signed division.
4436
4437 >>> x = BitVec('x', 32)
4438 >>> y = BitVec('y', 32)
4439 >>> UDiv(x, y)
4440 UDiv(x, y)
4441 >>> UDiv(x, y).sort()
4442 BitVec(32)
4443 >>> (x / y).sexpr()
4444 '(bvsdiv x y)'
4445 >>> UDiv(x, y).sexpr()
4446 '(bvudiv x y)'
4447 """
4448 _check_bv_args(a, b)
4449 a, b = _coerce_exprs(a, b)
4450 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4451
4452
4453def URem(a, b):
4454 """Create the Z3 expression (unsigned) remainder `self % other`.
4455
4456 Use the operator % for signed modulus, and SRem() for signed remainder.
4457
4458 >>> x = BitVec('x', 32)
4459 >>> y = BitVec('y', 32)
4460 >>> URem(x, y)
4461 URem(x, y)
4462 >>> URem(x, y).sort()
4463 BitVec(32)
4464 >>> (x % y).sexpr()
4465 '(bvsmod x y)'
4466 >>> URem(x, y).sexpr()
4467 '(bvurem x y)'
4468 """
4469 _check_bv_args(a, b)
4470 a, b = _coerce_exprs(a, b)
4471 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4472
4473
4474def SRem(a, b):
4475 """Create the Z3 expression signed remainder.
4476
4477 Use the operator % for signed modulus, and URem() for unsigned remainder.
4478
4479 >>> x = BitVec('x', 32)
4480 >>> y = BitVec('y', 32)
4481 >>> SRem(x, y)
4482 SRem(x, y)
4483 >>> SRem(x, y).sort()
4484 BitVec(32)
4485 >>> (x % y).sexpr()
4486 '(bvsmod x y)'
4487 >>> SRem(x, y).sexpr()
4488 '(bvsrem x y)'
4489 """
4490 _check_bv_args(a, b)
4491 a, b = _coerce_exprs(a, b)
4492 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4493
4494
4495def LShR(a, b):
4496 """Create the Z3 expression logical right shift.
4497
4498 Use the operator >> for the arithmetical right shift.
4499
4500 >>> x, y = BitVecs('x y', 32)
4501 >>> LShR(x, y)
4502 LShR(x, y)
4503 >>> (x >> y).sexpr()
4504 '(bvashr x y)'
4505 >>> LShR(x, y).sexpr()
4506 '(bvlshr x y)'
4507 >>> BitVecVal(4, 3)
4508 4
4509 >>> BitVecVal(4, 3).as_signed_long()
4510 -4
4511 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4512 -2
4513 >>> simplify(BitVecVal(4, 3) >> 1)
4514 6
4515 >>> simplify(LShR(BitVecVal(4, 3), 1))
4516 2
4517 >>> simplify(BitVecVal(2, 3) >> 1)
4518 1
4519 >>> simplify(LShR(BitVecVal(2, 3), 1))
4520 1
4521 """
4522 _check_bv_args(a, b)
4523 a, b = _coerce_exprs(a, b)
4524 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4525
4526
4527def RotateLeft(a, b):
4528 """Return an expression representing `a` rotated to the left `b` times.
4529
4530 >>> a, b = BitVecs('a b', 16)
4531 >>> RotateLeft(a, b)
4532 RotateLeft(a, b)
4533 >>> simplify(RotateLeft(a, 0))
4534 a
4535 >>> simplify(RotateLeft(a, 16))
4536 a
4537 """
4538 _check_bv_args(a, b)
4539 a, b = _coerce_exprs(a, b)
4540 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4541
4542
4543def RotateRight(a, b):
4544 """Return an expression representing `a` rotated to the right `b` times.
4545
4546 >>> a, b = BitVecs('a b', 16)
4547 >>> RotateRight(a, b)
4548 RotateRight(a, b)
4549 >>> simplify(RotateRight(a, 0))
4550 a
4551 >>> simplify(RotateRight(a, 16))
4552 a
4553 """
4554 _check_bv_args(a, b)
4555 a, b = _coerce_exprs(a, b)
4556 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4557
4558
4559def SignExt(n, a):
4560 """Return a bit-vector expression with `n` extra sign-bits.
4561
4562 >>> x = BitVec('x', 16)
4563 >>> n = SignExt(8, x)
4564 >>> n.size()
4565 24
4566 >>> n
4567 SignExt(8, x)
4568 >>> n.sort()
4569 BitVec(24)
4570 >>> v0 = BitVecVal(2, 2)
4571 >>> v0
4572 2
4573 >>> v0.size()
4574 2
4575 >>> v = simplify(SignExt(6, v0))
4576 >>> v
4577 254
4578 >>> v.size()
4579 8
4580 >>> print("%.x" % v.as_long())
4581 fe
4582 """
4583 if z3_debug():
4584 _z3_assert(_is_int(n), "First argument must be an integer")
4585 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4586 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4587
4588
4589def ZeroExt(n, a):
4590 """Return a bit-vector expression with `n` extra zero-bits.
4591
4592 >>> x = BitVec('x', 16)
4593 >>> n = ZeroExt(8, x)
4594 >>> n.size()
4595 24
4596 >>> n
4597 ZeroExt(8, x)
4598 >>> n.sort()
4599 BitVec(24)
4600 >>> v0 = BitVecVal(2, 2)
4601 >>> v0
4602 2
4603 >>> v0.size()
4604 2
4605 >>> v = simplify(ZeroExt(6, v0))
4606 >>> v
4607 2
4608 >>> v.size()
4609 8
4610 """
4611 if z3_debug():
4612 _z3_assert(_is_int(n), "First argument must be an integer")
4613 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4614 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4615
4616
4618 """Return an expression representing `n` copies of `a`.
4619
4620 >>> x = BitVec('x', 8)
4621 >>> n = RepeatBitVec(4, x)
4622 >>> n
4623 RepeatBitVec(4, x)
4624 >>> n.size()
4625 32
4626 >>> v0 = BitVecVal(10, 4)
4627 >>> print("%.x" % v0.as_long())
4628 a
4629 >>> v = simplify(RepeatBitVec(4, v0))
4630 >>> v.size()
4631 16
4632 >>> print("%.x" % v.as_long())
4633 aaaa
4634 """
4635 if z3_debug():
4636 _z3_assert(_is_int(n), "First argument must be an integer")
4637 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4638 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4639
4640
4642 """Return the reduction-and expression of `a`."""
4643 if z3_debug():
4644 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4645 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4646
4647
4648def BVRedOr(a):
4649 """Return the reduction-or expression of `a`."""
4650 if z3_debug():
4651 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4652 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4653
4654
4655def BvNand(a, b):
4656 """Return the bitwise NAND of `a` and `b`.
4657
4658 >>> x = BitVec('x', 8)
4659 >>> y = BitVec('y', 8)
4660 >>> BvNand(x, y)
4661 bvnand(x, y)
4662 """
4663 _check_bv_args(a, b)
4664 a, b = _coerce_exprs(a, b)
4665 return BitVecRef(Z3_mk_bvnand(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4666
4667
4668def BvNor(a, b):
4669 """Return the bitwise NOR of `a` and `b`.
4670
4671 >>> x = BitVec('x', 8)
4672 >>> y = BitVec('y', 8)
4673 >>> BvNor(x, y)
4674 bvnor(x, y)
4675 """
4676 _check_bv_args(a, b)
4677 a, b = _coerce_exprs(a, b)
4678 return BitVecRef(Z3_mk_bvnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4679
4680
4681def BvXnor(a, b):
4682 """Return the bitwise XNOR of `a` and `b`.
4683
4684 >>> x = BitVec('x', 8)
4685 >>> y = BitVec('y', 8)
4686 >>> BvXnor(x, y)
4687 bvxnor(x, y)
4688 """
4689 _check_bv_args(a, b)
4690 a, b = _coerce_exprs(a, b)
4691 return BitVecRef(Z3_mk_bvxnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4692
4693
4694def BVAddNoOverflow(a, b, signed):
4695 """A predicate the determines that bit-vector addition does not overflow"""
4696 _check_bv_args(a, b)
4697 a, b = _coerce_exprs(a, b)
4698 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4699
4700
4702 """A predicate the determines that signed bit-vector addition does not underflow"""
4703 _check_bv_args(a, b)
4704 a, b = _coerce_exprs(a, b)
4705 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4706
4707
4709 """A predicate the determines that bit-vector subtraction does not overflow"""
4710 _check_bv_args(a, b)
4711 a, b = _coerce_exprs(a, b)
4712 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4713
4714
4715def BVSubNoUnderflow(a, b, signed):
4716 """A predicate the determines that bit-vector subtraction does not underflow"""
4717 _check_bv_args(a, b)
4718 a, b = _coerce_exprs(a, b)
4719 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4720
4721
4723 """A predicate the determines that bit-vector signed division does not overflow"""
4724 _check_bv_args(a, b)
4725 a, b = _coerce_exprs(a, b)
4726 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4727
4728
4730 """A predicate the determines that bit-vector unary negation does not overflow"""
4731 if z3_debug():
4732 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4733 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4734
4735
4736def BVMulNoOverflow(a, b, signed):
4737 """A predicate the determines that bit-vector multiplication does not overflow"""
4738 _check_bv_args(a, b)
4739 a, b = _coerce_exprs(a, b)
4740 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4741
4742
4744 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4745 _check_bv_args(a, b)
4746 a, b = _coerce_exprs(a, b)
4747 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4748
4749
4750
4755
4757 """Array sorts."""
4758
4759 def domain(self):
4760 """Return the domain of the array sort `self`.
4761
4762 >>> A = ArraySort(IntSort(), BoolSort())
4763 >>> A.domain()
4764 Int
4765 """
4767
4768 def domain_n(self, i):
4769 """Return the domain of the array sort `self`.
4770 """
4771 return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), self.ctx)
4772
4773 def range(self):
4774 """Return the range of the array sort `self`.
4775
4776 >>> A = ArraySort(IntSort(), BoolSort())
4777 >>> A.range()
4778 Bool
4779 """
4780 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4781
4782
4784 """Array expressions. """
4785
4786 def sort(self):
4787 """Return the array sort of the array expression `self`.
4788
4789 >>> a = Array('a', IntSort(), BoolSort())
4790 >>> a.sort()
4791 Array(Int, Bool)
4792 """
4793 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
4794
4795 def domain(self):
4796 """Shorthand for `self.sort().domain()`.
4797
4798 >>> a = Array('a', IntSort(), BoolSort())
4799 >>> a.domain()
4800 Int
4801 """
4802 return self.sort().domain()
4803
4804 def domain_n(self, i):
4805 """Shorthand for self.sort().domain_n(i)`."""
4806 return self.sort().domain_n(i)
4807
4808 def range(self):
4809 """Shorthand for `self.sort().range()`.
4810
4811 >>> a = Array('a', IntSort(), BoolSort())
4812 >>> a.range()
4813 Bool
4814 """
4815 return self.sort().range()
4816
4817 def __getitem__(self, arg):
4818 """Return the Z3 expression `self[arg]`.
4819
4820 >>> a = Array('a', IntSort(), BoolSort())
4821 >>> i = Int('i')
4822 >>> a[i]
4823 a[i]
4824 >>> a[i].sexpr()
4825 '(select a i)'
4826 """
4827 return _array_select(self, arg)
4828
4829 def default(self):
4830 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
4831
4832
4833def _array_select(ar, arg):
4834 if isinstance(arg, tuple):
4835 args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))]
4836 _args, sz = _to_ast_array(args)
4837 return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4838 arg = ar.sort().domain().cast(arg)
4839 return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4840
4841
4843 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4844
4845
4846def is_array(a : Any) -> bool:
4847 """Return `True` if `a` is a Z3 array expression.
4848
4849 >>> a = Array('a', IntSort(), IntSort())
4850 >>> is_array(a)
4851 True
4852 >>> is_array(Store(a, 0, 1))
4853 True
4854 >>> is_array(a[0])
4855 False
4856 """
4857 return isinstance(a, ArrayRef)
4858
4859
4861 """Return `True` if `a` is a Z3 constant array.
4862
4863 >>> a = K(IntSort(), 10)
4864 >>> is_const_array(a)
4865 True
4866 >>> a = Array('a', IntSort(), IntSort())
4867 >>> is_const_array(a)
4868 False
4869 """
4870 return is_app_of(a, Z3_OP_CONST_ARRAY)
4871
4872
4873def is_K(a):
4874 """Return `True` if `a` is a Z3 constant array.
4875
4876 >>> a = K(IntSort(), 10)
4877 >>> is_K(a)
4878 True
4879 >>> a = Array('a', IntSort(), IntSort())
4880 >>> is_K(a)
4881 False
4882 """
4883 return is_app_of(a, Z3_OP_CONST_ARRAY)
4884
4885
4886def is_map(a):
4887 """Return `True` if `a` is a Z3 map array expression.
4888
4889 >>> f = Function('f', IntSort(), IntSort())
4890 >>> b = Array('b', IntSort(), IntSort())
4891 >>> a = Map(f, b)
4892 >>> a
4893 Map(f, b)
4894 >>> is_map(a)
4895 True
4896 >>> is_map(b)
4897 False
4898 """
4899 return is_app_of(a, Z3_OP_ARRAY_MAP)
4900
4901
4903 """Return `True` if `a` is a Z3 default array expression.
4904 >>> d = Default(K(IntSort(), 10))
4905 >>> is_default(d)
4906 True
4907 """
4908 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4909
4910
4912 """Return the function declaration associated with a Z3 map array expression.
4913
4914 >>> f = Function('f', IntSort(), IntSort())
4915 >>> b = Array('b', IntSort(), IntSort())
4916 >>> a = Map(f, b)
4917 >>> eq(f, get_map_func(a))
4918 True
4919 >>> get_map_func(a)
4920 f
4921 >>> get_map_func(a)(0)
4922 f(0)
4923 """
4924 if z3_debug():
4925 _z3_assert(is_map(a), "Z3 array map expression expected.")
4926 return FuncDeclRef(
4928 a.ctx_ref(),
4929 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4930 ),
4931 ctx=a.ctx,
4932 )
4933
4934
4935def ArraySort(*sig):
4936 """Return the Z3 array sort with the given domain and range sorts.
4937
4938 >>> A = ArraySort(IntSort(), BoolSort())
4939 >>> A
4940 Array(Int, Bool)
4941 >>> A.domain()
4942 Int
4943 >>> A.range()
4944 Bool
4945 >>> AA = ArraySort(IntSort(), A)
4946 >>> AA
4947 Array(Int, Array(Int, Bool))
4948 """
4949 sig = _get_args(sig)
4950 if z3_debug():
4951 _z3_assert(len(sig) > 1, "At least two arguments expected")
4952 arity = len(sig) - 1
4953 r = sig[arity]
4954 d = sig[0]
4955 if z3_debug():
4956 for s in sig:
4957 _z3_assert(is_sort(s), "Z3 sort expected")
4958 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4959 ctx = d.ctx
4960 if len(sig) == 2:
4961 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4962 dom = (Sort * arity)()
4963 for i in range(arity):
4964 dom[i] = sig[i].ast
4965 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4966
4967
4968def Array(name, *sorts):
4969 """Return an array constant named `name` with the given domain and range sorts.
4970
4971 >>> a = Array('a', IntSort(), IntSort())
4972 >>> a.sort()
4973 Array(Int, Int)
4974 >>> a[0]
4975 a[0]
4976 """
4977 s = ArraySort(sorts)
4978 ctx = s.ctx
4979 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4980
4981
4982def Update(a, *args):
4983 """Return a Z3 store array expression.
4984
4985 >>> a = Array('a', IntSort(), IntSort())
4986 >>> i, v = Ints('i v')
4987 >>> s = Update(a, i, v)
4988 >>> s.sort()
4989 Array(Int, Int)
4990 >>> prove(s[i] == v)
4991 proved
4992 >>> j = Int('j')
4993 >>> prove(Implies(i != j, s[j] == a[j]))
4994 proved
4995 """
4996 if z3_debug():
4997 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4998 args = _get_args(args)
4999 ctx = a.ctx
5000 if len(args) <= 1:
5001 raise Z3Exception("array update requires index and value arguments")
5002 if len(args) == 2:
5003 i = args[0]
5004 v = args[1]
5005 i = a.sort().domain().cast(i)
5006 v = a.sort().range().cast(v)
5007 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
5008 v = a.sort().range().cast(args[-1])
5009 idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
5010 _args, sz = _to_ast_array(idxs)
5011 return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
5012
5013
5014def Default(a):
5015 """ Return a default value for array expression.
5016 >>> b = K(IntSort(), 1)
5017 >>> prove(Default(b) == 1)
5018 proved
5019 """
5020 if z3_debug():
5021 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5022 return a.default()
5023
5024
5025def Store(a, *args):
5026 """Return a Z3 store array expression.
5027
5028 >>> a = Array('a', IntSort(), IntSort())
5029 >>> i, v = Ints('i v')
5030 >>> s = Store(a, i, v)
5031 >>> s.sort()
5032 Array(Int, Int)
5033 >>> prove(s[i] == v)
5034 proved
5035 >>> j = Int('j')
5036 >>> prove(Implies(i != j, s[j] == a[j]))
5037 proved
5038 """
5039 return Update(a, args)
5040
5041
5042def Select(a, *args):
5043 """Return a Z3 select array expression.
5044
5045 >>> a = Array('a', IntSort(), IntSort())
5046 >>> i = Int('i')
5047 >>> Select(a, i)
5048 a[i]
5049 >>> eq(Select(a, i), a[i])
5050 True
5051 """
5052 args = _get_args(args)
5053 if z3_debug():
5054 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5055 return a[args]
5056
5057
5058def Map(f, *args):
5059 """Return a Z3 map array expression.
5060
5061 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5062 >>> a1 = Array('a1', IntSort(), IntSort())
5063 >>> a2 = Array('a2', IntSort(), IntSort())
5064 >>> b = Map(f, a1, a2)
5065 >>> b
5066 Map(f, a1, a2)
5067 >>> prove(b[0] == f(a1[0], a2[0]))
5068 proved
5069 """
5070 args = _get_args(args)
5071 if z3_debug():
5072 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
5073 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
5074 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
5075 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
5076 _args, sz = _to_ast_array(args)
5077 ctx = f.ctx
5078 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
5079
5080
5081def K(dom, v):
5082 """Return a Z3 constant array expression.
5083
5084 >>> a = K(IntSort(), 10)
5085 >>> a
5086 K(Int, 10)
5087 >>> a.sort()
5088 Array(Int, Int)
5089 >>> i = Int('i')
5090 >>> a[i]
5091 K(Int, 10)[i]
5092 >>> simplify(a[i])
5093 10
5094 """
5095 if z3_debug():
5096 _z3_assert(is_sort(dom), "Z3 sort expected")
5097 ctx = dom.ctx
5098 if not is_expr(v):
5099 v = _py2expr(v, ctx)
5100 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
5101
5102
5103def Ext(a, b):
5104 """Return extensionality index for one-dimensional arrays.
5105 >> a, b = Consts('a b', SetSort(IntSort()))
5106 >> Ext(a, b)
5107 Ext(a, b)
5108 """
5109 ctx = a.ctx
5110 if z3_debug():
5111 _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
5112 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5113
5114
5115def AsArray(f):
5116 """Return a Z3 as-array expression for the given function declaration.
5117
5118 >>> f = Function('f', IntSort(), IntSort())
5119 >>> a = AsArray(f)
5120 >>> a.sort()
5121 Array(Int, Int)
5122 >>> is_as_array(a)
5123 True
5124 >>> get_as_array_func(a) == f
5125 True
5126 """
5127 if z3_debug():
5128 _z3_assert(isinstance(f, FuncDeclRef), "function declaration expected")
5129 ctx = f.ctx
5130 return ArrayRef(Z3_mk_as_array(ctx.ref(), f.ast), ctx)
5131
5132
5134 """Return `True` if `a` is a Z3 array select application.
5135
5136 >>> a = Array('a', IntSort(), IntSort())
5137 >>> is_select(a)
5138 False
5139 >>> i = Int('i')
5140 >>> is_select(a[i])
5141 True
5142 """
5143 return is_app_of(a, Z3_OP_SELECT)
5144
5145
5147 """Return `True` if `a` is a Z3 array store application.
5148
5149 >>> a = Array('a', IntSort(), IntSort())
5150 >>> is_store(a)
5151 False
5152 >>> is_store(Store(a, 0, 1))
5153 True
5154 """
5155 return is_app_of(a, Z3_OP_STORE)
5156
5157
5162
5163
5164def SetSort(s):
5165 """ Create a set sort over element sort s"""
5166 return ArraySort(s, BoolSort())
5167
5168
5170 """Create the empty set
5171 >>> EmptySet(IntSort())
5172 K(Int, False)
5173 """
5174 ctx = s.ctx
5175 if is_finite_set_sort(s):
5176 return FiniteSetEmpty(s)
5177 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
5178
5179
5180def FullSet(s):
5181 """Create the full set
5182 >>> FullSet(IntSort())
5183 K(Int, True)
5184 """
5185 ctx = s.ctx
5186 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
5187
5188
5189def SetUnion(*args):
5190 """ Take the union of sets
5191 >>> a = Const('a', SetSort(IntSort()))
5192 >>> b = Const('b', SetSort(IntSort()))
5193 >>> SetUnion(a, b)
5194 union(a, b)
5195 """
5196 args = _get_args(args)
5197 if len(args) > 0 and is_finite_set(args[0]):
5198 from functools import reduce
5199 return reduce(FiniteSetUnion, args)
5200 ctx = _ctx_from_ast_arg_list(args)
5201 _args, sz = _to_ast_array(args)
5202 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
5203
5204
5205def SetIntersect(*args):
5206 """ Take the union of sets
5207 >>> a = Const('a', SetSort(IntSort()))
5208 >>> b = Const('b', SetSort(IntSort()))
5209 >>> SetIntersect(a, b)
5210 intersection(a, b)
5211 """
5212 args = _get_args(args)
5213 ctx = _ctx_from_ast_arg_list(args)
5214 if len(args) > 0 and is_finite_set(args[0]):
5215 from functools import reduce
5216 return reduce(FiniteSetIntersect, args)
5217 _args, sz = _to_ast_array(args)
5218 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
5219
5220
5221def SetAdd(s, e):
5222 """ Add element e to set s
5223 >>> a = Const('a', SetSort(IntSort()))
5224 >>> SetAdd(a, 1)
5225 Store(a, 1, True)
5226 """
5227 ctx = _ctx_from_ast_arg_list([s, e])
5228 e = _py2expr(e, ctx)
5229 if is_finite_set(s):
5230 return FiniteSetSingleton(e) | s
5231 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5232
5233
5234def SetDel(s, e):
5235 """ Remove element e to set s
5236 >>> a = Const('a', SetSort(IntSort()))
5237 >>> SetDel(a, 1)
5238 Store(a, 1, False)
5239 """
5240 ctx = _ctx_from_ast_arg_list([s, e])
5241 e = _py2expr(e, ctx)
5242 if is_finite_set(s):
5243 return s - FiniteSetSingleton(e)
5244 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5245
5246
5248 """ The complement of set s
5249 >>> a = Const('a', SetSort(IntSort()))
5250 >>> SetComplement(a)
5251 complement(a)
5252 """
5253 ctx = s.ctx
5254 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
5255
5256
5258 """ The set difference of a and b
5259 >>> a = Const('a', SetSort(IntSort()))
5260 >>> b = Const('b', SetSort(IntSort()))
5261 >>> SetDifference(a, b)
5262 setminus(a, b)
5263 """
5264 ctx = _ctx_from_ast_arg_list([a, b])
5265 if is_finite_set(a):
5266 return FiniteSetDifference(a, b)
5267 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5268
5269
5270def IsMember(e, s):
5271 """ Check if e is a member of set s
5272 >>> a = Const('a', SetSort(IntSort()))
5273 >>> IsMember(1, a)
5274 a[1]
5275 """
5276 ctx = _ctx_from_ast_arg_list([s, e])
5277 e = _py2expr(e, ctx)
5278 if is_finite_set(s):
5279 return FiniteSetIsMember(e, s)
5280 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5281
5282
5283def IsSubset(a, b):
5284 """ Check if a is a subset of b
5285 >>> a = Const('a', SetSort(IntSort()))
5286 >>> b = Const('b', SetSort(IntSort()))
5287 >>> IsSubset(a, b)
5288 subset(a, b)
5289 """
5290 ctx = _ctx_from_ast_arg_list([a, b])
5291 if is_finite_set(a):
5292 return FiniteSetIsSubset(a, b)
5293 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5294
5295
5296
5301
5302
5304 """Finite set sort."""
5305
5306 def element_sort(self):
5307 """Return the element sort of this finite set sort."""
5309
5310 def cast(self, val):
5311 """Try to cast val as a finite set expression."""
5312 if is_expr(val):
5313 if self.eq(val.sort()):
5314 return val
5315 else:
5316 _z3_assert(False, "Cannot cast to finite set sort")
5317 if isinstance(val, set):
5318 elem_sort = self.element_sort()
5319 result = FiniteSetEmpty(self)
5320 for e in val:
5321 result = FiniteSetUnion(result, Singleton(_py2expr(e, self.ctx, elem_sort)))
5322 return result
5323 _z3_assert(False, "Cannot cast to finite set sort")
5324
5325 def subsort(self, other):
5326 return False
5327
5328 def is_int(self):
5329 return False
5330
5331 def is_bool(self):
5332 return False
5333
5334 def is_datatype(self):
5335 return False
5336
5337 def is_array(self):
5338 return False
5339
5340 def is_bv(self):
5341 return False
5342
5343
5345 """Return True if a is a Z3 finite set expression.
5346 >>> s = FiniteSetSort(IntSort())
5347 >>> is_finite_set(FiniteSetEmpty(s))
5348 True
5349 >>> is_finite_set(IntVal(1))
5350 False
5351 """
5352 return isinstance(a, FiniteSetRef)
5353
5354
5356 """Return True if s is a Z3 finite set sort.
5357 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5358 True
5359 >>> is_finite_set_sort(IntSort())
5360 False
5361 """
5362 return isinstance(s, FiniteSetSortRef)
5363
5364
5366 """Finite set expression."""
5367
5368 def sort(self):
5369 return FiniteSetSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
5370
5371 def __or__(self, other):
5372 """Return the union of self and other."""
5373 return FiniteSetUnion(self, other)
5374
5375 def __and__(self, other):
5376 """Return the intersection of self and other."""
5377 return FiniteSetIntersect(self, other)
5378
5379 def __sub__(self, other):
5380 """Return the set difference of self and other."""
5381 return FiniteSetDifference(self, other)
5382
5383
5384def FiniteSetSort(elem_sort):
5385 """Create a finite set sort over element sort elem_sort.
5386 >>> s = FiniteSetSort(IntSort())
5387 >>> s
5388 FiniteSet(Int)
5389 """
5390 return FiniteSetSortRef(Z3_mk_finite_set_sort(elem_sort.ctx_ref(), elem_sort.ast), elem_sort.ctx)
5391
5392
5393def FiniteSetEmpty(set_sort):
5394 """Create an empty finite set of the given sort.
5395 >>> s = FiniteSetSort(IntSort())
5396 >>> FiniteSetEmpty(s)
5397 set.empty
5398 """
5399 ctx = set_sort.ctx
5400 return FiniteSetRef(Z3_mk_finite_set_empty(ctx.ref(), set_sort.ast), ctx)
5401
5402
5403def Singleton(elem):
5404 """Create a singleton finite set containing elem.
5405 >>> Singleton(IntVal(1))
5406 set.singleton(1)
5407 """
5408 ctx = elem.ctx
5409 return FiniteSetRef(Z3_mk_finite_set_singleton(ctx.ref(), elem.as_ast()), ctx)
5410
5411
5412def FiniteSetUnion(s1, s2):
5413 """Create the union of two finite sets.
5414 >>> a = Const('a', FiniteSetSort(IntSort()))
5415 >>> b = Const('b', FiniteSetSort(IntSort()))
5416 >>> FiniteSetUnion(a, b)
5417 set.union(a, b)
5418 """
5419 ctx = _ctx_from_ast_arg_list([s1, s2])
5420 return FiniteSetRef(Z3_mk_finite_set_union(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5421
5422
5424 """Create the intersection of two finite sets.
5425 >>> a = Const('a', FiniteSetSort(IntSort()))
5426 >>> b = Const('b', FiniteSetSort(IntSort()))
5427 >>> FiniteSetIntersect(a, b)
5428 set.intersect(a, b)
5429 """
5430 ctx = _ctx_from_ast_arg_list([s1, s2])
5431 return FiniteSetRef(Z3_mk_finite_set_intersect(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5432
5433
5435 """Create the set difference of two finite sets.
5436 >>> a = Const('a', FiniteSetSort(IntSort()))
5437 >>> b = Const('b', FiniteSetSort(IntSort()))
5438 >>> FiniteSetDifference(a, b)
5439 set.difference(a, b)
5440 """
5441 ctx = _ctx_from_ast_arg_list([s1, s2])
5442 return FiniteSetRef(Z3_mk_finite_set_difference(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5443
5444
5445def FiniteSetMember(elem, set):
5446 """Check if elem is a member of the finite set.
5447 >>> a = Const('a', FiniteSetSort(IntSort()))
5448 >>> FiniteSetMember(IntVal(1), a)
5449 set.in(1, a)
5450 """
5451 ctx = _ctx_from_ast_arg_list([elem, set])
5452 return BoolRef(Z3_mk_finite_set_member(ctx.ref(), elem.as_ast(), set.as_ast()), ctx)
5453
5454def In(elem, set):
5455 return FiniteSetMember(elem, set)
5456
5458 """Get the size (cardinality) of a finite set.
5459 >>> a = Const('a', FiniteSetSort(IntSort()))
5460 >>> FiniteSetSize(a)
5461 set.size(a)
5462 """
5463 ctx = set.ctx
5464 return ArithRef(Z3_mk_finite_set_size(ctx.ref(), set.as_ast()), ctx)
5465
5466
5468 """Check if s1 is a subset of s2.
5469 >>> a = Const('a', FiniteSetSort(IntSort()))
5470 >>> b = Const('b', FiniteSetSort(IntSort()))
5471 >>> FiniteSetSubset(a, b)
5472 set.subset(a, b)
5473 """
5474 ctx = _ctx_from_ast_arg_list([s1, s2])
5475 return BoolRef(Z3_mk_finite_set_subset(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5476
5477
5478def FiniteSetMap(f, set):
5479 """Apply function f to all elements of the finite set.
5480 >>> f = Array('f', IntSort(), IntSort())
5481 >>> a = Const('a', FiniteSetSort(IntSort()))
5482 >>> FiniteSetMap(f, a)
5483 set.map(f, a)
5484 """
5485 if isinstance(f, FuncDeclRef):
5486 f = AsArray(f)
5487 ctx = _ctx_from_ast_arg_list([f, set])
5488 return FiniteSetRef(Z3_mk_finite_set_map(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5489
5490
5492 """Filter a finite set using predicate f.
5493 >>> f = Array('f', IntSort(), BoolSort())
5494 >>> a = Const('a', FiniteSetSort(IntSort()))
5495 >>> FiniteSetFilter(f, a)
5496 set.filter(f, a)
5497 """
5498 if isinstance(f, FuncDeclRef):
5499 f = AsArray(f)
5500 ctx = _ctx_from_ast_arg_list([f, set])
5501 return FiniteSetRef(Z3_mk_finite_set_filter(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5502
5503
5504def FiniteSetRange(low, high):
5505 """Create a finite set of integers in the range [low, high).
5506 >>> FiniteSetRange(IntVal(0), IntVal(5))
5507 set.range(0, 5)
5508 """
5509 ctx = _ctx_from_ast_arg_list([low, high])
5510 return FiniteSetRef(Z3_mk_finite_set_range(ctx.ref(), low.as_ast(), high.as_ast()), ctx)
5511
5512
5513
5518
5520 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5521 if not isinstance(acc, tuple):
5522 return False
5523 if len(acc) != 2:
5524 return False
5525 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5526
5527
5529 """Helper class for declaring Z3 datatypes.
5530
5531 >>> List = Datatype('List')
5532 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5533 >>> List.declare('nil')
5534 >>> List = List.create()
5535 >>> # List is now a Z3 declaration
5536 >>> List.nil
5537 nil
5538 >>> List.cons(10, List.nil)
5539 cons(10, nil)
5540 >>> List.cons(10, List.nil).sort()
5541 List
5542 >>> cons = List.cons
5543 >>> nil = List.nil
5544 >>> car = List.car
5545 >>> cdr = List.cdr
5546 >>> n = cons(1, cons(0, nil))
5547 >>> n
5548 cons(1, cons(0, nil))
5549 >>> simplify(cdr(n))
5550 cons(0, nil)
5551 >>> simplify(car(n))
5552 1
5553 """
5554
5555 def __init__(self, name, ctx=None):
5556 self.ctx = _get_ctx(ctx)
5557 self.name = name
5559
5560 def __deepcopy__(self, memo={}):
5561 r = Datatype(self.name, self.ctx)
5562 r.constructors = copy.deepcopy(self.constructors)
5563 return r
5564
5565 def declare_core(self, name, rec_name, *args):
5566 if z3_debug():
5567 _z3_assert(isinstance(name, str), "String expected")
5568 _z3_assert(isinstance(rec_name, str), "String expected")
5569 _z3_assert(
5570 all([_valid_accessor(a) for a in args]),
5571 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5572 )
5573 self.constructors.append((name, rec_name, args))
5574
5575 def declare(self, name, *args):
5576 """Declare constructor named `name` with the given accessors `args`.
5577 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5578 or a reference to the datatypes being declared.
5579
5580 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5581 declares the constructor named `cons` that builds a new List using an integer and a List.
5582 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5583 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5584 we use the method create() to create the actual datatype in Z3.
5585
5586 >>> List = Datatype('List')
5587 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5588 >>> List.declare('nil')
5589 >>> List = List.create()
5590 """
5591 if z3_debug():
5592 _z3_assert(isinstance(name, str), "String expected")
5593 _z3_assert(name != "", "Constructor name cannot be empty")
5594 return self.declare_core(name, "is-" + name, *args)
5595
5596 def __repr__(self):
5597 return "Datatype(%s, %s)" % (self.name, self.constructors)
5598
5599 def create(self):
5600 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5601
5602 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5603
5604 >>> List = Datatype('List')
5605 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5606 >>> List.declare('nil')
5607 >>> List = List.create()
5608 >>> List.nil
5609 nil
5610 >>> List.cons(10, List.nil)
5611 cons(10, nil)
5612 """
5613 return CreateDatatypes([self])[0]
5614
5615 def create_polymorphic(self, type_params):
5616 """Create a polymorphic Z3 datatype with explicit type variables.
5617
5618 `type_params` is a list of type variables created with `DeclareTypeVar`.
5619 Constructor field sorts may reference these type variables.
5620 Self-recursive fields may reference this datatype directly.
5621
5622 >>> A = DeclareTypeVar('A')
5623 >>> Pair = Datatype('Pair')
5624 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5625 >>> Pair = Pair.create_polymorphic([A])
5626 """
5627 return CreatePolymorphicDatatype(self, type_params)
5628
5629
5631 """Auxiliary object used to create Z3 datatypes."""
5632
5633 def __init__(self, c, ctx):
5634 self.c = c
5635 self.ctx = ctx
5636
5637 def __del__(self):
5638 if self.ctx.ref() is not None and Z3_del_constructor is not None:
5639 Z3_del_constructor(self.ctx.ref(), self.c)
5640
5641
5643 """Auxiliary object used to create Z3 datatypes."""
5644
5645 def __init__(self, c, ctx):
5646 self.c = c
5647 self.ctx = ctx
5648
5649 def __del__(self):
5650 if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5651 Z3_del_constructor_list(self.ctx.ref(), self.c)
5652
5653
5655 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5656
5657 In the following example we define a Tree-List using two mutually recursive datatypes.
5658
5659 >>> TreeList = Datatype('TreeList')
5660 >>> Tree = Datatype('Tree')
5661 >>> # Tree has two constructors: leaf and node
5662 >>> Tree.declare('leaf', ('val', IntSort()))
5663 >>> # a node contains a list of trees
5664 >>> Tree.declare('node', ('children', TreeList))
5665 >>> TreeList.declare('nil')
5666 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5667 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5668 >>> Tree.val(Tree.leaf(10))
5669 val(leaf(10))
5670 >>> simplify(Tree.val(Tree.leaf(10)))
5671 10
5672 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5673 >>> n1
5674 node(cons(leaf(10), cons(leaf(20), nil)))
5675 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5676 >>> simplify(n2 == n1)
5677 False
5678 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5679 True
5680 """
5681 ds = _get_args(ds)
5682 if z3_debug():
5683 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5684 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5685 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5686 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5687 ctx = ds[0].ctx
5688 num = len(ds)
5689 names = (Symbol * num)()
5690 out = (Sort * num)()
5691 clists = (ConstructorList * num)()
5692 to_delete = []
5693 for i in range(num):
5694 d = ds[i]
5695 names[i] = to_symbol(d.name, ctx)
5696 num_cs = len(d.constructors)
5697 cs = (Constructor * num_cs)()
5698 for j in range(num_cs):
5699 c = d.constructors[j]
5700 cname = to_symbol(c[0], ctx)
5701 rname = to_symbol(c[1], ctx)
5702 fs = c[2]
5703 num_fs = len(fs)
5704 fnames = (Symbol * num_fs)()
5705 sorts = (Sort * num_fs)()
5706 refs = (ctypes.c_uint * num_fs)()
5707 for k in range(num_fs):
5708 fname = fs[k][0]
5709 ftype = fs[k][1]
5710 fnames[k] = to_symbol(fname, ctx)
5711 if isinstance(ftype, Datatype):
5712 if z3_debug():
5713 _z3_assert(
5714 ds.count(ftype) == 1,
5715 "One and only one occurrence of each datatype is expected",
5716 )
5717 sorts[k] = None
5718 refs[k] = ds.index(ftype)
5719 else:
5720 if z3_debug():
5721 _z3_assert(is_sort(ftype), "Z3 sort expected")
5722 sorts[k] = ftype.ast
5723 refs[k] = 0
5724 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5725 to_delete.append(ScopedConstructor(cs[j], ctx))
5726 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5727 to_delete.append(ScopedConstructorList(clists[i], ctx))
5728 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5729 result = []
5730 # Create a field for every constructor, recognizer and accessor
5731 for i in range(num):
5732 dref = DatatypeSortRef(out[i], ctx)
5733 num_cs = dref.num_constructors()
5734 for j in range(num_cs):
5735 cref = dref.constructor(j)
5736 cref_name = cref.name()
5737 cref_arity = cref.arity()
5738 if cref.arity() == 0:
5739 cref = cref()
5740 setattr(dref, cref_name, cref)
5741 rref = dref.recognizer(j)
5742 setattr(dref, "is_" + cref_name, rref)
5743 for k in range(cref_arity):
5744 aref = dref.accessor(j, k)
5745 setattr(dref, aref.name(), aref)
5746 result.append(dref)
5747 return tuple(result)
5748
5749
5750def CreatePolymorphicDatatype(d, type_params):
5751 """Create a single polymorphic Z3 datatype with explicit type parameters.
5752
5753 `d` is a `Datatype` helper object whose constructors have been declared.
5754 `type_params` is a list of type variables created with `DeclareTypeVar`.
5755 Constructor field sorts may reference these type variables, and self-recursive
5756 fields may reference `d` directly.
5757
5758 >>> A = DeclareTypeVar('A')
5759 >>> Pair = Datatype('Pair')
5760 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5761 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5762 """
5763 if z3_debug():
5764 _z3_assert(isinstance(d, Datatype), "Datatype expected")
5765 _z3_assert(d.constructors != [], "Non-empty Datatype expected")
5766 ctx = d.ctx
5767 name = to_symbol(d.name, ctx)
5768 num_params = len(type_params)
5769 params_arr = (Sort * num_params)()
5770 for i, p in enumerate(type_params):
5771 if z3_debug():
5772 _z3_assert(is_sort(p), "Z3 sort expected for type parameter")
5773 params_arr[i] = p.ast
5774 num_cs = len(d.constructors)
5775 cs = (Constructor * num_cs)()
5776 to_delete = []
5777 for j in range(num_cs):
5778 c = d.constructors[j]
5779 cname = to_symbol(c[0], ctx)
5780 rname = to_symbol(c[1], ctx)
5781 fs = c[2]
5782 num_fs = len(fs)
5783 fnames = (Symbol * num_fs)()
5784 sorts = (Sort * num_fs)()
5785 refs = (ctypes.c_uint * num_fs)()
5786 for k in range(num_fs):
5787 fname = fs[k][0]
5788 ftype = fs[k][1]
5789 fnames[k] = to_symbol(fname, ctx)
5790 if isinstance(ftype, Datatype):
5791 if z3_debug():
5792 _z3_assert(ftype is d, "Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5793 sorts[k] = None
5794 refs[k] = 0
5795 else:
5796 if z3_debug():
5797 _z3_assert(is_sort(ftype), "Z3 sort expected")
5798 sorts[k] = ftype.ast
5799 refs[k] = 0
5800 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5801 to_delete.append(ScopedConstructor(cs[j], ctx))
5802 out = Z3_mk_polymorphic_datatype(ctx.ref(), name, num_params, params_arr, num_cs, cs)
5803 dref = DatatypeSortRef(out, ctx)
5804 num_cs_actual = dref.num_constructors()
5805 for j in range(num_cs_actual):
5806 cref = dref.constructor(j)
5807 cref_name = cref.name()
5808 cref_arity = cref.arity()
5809 if cref_arity == 0:
5810 cref = cref()
5811 setattr(dref, cref_name, cref)
5812 rref = dref.recognizer(j)
5813 setattr(dref, "is_" + cref_name, rref)
5814 for k in range(cref_arity):
5815 aref = dref.accessor(j, k)
5816 setattr(dref, aref.name(), aref)
5817 return dref
5818
5819
5821 """Datatype sorts."""
5822
5824 """Return the number of constructors in the given Z3 datatype.
5825
5826 >>> List = Datatype('List')
5827 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5828 >>> List.declare('nil')
5829 >>> List = List.create()
5830 >>> # List is now a Z3 declaration
5831 >>> List.num_constructors()
5832 2
5833 """
5835
5836 def constructor(self, idx):
5837 """Return a constructor of the datatype `self`.
5838
5839 >>> List = Datatype('List')
5840 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5841 >>> List.declare('nil')
5842 >>> List = List.create()
5843 >>> # List is now a Z3 declaration
5844 >>> List.num_constructors()
5845 2
5846 >>> List.constructor(0)
5847 cons
5848 >>> List.constructor(1)
5849 nil
5850 """
5851 if z3_debug():
5852 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5854
5855 def recognizer(self, idx):
5856 """In Z3, each constructor has an associated recognizer predicate.
5857
5858 If the constructor is named `name`, then the recognizer `is_name`.
5859
5860 >>> List = Datatype('List')
5861 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5862 >>> List.declare('nil')
5863 >>> List = List.create()
5864 >>> # List is now a Z3 declaration
5865 >>> List.num_constructors()
5866 2
5867 >>> List.recognizer(0)
5868 is(cons)
5869 >>> List.recognizer(1)
5870 is(nil)
5871 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5872 False
5873 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5874 True
5875 >>> l = Const('l', List)
5876 >>> simplify(List.is_cons(l))
5877 is(cons, l)
5878 """
5879 if z3_debug():
5880 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5881 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
5882
5883 def accessor(self, i, j):
5884 """In Z3, each constructor has 0 or more accessor.
5885 The number of accessors is equal to the arity of the constructor.
5886
5887 >>> List = Datatype('List')
5888 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5889 >>> List.declare('nil')
5890 >>> List = List.create()
5891 >>> List.num_constructors()
5892 2
5893 >>> List.constructor(0)
5894 cons
5895 >>> num_accs = List.constructor(0).arity()
5896 >>> num_accs
5897 2
5898 >>> List.accessor(0, 0)
5899 car
5900 >>> List.accessor(0, 1)
5901 cdr
5902 >>> List.constructor(1)
5903 nil
5904 >>> num_accs = List.constructor(1).arity()
5905 >>> num_accs
5906 0
5907 """
5908 if z3_debug():
5909 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5910 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5911 return FuncDeclRef(
5913 ctx=self.ctx,
5914 )
5915
5916
5918 """Datatype expressions."""
5919
5920 def sort(self):
5921 """Return the datatype sort of the datatype expression `self`."""
5922 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
5923
5924 def update_field(self, field_accessor, new_value):
5925 """Return a new datatype expression with the specified field updated.
5926
5927 Args:
5928 field_accessor: The accessor function declaration for the field to update
5929 new_value: The new value for the field
5930
5931 Returns:
5932 A new datatype expression with the field updated, other fields unchanged
5933
5934 Example:
5935 >>> Person = Datatype('Person')
5936 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
5937 >>> Person = Person.create()
5938 >>> person_age = Person.accessor(0, 1) # age accessor
5939 >>> p = Const('p', Person)
5940 >>> p2 = p.update_field(person_age, IntVal(30))
5941 """
5942 if z3_debug():
5943 _z3_assert(is_func_decl(field_accessor), "Z3 function declaration expected")
5944 _z3_assert(is_expr(new_value), "Z3 expression expected")
5945 return _to_expr_ref(
5946 Z3_datatype_update_field(self.ctx_ref(), field_accessor.ast, self.as_ast(), new_value.as_ast()),
5947 self.ctx
5948 )
5949
5950def DatatypeSort(name, params=None, ctx=None):
5951 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
5952
5953 Args:
5954 name: name of the datatype sort
5955 params: optional list/tuple of sort parameters for parametric datatypes
5956 ctx: Z3 context (optional)
5957
5958 Example:
5959 >>> # Non-parametric datatype
5960 >>> TreeRef = DatatypeSort('Tree')
5961 >>> # Parametric datatype with one parameter
5962 >>> ListIntRef = DatatypeSort('List', [IntSort()])
5963 >>> # Parametric datatype with multiple parameters
5964 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
5965 """
5966 ctx = _get_ctx(ctx)
5967 if params is None or len(params) == 0:
5968 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), 0, (Sort * 0)()), ctx)
5969 else:
5970 _params = (Sort * len(params))()
5971 for i in range(len(params)):
5972 _params[i] = params[i].ast
5973 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), len(params), _params), ctx)
5974
5975def TupleSort(name, sorts, ctx=None):
5976 """Create a named tuple sort base on a set of underlying sorts
5977 Example:
5978 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5979 """
5980 tuple = Datatype(name, ctx)
5981 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5982 tuple.declare(name, *projects)
5983 tuple = tuple.create()
5984 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5985
5986
5987def DisjointSum(name, sorts, ctx=None):
5988 """Create a named tagged union sort base on a set of underlying sorts
5989 Example:
5990 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5991 """
5992 sum = Datatype(name, ctx)
5993 for i in range(len(sorts)):
5994 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5995 sum = sum.create()
5996 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5997
5998
5999def EnumSort(name, values, ctx=None):
6000 """Return a new enumeration sort named `name` containing the given values.
6001
6002 The result is a pair (sort, list of constants).
6003 Example:
6004 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6005 """
6006 if z3_debug():
6007 _z3_assert(isinstance(name, str), "Name must be a string")
6008 _z3_assert(all([isinstance(v, str) for v in values]), "Enumeration sort values must be strings")
6009 _z3_assert(len(values) > 0, "At least one value expected")
6010 ctx = _get_ctx(ctx)
6011 num = len(values)
6012 _val_names = (Symbol * num)()
6013 for i in range(num):
6014 _val_names[i] = to_symbol(values[i], ctx)
6015 _values = (FuncDecl * num)()
6016 _testers = (FuncDecl * num)()
6017 name = to_symbol(name, ctx)
6018 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
6019 V = []
6020 for i in range(num):
6021 V.append(FuncDeclRef(_values[i], ctx))
6022 V = [a() for a in V]
6023 return S, V
6024
6025
6030
6031
6033 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6034
6035 Consider using the function `args2params` to create instances of this object.
6036 """
6037
6038 def __init__(self, ctx=None, params=None):
6039 self.ctx = _get_ctx(ctx)
6040 if params is None:
6041 self.params = Z3_mk_params(self.ctx.ref())
6042 else:
6043 self.params = params
6044 Z3_params_inc_ref(self.ctx.ref(), self.params)
6045
6046 def __deepcopy__(self, memo={}):
6047 return ParamsRef(self.ctx, self.params)
6048
6049 def __del__(self):
6050 if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
6051 Z3_params_dec_ref(self.ctx.ref(), self.params)
6052
6053 def set(self, name, val):
6054 """Set parameter name with value val."""
6055 if z3_debug():
6056 _z3_assert(isinstance(name, str), "parameter name must be a string")
6057 name_sym = to_symbol(name, self.ctx)
6058 if isinstance(val, bool):
6059 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
6060 elif _is_int(val):
6061 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
6062 elif isinstance(val, float):
6063 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
6064 elif isinstance(val, str):
6065 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
6066 else:
6067 if z3_debug():
6068 _z3_assert(False, "invalid parameter value")
6069
6070 def __repr__(self):
6071 return Z3_params_to_string(self.ctx.ref(), self.params)
6072
6073 def validate(self, ds):
6074 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
6075 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
6076
6077
6078def args2params(arguments, keywords, ctx=None):
6079 """Convert python arguments into a Z3_params object.
6080 A ':' is added to the keywords, and '_' is replaced with '-'
6081
6082 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6083 (params model true relevancy 2 elim_and true)
6084 """
6085 if z3_debug():
6086 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
6087 prev = None
6088 r = ParamsRef(ctx)
6089 for a in arguments:
6090 if prev is None:
6091 prev = a
6092 else:
6093 r.set(prev, a)
6094 prev = None
6095 for k in keywords:
6096 v = keywords[k]
6097 r.set(k, v)
6098 return r
6099
6100
6102 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6103 """
6104
6105 def __init__(self, descr, ctx=None):
6106 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
6107 self.ctx = _get_ctx(ctx)
6108 self.descr = descr
6109 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
6110
6111 def __deepcopy__(self, memo={}):
6112 return ParamsDescrsRef(self.descr, self.ctx)
6113
6114 def __del__(self):
6115 if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
6116 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
6117
6118 def size(self):
6119 """Return the size of in the parameter description `self`.
6120 """
6121 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
6122
6123 def __len__(self):
6124 """Return the size of in the parameter description `self`.
6125 """
6126 return self.size()
6127
6128 def get_name(self, i):
6129 """Return the i-th parameter name in the parameter description `self`.
6130 """
6131 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
6132
6133 def get_kind(self, n):
6134 """Return the kind of the parameter named `n`.
6135 """
6136 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6137
6138 def get_documentation(self, n):
6139 """Return the documentation string of the parameter named `n`.
6140 """
6141 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6142
6143 def __getitem__(self, arg):
6144 if _is_int(arg):
6145 return self.get_name(arg)
6146 else:
6147 return self.get_kind(arg)
6148
6149 def __repr__(self):
6150 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
6151
6152
6157
6158
6160 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6161
6162 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6163 A goal has a solution if one of its subgoals has a solution.
6164 A goal is unsatisfiable if all subgoals are unsatisfiable.
6165 """
6166
6167 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6168 if z3_debug():
6169 _z3_assert(goal is None or ctx is not None,
6170 "If goal is different from None, then ctx must be also different from None")
6171 self.ctx = _get_ctx(ctx)
6172 self.goal = goal
6173 if self.goal is None:
6174 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
6175 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
6176
6177 def __del__(self):
6178 if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
6179 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
6180
6181 def depth(self):
6182 """Return the depth of the goal `self`.
6183 The depth corresponds to the number of tactics applied to `self`.
6184
6185 >>> x, y = Ints('x y')
6186 >>> g = Goal()
6187 >>> g.add(x == 0, y >= x + 1)
6188 >>> g.depth()
6189 0
6190 >>> r = Then('simplify', 'solve-eqs')(g)
6191 >>> # r has 1 subgoal
6192 >>> len(r)
6193 1
6194 >>> r[0].depth()
6195 2
6196 """
6197 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
6198
6199 def inconsistent(self):
6200 """Return `True` if `self` contains the `False` constraints.
6201
6202 >>> x, y = Ints('x y')
6203 >>> g = Goal()
6204 >>> g.inconsistent()
6205 False
6206 >>> g.add(x == 0, x == 1)
6207 >>> g
6208 [x == 0, x == 1]
6209 >>> g.inconsistent()
6210 False
6211 >>> g2 = Tactic('propagate-values')(g)[0]
6212 >>> g2.inconsistent()
6213 True
6214 """
6215 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
6216
6217 def prec(self):
6218 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6219
6220 >>> g = Goal()
6221 >>> g.prec() == Z3_GOAL_PRECISE
6222 True
6223 >>> x, y = Ints('x y')
6224 >>> g.add(x == y + 1)
6225 >>> g.prec() == Z3_GOAL_PRECISE
6226 True
6227 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6228 >>> g2 = t(g)[0]
6229 >>> g2
6230 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6231 >>> g2.prec() == Z3_GOAL_PRECISE
6232 False
6233 >>> g2.prec() == Z3_GOAL_UNDER
6234 True
6235 """
6236 return Z3_goal_precision(self.ctx.ref(), self.goal)
6237
6238 def precision(self):
6239 """Alias for `prec()`.
6240
6241 >>> g = Goal()
6242 >>> g.precision() == Z3_GOAL_PRECISE
6243 True
6244 """
6245 return self.prec()
6246
6247 def size(self):
6248 """Return the number of constraints in the goal `self`.
6249
6250 >>> g = Goal()
6251 >>> g.size()
6252 0
6253 >>> x, y = Ints('x y')
6254 >>> g.add(x == 0, y > x)
6255 >>> g.size()
6256 2
6257 """
6258 return int(Z3_goal_size(self.ctx.ref(), self.goal))
6259
6260 def __len__(self):
6261 """Return the number of constraints in the goal `self`.
6262
6263 >>> g = Goal()
6264 >>> len(g)
6265 0
6266 >>> x, y = Ints('x y')
6267 >>> g.add(x == 0, y > x)
6268 >>> len(g)
6269 2
6270 """
6271 return self.size()
6272
6273 def get(self, i):
6274 """Return a constraint in the goal `self`.
6275
6276 >>> g = Goal()
6277 >>> x, y = Ints('x y')
6278 >>> g.add(x == 0, y > x)
6279 >>> g.get(0)
6280 x == 0
6281 >>> g.get(1)
6282 y > x
6283 """
6284 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
6285
6286 def __getitem__(self, arg):
6287 """Return a constraint in the goal `self`.
6288
6289 >>> g = Goal()
6290 >>> x, y = Ints('x y')
6291 >>> g.add(x == 0, y > x)
6292 >>> g[0]
6293 x == 0
6294 >>> g[1]
6295 y > x
6296 """
6297 if arg < 0:
6298 arg += len(self)
6299 if arg < 0 or arg >= len(self):
6300 raise IndexError
6301 return self.get(arg)
6302
6303 def assert_exprs(self, *args):
6304 """Assert constraints into the goal.
6305
6306 >>> x = Int('x')
6307 >>> g = Goal()
6308 >>> g.assert_exprs(x > 0, x < 2)
6309 >>> g
6310 [x > 0, x < 2]
6311 """
6312 args = _get_args(args)
6313 s = BoolSort(self.ctx)
6314 for arg in args:
6315 arg = s.cast(arg)
6316 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
6317
6318 def append(self, *args):
6319 """Add constraints.
6320
6321 >>> x = Int('x')
6322 >>> g = Goal()
6323 >>> g.append(x > 0, x < 2)
6324 >>> g
6325 [x > 0, x < 2]
6326 """
6327 self.assert_exprs(*args)
6328
6329 def insert(self, *args):
6330 """Add constraints.
6331
6332 >>> x = Int('x')
6333 >>> g = Goal()
6334 >>> g.insert(x > 0, x < 2)
6335 >>> g
6336 [x > 0, x < 2]
6337 """
6338 self.assert_exprs(*args)
6339
6340 def add(self, *args):
6341 """Add constraints.
6342
6343 >>> x = Int('x')
6344 >>> g = Goal()
6345 >>> g.add(x > 0, x < 2)
6346 >>> g
6347 [x > 0, x < 2]
6348 """
6349 self.assert_exprs(*args)
6350
6351 def convert_model(self, model):
6352 """Retrieve model from a satisfiable goal
6353 >>> a, b = Ints('a b')
6354 >>> g = Goal()
6355 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6356 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6357 >>> r = t(g)
6358 >>> r[0]
6359 [Or(b == 0, b == 1), Not(0 <= b)]
6360 >>> r[1]
6361 [Or(b == 0, b == 1), Not(1 <= b)]
6362 >>> # Remark: the subgoal r[0] is unsatisfiable
6363 >>> # Creating a solver for solving the second subgoal
6364 >>> s = Solver()
6365 >>> s.add(r[1])
6366 >>> s.check()
6367 sat
6368 >>> s.model()
6369 [b = 0]
6370 >>> # Model s.model() does not assign a value to `a`
6371 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6372 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6373 >>> r[1].convert_model(s.model())
6374 [b = 0, a = 1]
6375 """
6376 if z3_debug():
6377 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
6378 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
6379
6380 def __repr__(self):
6381 return obj_to_string(self)
6382
6383 def sexpr(self):
6384 """Return a textual representation of the s-expression representing the goal."""
6385 return Z3_goal_to_string(self.ctx.ref(), self.goal)
6386
6387 def dimacs(self, include_names=True):
6388 """Return a textual representation of the goal in DIMACS format."""
6389 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
6390
6391 def translate(self, target):
6392 """Copy goal `self` to context `target`.
6393
6394 >>> x = Int('x')
6395 >>> g = Goal()
6396 >>> g.add(x > 10)
6397 >>> g
6398 [x > 10]
6399 >>> c2 = Context()
6400 >>> g2 = g.translate(c2)
6401 >>> g2
6402 [x > 10]
6403 >>> g.ctx == main_ctx()
6404 True
6405 >>> g2.ctx == c2
6406 True
6407 >>> g2.ctx == main_ctx()
6408 False
6409 """
6410 if z3_debug():
6411 _z3_assert(isinstance(target, Context), "target must be a context")
6412 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
6413
6414 def __copy__(self):
6415 return self.translate(self.ctx)
6416
6417 def __deepcopy__(self, memo={}):
6418 return self.translate(self.ctx)
6419
6420 def simplify(self, *arguments, **keywords):
6421 """Return a new simplified goal.
6422
6423 This method is essentially invoking the simplify tactic.
6424
6425 >>> g = Goal()
6426 >>> x = Int('x')
6427 >>> g.add(x + 1 >= 2)
6428 >>> g
6429 [x + 1 >= 2]
6430 >>> g2 = g.simplify()
6431 >>> g2
6432 [x >= 1]
6433 >>> # g was not modified
6434 >>> g
6435 [x + 1 >= 2]
6436 """
6437 t = Tactic("simplify")
6438 return t.apply(self, *arguments, **keywords)[0]
6439
6440 def as_expr(self):
6441 """Return goal `self` as a single Z3 expression.
6442
6443 >>> x = Int('x')
6444 >>> g = Goal()
6445 >>> g.as_expr()
6446 True
6447 >>> g.add(x > 1)
6448 >>> g.as_expr()
6449 x > 1
6450 >>> g.add(x < 10)
6451 >>> g.as_expr()
6452 And(x > 1, x < 10)
6453 """
6454 sz = len(self)
6455 if sz == 0:
6456 return BoolVal(True, self.ctx)
6457 elif sz == 1:
6458 return self.get(0)
6459 else:
6460 return And([self.get(i) for i in range(len(self))], self.ctx)
6461
6462
6467
6468
6470 """A collection (vector) of ASTs."""
6471
6472 def __init__(self, v=None, ctx=None):
6473 self.vector = None
6474 if v is None:
6475 self.ctx = _get_ctx(ctx)
6476 self.vector = Z3_mk_ast_vector(self.ctx.ref())
6477 else:
6478 self.vector = v
6479 assert ctx is not None
6480 self.ctx = ctx
6481 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
6482
6483 def __del__(self):
6484 if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
6485 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
6486
6487 def __len__(self):
6488 """Return the size of the vector `self`.
6489
6490 >>> A = AstVector()
6491 >>> len(A)
6492 0
6493 >>> A.push(Int('x'))
6494 >>> A.push(Int('x'))
6495 >>> len(A)
6496 2
6497 """
6498 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
6499
6500 def __getitem__(self, i):
6501 """Return the AST at position `i`.
6502
6503 >>> A = AstVector()
6504 >>> A.push(Int('x') + 1)
6505 >>> A.push(Int('y'))
6506 >>> A[0]
6507 x + 1
6508 >>> A[1]
6509 y
6510 """
6511
6512 if isinstance(i, int):
6513 if i < 0:
6514 i += self.__len__()
6515
6516 if i >= self.__len__():
6517 raise IndexError
6518 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
6519
6520 elif isinstance(i, slice):
6521 result = []
6522 for ii in range(*i.indices(self.__len__())):
6523 result.append(_to_ast_ref(
6524 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
6525 self.ctx,
6526 ))
6527 return result
6528
6529 def __setitem__(self, i, v):
6530 """Update AST at position `i`.
6531
6532 >>> A = AstVector()
6533 >>> A.push(Int('x') + 1)
6534 >>> A.push(Int('y'))
6535 >>> A[0]
6536 x + 1
6537 >>> A[0] = Int('x')
6538 >>> A[0]
6539 x
6540 """
6541 if i < 0:
6542 i += self.__len__()
6543 if i < 0 or i >= self.__len__():
6544 raise IndexError
6545 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
6546
6547 def push(self, v):
6548 """Add `v` in the end of the vector.
6549
6550 >>> A = AstVector()
6551 >>> len(A)
6552 0
6553 >>> A.push(Int('x'))
6554 >>> len(A)
6555 1
6556 """
6557 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
6558
6559 def resize(self, sz):
6560 """Resize the vector to `sz` elements.
6561
6562 >>> A = AstVector()
6563 >>> A.resize(10)
6564 >>> len(A)
6565 10
6566 >>> for i in range(10): A[i] = Int('x')
6567 >>> A[5]
6568 x
6569 """
6570 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
6571
6572 def __contains__(self, item):
6573 """Return `True` if the vector contains `item`.
6574
6575 >>> x = Int('x')
6576 >>> A = AstVector()
6577 >>> x in A
6578 False
6579 >>> A.push(x)
6580 >>> x in A
6581 True
6582 >>> (x+1) in A
6583 False
6584 >>> A.push(x+1)
6585 >>> (x+1) in A
6586 True
6587 >>> A
6588 [x, x + 1]
6589 """
6590 for elem in self:
6591 if elem.eq(item):
6592 return True
6593 return False
6594
6595 def translate(self, other_ctx):
6596 """Copy vector `self` to context `other_ctx`.
6597
6598 >>> x = Int('x')
6599 >>> A = AstVector()
6600 >>> A.push(x)
6601 >>> c2 = Context()
6602 >>> B = A.translate(c2)
6603 >>> B
6604 [x]
6605 """
6606 return AstVector(
6607 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
6608 ctx=other_ctx,
6609 )
6610
6611 def __copy__(self):
6612 return self.translate(self.ctx)
6613
6614 def __deepcopy__(self, memo={}):
6615 return self.translate(self.ctx)
6616
6617 def __repr__(self):
6618 return obj_to_string(self)
6619
6620 def sexpr(self):
6621 """Return a textual representation of the s-expression representing the vector."""
6622 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
6623
6624
6629
6630
6632 """A mapping from ASTs to ASTs."""
6633
6634 def __init__(self, m=None, ctx=None):
6635 self.map = None
6636 if m is None:
6637 self.ctx = _get_ctx(ctx)
6638 self.map = Z3_mk_ast_map(self.ctx.ref())
6639 else:
6640 self.map = m
6641 assert ctx is not None
6642 self.ctx = ctx
6643 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6644
6645 def __deepcopy__(self, memo={}):
6646 return AstMap(self.map, self.ctx)
6647
6648 def __del__(self):
6649 if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6650 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6651
6652 def __len__(self):
6653 """Return the size of the map.
6654
6655 >>> M = AstMap()
6656 >>> len(M)
6657 0
6658 >>> x = Int('x')
6659 >>> M[x] = IntVal(1)
6660 >>> len(M)
6661 1
6662 """
6663 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6664
6665 def __contains__(self, key):
6666 """Return `True` if the map contains key `key`.
6667
6668 >>> M = AstMap()
6669 >>> x = Int('x')
6670 >>> M[x] = x + 1
6671 >>> x in M
6672 True
6673 >>> x+1 in M
6674 False
6675 """
6676 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6677
6678 def __getitem__(self, key):
6679 """Retrieve the value associated with key `key`.
6680
6681 >>> M = AstMap()
6682 >>> x = Int('x')
6683 >>> M[x] = x + 1
6684 >>> M[x]
6685 x + 1
6686 """
6687 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6688
6689 def __setitem__(self, k, v):
6690 """Add/Update key `k` with value `v`.
6691
6692 >>> M = AstMap()
6693 >>> x = Int('x')
6694 >>> M[x] = x + 1
6695 >>> len(M)
6696 1
6697 >>> M[x]
6698 x + 1
6699 >>> M[x] = IntVal(1)
6700 >>> M[x]
6701 1
6702 """
6703 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6704
6705 def __repr__(self):
6706 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6707
6708 def erase(self, k):
6709 """Remove the entry associated with key `k`.
6710
6711 >>> M = AstMap()
6712 >>> x = Int('x')
6713 >>> M[x] = x + 1
6714 >>> len(M)
6715 1
6716 >>> M.erase(x)
6717 >>> len(M)
6718 0
6719 """
6720 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6721
6722 def reset(self):
6723 """Remove all entries from the map.
6724
6725 >>> M = AstMap()
6726 >>> x = Int('x')
6727 >>> M[x] = x + 1
6728 >>> M[x+x] = IntVal(1)
6729 >>> len(M)
6730 2
6731 >>> M.reset()
6732 >>> len(M)
6733 0
6734 """
6735 Z3_ast_map_reset(self.ctx.ref(), self.map)
6736
6737 def keys(self):
6738 """Return an AstVector containing all keys in the map.
6739
6740 >>> M = AstMap()
6741 >>> x = Int('x')
6742 >>> M[x] = x + 1
6743 >>> M[x+x] = IntVal(1)
6744 >>> M.keys()
6745 [x + x, x]
6746 """
6747 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6748
6749
6754
6755
6757 """Store the value of the interpretation of a function in a particular point."""
6758
6759 def __init__(self, entry, ctx):
6760 self.entry = entry
6761 self.ctx = ctx
6762 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6763
6764 def __deepcopy__(self, memo={}):
6765 return FuncEntry(self.entry, self.ctx)
6766
6767 def __del__(self):
6768 if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6769 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6770
6771 def num_args(self):
6772 """Return the number of arguments in the given entry.
6773
6774 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6775 >>> s = Solver()
6776 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6777 >>> s.check()
6778 sat
6779 >>> m = s.model()
6780 >>> f_i = m[f]
6781 >>> f_i.num_entries()
6782 1
6783 >>> e = f_i.entry(0)
6784 >>> e.num_args()
6785 2
6786 """
6787 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6788
6789 def arg_value(self, idx):
6790 """Return the value of argument `idx`.
6791
6792 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6793 >>> s = Solver()
6794 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6795 >>> s.check()
6796 sat
6797 >>> m = s.model()
6798 >>> f_i = m[f]
6799 >>> f_i.num_entries()
6800 1
6801 >>> e = f_i.entry(0)
6802 >>> e
6803 [1, 2, 20]
6804 >>> e.num_args()
6805 2
6806 >>> e.arg_value(0)
6807 1
6808 >>> e.arg_value(1)
6809 2
6810 >>> try:
6811 ... e.arg_value(2)
6812 ... except IndexError:
6813 ... print("index error")
6814 index error
6815 """
6816 if idx >= self.num_args():
6817 raise IndexError
6818 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6819
6820 def value(self):
6821 """Return the value of the function at point `self`.
6822
6823 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6824 >>> s = Solver()
6825 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6826 >>> s.check()
6827 sat
6828 >>> m = s.model()
6829 >>> f_i = m[f]
6830 >>> f_i.num_entries()
6831 1
6832 >>> e = f_i.entry(0)
6833 >>> e
6834 [1, 2, 20]
6835 >>> e.num_args()
6836 2
6837 >>> e.value()
6838 20
6839 """
6840 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6841
6842 def as_list(self):
6843 """Return entry `self` as a Python list.
6844 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6845 >>> s = Solver()
6846 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6847 >>> s.check()
6848 sat
6849 >>> m = s.model()
6850 >>> f_i = m[f]
6851 >>> f_i.num_entries()
6852 1
6853 >>> e = f_i.entry(0)
6854 >>> e.as_list()
6855 [1, 2, 20]
6856 """
6857 args = [self.arg_value(i) for i in range(self.num_args())]
6858 args.append(self.value())
6859 return args
6860
6861 def __repr__(self):
6862 return repr(self.as_list())
6863
6864
6866 """Stores the interpretation of a function in a Z3 model."""
6867
6868 def __init__(self, f, ctx):
6869 self.f = f
6870 self.ctx = ctx
6871 if self.f is not None:
6872 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6873
6874 def __del__(self):
6875 if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6876 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6877
6878 def else_value(self):
6879 """
6880 Return the `else` value for a function interpretation.
6881 Return None if Z3 did not specify the `else` value for
6882 this object.
6883
6884 >>> f = Function('f', IntSort(), IntSort())
6885 >>> s = Solver()
6886 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6887 >>> s.check()
6888 sat
6889 >>> m = s.model()
6890 >>> m[f]
6891 [2 -> 0, else -> 1]
6892 >>> m[f].else_value()
6893 1
6894 """
6895 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6896 if r:
6897 return _to_expr_ref(r, self.ctx)
6898 else:
6899 return None
6900
6901 def num_entries(self):
6902 """Return the number of entries/points in the function interpretation `self`.
6903
6904 >>> f = Function('f', IntSort(), IntSort())
6905 >>> s = Solver()
6906 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6907 >>> s.check()
6908 sat
6909 >>> m = s.model()
6910 >>> m[f]
6911 [2 -> 0, else -> 1]
6912 >>> m[f].num_entries()
6913 1
6914 """
6915 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6916
6917 def arity(self):
6918 """Return the number of arguments for each entry in the function interpretation `self`.
6919
6920 >>> f = Function('f', IntSort(), IntSort())
6921 >>> s = Solver()
6922 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6923 >>> s.check()
6924 sat
6925 >>> m = s.model()
6926 >>> m[f].arity()
6927 1
6928 """
6929 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6930
6931 def entry(self, idx):
6932 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6933
6934 >>> f = Function('f', IntSort(), IntSort())
6935 >>> s = Solver()
6936 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6937 >>> s.check()
6938 sat
6939 >>> m = s.model()
6940 >>> m[f]
6941 [2 -> 0, else -> 1]
6942 >>> m[f].num_entries()
6943 1
6944 >>> m[f].entry(0)
6945 [2, 0]
6946 """
6947 if idx >= self.num_entries():
6948 raise IndexError
6949 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6950
6951 def translate(self, other_ctx):
6952 """Copy model 'self' to context 'other_ctx'.
6953 """
6954 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6955
6956 def __copy__(self):
6957 return self.translate(self.ctx)
6958
6959 def __deepcopy__(self, memo={}):
6960 return self.translate(self.ctx)
6961
6962 def as_list(self):
6963 """Return the function interpretation as a Python list.
6964 >>> f = Function('f', IntSort(), IntSort())
6965 >>> s = Solver()
6966 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6967 >>> s.check()
6968 sat
6969 >>> m = s.model()
6970 >>> m[f]
6971 [2 -> 0, else -> 1]
6972 >>> m[f].as_list()
6973 [[2, 0], 1]
6974 """
6975 r = [self.entry(i).as_list() for i in range(self.num_entries())]
6976 r.append(self.else_value())
6977 return r
6978
6979 def __repr__(self):
6980 return obj_to_string(self)
6981
6982
6984 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6985
6986 def __init__(self, m, ctx):
6987 assert ctx is not None
6988 self.model = m
6989 self.ctx = ctx
6990 Z3_model_inc_ref(self.ctx.ref(), self.model)
6991
6992 def __del__(self):
6993 if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
6994 Z3_model_dec_ref(self.ctx.ref(), self.model)
6995
6996 def __repr__(self):
6997 return obj_to_string(self)
6998
6999 def sexpr(self):
7000 """Return a textual representation of the s-expression representing the model."""
7001 return Z3_model_to_string(self.ctx.ref(), self.model)
7002
7003 def eval(self, t, model_completion=False):
7004 """Evaluate the expression `t` in the model `self`.
7005 If `model_completion` is enabled, then a default interpretation is automatically added
7006 for symbols that do not have an interpretation in the model `self`.
7007
7008 >>> x = Int('x')
7009 >>> s = Solver()
7010 >>> s.add(x > 0, x < 2)
7011 >>> s.check()
7012 sat
7013 >>> m = s.model()
7014 >>> m.eval(x + 1)
7015 2
7016 >>> m.eval(x == 1)
7017 True
7018 >>> y = Int('y')
7019 >>> m.eval(y + x)
7020 1 + y
7021 >>> m.eval(y)
7022 y
7023 >>> m.eval(y, model_completion=True)
7024 0
7025 >>> # Now, m contains an interpretation for y
7026 >>> m.eval(y + x)
7027 1
7028 """
7029 r = (Ast * 1)()
7030 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
7031 return _to_expr_ref(r[0], self.ctx)
7032 raise Z3Exception("failed to evaluate expression in the model")
7033
7034 def evaluate(self, t, model_completion=False):
7035 """Alias for `eval`.
7036
7037 >>> x = Int('x')
7038 >>> s = Solver()
7039 >>> s.add(x > 0, x < 2)
7040 >>> s.check()
7041 sat
7042 >>> m = s.model()
7043 >>> m.evaluate(x + 1)
7044 2
7045 >>> m.evaluate(x == 1)
7046 True
7047 >>> y = Int('y')
7048 >>> m.evaluate(y + x)
7049 1 + y
7050 >>> m.evaluate(y)
7051 y
7052 >>> m.evaluate(y, model_completion=True)
7053 0
7054 >>> # Now, m contains an interpretation for y
7055 >>> m.evaluate(y + x)
7056 1
7057 """
7058 return self.eval(t, model_completion)
7059
7060 def __len__(self):
7061 """Return the number of constant and function declarations in the model `self`.
7062
7063 >>> f = Function('f', IntSort(), IntSort())
7064 >>> x = Int('x')
7065 >>> s = Solver()
7066 >>> s.add(x > 0, f(x) != x)
7067 >>> s.check()
7068 sat
7069 >>> m = s.model()
7070 >>> len(m)
7071 2
7072 """
7073 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
7074 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
7075 return num_consts + num_funcs
7076
7077 def get_interp(self, decl):
7078 """Return the interpretation for a given declaration or constant.
7079
7080 >>> f = Function('f', IntSort(), IntSort())
7081 >>> x = Int('x')
7082 >>> s = Solver()
7083 >>> s.add(x > 0, x < 2, f(x) == 0)
7084 >>> s.check()
7085 sat
7086 >>> m = s.model()
7087 >>> m[x]
7088 1
7089 >>> m[f]
7090 [else -> 0]
7091 """
7092 if z3_debug():
7093 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
7094 if is_const(decl):
7095 decl = decl.decl()
7096 try:
7097 if decl.arity() == 0:
7098 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
7099 if _r.value is None:
7100 return None
7101 r = _to_expr_ref(_r, self.ctx)
7102 if is_as_array(r):
7103 fi = self.get_interp(get_as_array_func(r))
7104 if fi is None:
7105 return fi
7106 e = fi.else_value()
7107 if e is None:
7108 return fi
7109 if fi.arity() != 1:
7110 return fi
7111 srt = decl.range()
7112 dom = srt.domain()
7113 e = K(dom, e)
7114 i = 0
7115 sz = fi.num_entries()
7116 n = fi.arity()
7117 while i < sz:
7118 fe = fi.entry(i)
7119 e = Store(e, fe.arg_value(0), fe.value())
7120 i += 1
7121 return e
7122 else:
7123 return r
7124 else:
7125 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
7126 except Z3Exception:
7127 return None
7128
7129 def num_sorts(self):
7130 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7131
7132 >>> A = DeclareSort('A')
7133 >>> a, b = Consts('a b', A)
7134 >>> s = Solver()
7135 >>> s.add(a != b)
7136 >>> s.check()
7137 sat
7138 >>> m = s.model()
7139 >>> m.num_sorts()
7140 1
7141 """
7142 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
7143
7144 def get_sort(self, idx):
7145 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7146
7147 >>> A = DeclareSort('A')
7148 >>> B = DeclareSort('B')
7149 >>> a1, a2 = Consts('a1 a2', A)
7150 >>> b1, b2 = Consts('b1 b2', B)
7151 >>> s = Solver()
7152 >>> s.add(a1 != a2, b1 != b2)
7153 >>> s.check()
7154 sat
7155 >>> m = s.model()
7156 >>> m.num_sorts()
7157 2
7158 >>> m.get_sort(0)
7159 A
7160 >>> m.get_sort(1)
7161 B
7162 """
7163 if idx >= self.num_sorts():
7164 raise IndexError
7165 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
7166
7167 def sorts(self):
7168 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7169
7170 >>> A = DeclareSort('A')
7171 >>> B = DeclareSort('B')
7172 >>> a1, a2 = Consts('a1 a2', A)
7173 >>> b1, b2 = Consts('b1 b2', B)
7174 >>> s = Solver()
7175 >>> s.add(a1 != a2, b1 != b2)
7176 >>> s.check()
7177 sat
7178 >>> m = s.model()
7179 >>> m.sorts()
7180 [A, B]
7181 """
7182 return [self.get_sort(i) for i in range(self.num_sorts())]
7183
7184 def get_universe(self, s):
7185 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7186
7187 >>> A = DeclareSort('A')
7188 >>> a, b = Consts('a b', A)
7189 >>> s = Solver()
7190 >>> s.add(a != b)
7191 >>> s.check()
7192 sat
7193 >>> m = s.model()
7194 >>> m.get_universe(A)
7195 [A!val!0, A!val!1]
7196 """
7197 if z3_debug():
7198 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
7199 try:
7200 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
7201 except Z3Exception:
7202 return None
7203
7204 def __getitem__(self, idx):
7205 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7206 If `idx` is a declaration, then the actual interpretation is returned.
7207
7208 The elements can be retrieved using position or the actual declaration.
7209
7210 >>> f = Function('f', IntSort(), IntSort())
7211 >>> x = Int('x')
7212 >>> s = Solver()
7213 >>> s.add(x > 0, x < 2, f(x) == 0)
7214 >>> s.check()
7215 sat
7216 >>> m = s.model()
7217 >>> len(m)
7218 2
7219 >>> m[0]
7220 x
7221 >>> m[1]
7222 f
7223 >>> m[x]
7224 1
7225 >>> m[f]
7226 [else -> 0]
7227 >>> for d in m: print("%s -> %s" % (d, m[d]))
7228 x -> 1
7229 f -> [else -> 0]
7230 """
7231 if _is_int(idx):
7232 if idx < 0:
7233 idx += len(self)
7234 if idx < 0 or idx >= len(self):
7235 raise IndexError
7236 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
7237 if (idx < num_consts):
7238 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
7239 else:
7240 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
7241 if isinstance(idx, FuncDeclRef):
7242 return self.get_interp(idx)
7243 if is_const(idx):
7244 return self.get_interp(idx.decl())
7245 if isinstance(idx, SortRef):
7246 return self.get_universe(idx)
7247 if z3_debug():
7248 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7249 return None
7250
7251 def decls(self):
7252 """Return a list with all symbols that have an interpretation in the model `self`.
7253 >>> f = Function('f', IntSort(), IntSort())
7254 >>> x = Int('x')
7255 >>> s = Solver()
7256 >>> s.add(x > 0, x < 2, f(x) == 0)
7257 >>> s.check()
7258 sat
7259 >>> m = s.model()
7260 >>> m.decls()
7261 [x, f]
7262 """
7263 r = []
7264 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
7265 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
7266 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
7267 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
7268 return r
7269
7270 def update_value(self, x, value):
7271 """Update the interpretation of a constant"""
7272 if is_expr(x):
7273 x = x.decl()
7274 if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
7275 fi1 = value.f
7276 fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
7277 fi2 = FuncInterp(fi2, x.ctx)
7278 for i in range(value.num_entries()):
7279 e = value.entry(i)
7280 n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
7281 v = AstVector()
7282 for j in range(n):
7283 v.push(e.arg_value(j))
7284 val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
7285 Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
7286 return
7287 if not is_func_decl(x) or x.arity() != 0:
7288 raise Z3Exception("Expecting 0-ary function or constant expression")
7289 value = _py2expr(value)
7290 Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
7291
7292 def translate(self, target):
7293 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7294 """
7295 if z3_debug():
7296 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7297 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
7298 return ModelRef(model, target)
7299
7300 def project(self, vars, fml):
7301 """Perform model-based projection on fml with respect to vars.
7302 Assume that the model satisfies fml. Then compute a projection fml_p, such
7303 that vars do not occur free in fml_p, fml_p is true in the model and
7304 fml_p => exists vars . fml
7305 """
7306 ctx = self.ctx.ref()
7307 _vars = (Ast * len(vars))()
7308 for i in range(len(vars)):
7309 _vars[i] = vars[i].as_ast()
7310 return _to_expr_ref(Z3_qe_model_project(ctx, self.model, len(vars), _vars, fml.ast), self.ctx)
7311
7312 def project_with_witness(self, vars, fml):
7313 """Perform model-based projection, but also include realizer terms for the projected variables"""
7314 ctx = self.ctx.ref()
7315 _vars = (Ast * len(vars))()
7316 for i in range(len(vars)):
7317 _vars[i] = vars[i].as_ast()
7318 defs = AstMap()
7319 result = Z3_qe_model_project_with_witness(ctx, self.model, len(vars), _vars, fml.ast, defs.map)
7320 result = _to_expr_ref(result, self.ctx)
7321 return result, defs
7322
7323
7324 def __copy__(self):
7325 return self.translate(self.ctx)
7326
7327 def __deepcopy__(self, memo={}):
7328 return self.translate(self.ctx)
7329
7330
7331def Model(ctx=None, eval = {}):
7332 ctx = _get_ctx(ctx)
7333 mdl = ModelRef(Z3_mk_model(ctx.ref()), ctx)
7334 for k, v in eval.items():
7335 mdl.update_value(k, v)
7336 return mdl
7337
7338
7340 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7341 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7342
7343
7345 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7346 if z3_debug():
7347 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
7348 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
7349
7350
7355
7356
7358 """Statistics for `Solver.check()`."""
7359
7360 def __init__(self, stats, ctx):
7361 self.stats = stats
7362 self.ctx = ctx
7363 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
7364
7365 def __deepcopy__(self, memo={}):
7366 return Statistics(self.stats, self.ctx)
7367
7368 def __del__(self):
7369 if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
7370 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
7371
7372 def __repr__(self):
7373 if in_html_mode():
7374 out = io.StringIO()
7375 even = True
7376 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
7377 for k, v in self:
7378 if even:
7379 out.write(u('<tr style="background-color:#CFCFCF">'))
7380 even = False
7381 else:
7382 out.write(u("<tr>"))
7383 even = True
7384 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
7385 out.write(u("</table>"))
7386 return out.getvalue()
7387 else:
7388 return Z3_stats_to_string(self.ctx.ref(), self.stats)
7389
7390 def __len__(self):
7391 """Return the number of statistical counters.
7392
7393 >>> x = Int('x')
7394 >>> s = Then('simplify', 'nlsat').solver()
7395 >>> s.add(x > 0)
7396 >>> s.check()
7397 sat
7398 >>> st = s.statistics()
7399 >>> len(st) > 0
7400 True
7401 """
7402 return int(Z3_stats_size(self.ctx.ref(), self.stats))
7403
7404 def __getitem__(self, idx):
7405 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7406
7407 >>> x = Int('x')
7408 >>> s = Then('simplify', 'nlsat').solver()
7409 >>> s.add(x > 0)
7410 >>> s.check()
7411 sat
7412 >>> st = s.statistics()
7413 >>> len(st) > 0
7414 True
7415 >>> st[0]
7416 ('nlsat propagations', 2)
7417 >>> st[1]
7418 ('nlsat restarts', 1)
7419 """
7420 if idx >= len(self):
7421 raise IndexError
7422 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7423 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7424 else:
7425 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7426 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
7427
7428 def keys(self):
7429 """Return the list of statistical counters.
7430
7431 >>> x = Int('x')
7432 >>> s = Then('simplify', 'nlsat').solver()
7433 >>> s.add(x > 0)
7434 >>> s.check()
7435 sat
7436 >>> st = s.statistics()
7437 """
7438 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
7439
7440 def get_key_value(self, key):
7441 """Return the value of a particular statistical counter.
7442
7443 >>> x = Int('x')
7444 >>> s = Then('simplify', 'nlsat').solver()
7445 >>> s.add(x > 0)
7446 >>> s.check()
7447 sat
7448 >>> st = s.statistics()
7449 >>> st.get_key_value('nlsat propagations')
7450 2
7451 """
7452 for idx in range(len(self)):
7453 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
7454 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7455 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7456 else:
7457 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7458 raise Z3Exception("unknown key")
7459
7460 def __getattr__(self, name):
7461 """Access the value of statistical using attributes.
7462
7463 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7464 we should use '_' (e.g., 'nlsat_propagations').
7465
7466 >>> x = Int('x')
7467 >>> s = Then('simplify', 'nlsat').solver()
7468 >>> s.add(x > 0)
7469 >>> s.check()
7470 sat
7471 >>> st = s.statistics()
7472 >>> st.nlsat_propagations
7473 2
7474 >>> st.nlsat_stages
7475 2
7476 """
7477 key = name.replace("_", " ")
7478 try:
7479 return self.get_key_value(key)
7480 except Z3Exception:
7481 raise AttributeError
7482
7483
7488
7489
7491 """Represents the result of a satisfiability check: sat, unsat, unknown.
7492
7493 >>> s = Solver()
7494 >>> s.check()
7495 sat
7496 >>> r = s.check()
7497 >>> isinstance(r, CheckSatResult)
7498 True
7499 """
7500
7501 def __init__(self, r):
7502 self.r = r
7503
7504 def __deepcopy__(self, memo={}):
7505 return CheckSatResult(self.r)
7506
7507 def __eq__(self, other):
7508 return isinstance(other, CheckSatResult) and self.r == other.r
7509
7510 def __ne__(self, other):
7511 return not self.__eq__(other)
7512
7513 def __repr__(self):
7514 if in_html_mode():
7515 if self.r == Z3_L_TRUE:
7516 return "<b>sat</b>"
7517 elif self.r == Z3_L_FALSE:
7518 return "<b>unsat</b>"
7519 else:
7520 return "<b>unknown</b>"
7521 else:
7522 if self.r == Z3_L_TRUE:
7523 return "sat"
7524 elif self.r == Z3_L_FALSE:
7525 return "unsat"
7526 else:
7527 return "unknown"
7528
7529 def _repr_html_(self):
7530 in_html = in_html_mode()
7531 set_html_mode(True)
7532 res = repr(self)
7533 set_html_mode(in_html)
7534 return res
7535
7536
7537sat = CheckSatResult(Z3_L_TRUE)
7538unsat = CheckSatResult(Z3_L_FALSE)
7539unknown = CheckSatResult(Z3_L_UNDEF)
7540
7541
7543 """
7544 Solver API provides methods for implementing the main SMT 2.0 commands:
7545 push, pop, check, get-model, etc.
7546 """
7547
7548 def __init__(self, solver=None, ctx=None, logFile=None):
7549 assert solver is None or ctx is not None
7550 self.ctx = _get_ctx(ctx)
7551 self.backtrack_level = 4000000000
7552 self.solver = None
7553 if solver is None:
7554 self.solver = Z3_mk_solver(self.ctx.ref())
7555 else:
7556 self.solver = solver
7557 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
7558 if logFile is not None:
7559 self.set("smtlib2_log", logFile)
7560
7561 def __del__(self):
7562 if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
7563 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
7564
7565 def __enter__(self):
7566 self.push()
7567 return self
7568
7569 def __exit__(self, *exc_info):
7570 self.pop()
7571
7572 def set(self, *args, **keys):
7573 """Set a configuration option.
7574 The method `help()` return a string containing all available options.
7575
7576 >>> s = Solver()
7577 >>> # The option MBQI can be set using three different approaches.
7578 >>> s.set(mbqi=True)
7579 >>> s.set('MBQI', True)
7580 >>> s.set(':mbqi', True)
7581 """
7582 p = args2params(args, keys, self.ctx)
7583 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
7584
7585 def push(self):
7586 """Create a backtracking point.
7587
7588 >>> x = Int('x')
7589 >>> s = Solver()
7590 >>> s.add(x > 0)
7591 >>> s
7592 [x > 0]
7593 >>> s.push()
7594 >>> s.add(x < 1)
7595 >>> s
7596 [x > 0, x < 1]
7597 >>> s.check()
7598 unsat
7599 >>> s.pop()
7600 >>> s.check()
7601 sat
7602 >>> s
7603 [x > 0]
7604 """
7605 Z3_solver_push(self.ctx.ref(), self.solver)
7606
7607 def pop(self, num=1):
7608 """Backtrack \\c num backtracking points.
7609
7610 >>> x = Int('x')
7611 >>> s = Solver()
7612 >>> s.add(x > 0)
7613 >>> s
7614 [x > 0]
7615 >>> s.push()
7616 >>> s.add(x < 1)
7617 >>> s
7618 [x > 0, x < 1]
7619 >>> s.check()
7620 unsat
7621 >>> s.pop()
7622 >>> s.check()
7623 sat
7624 >>> s
7625 [x > 0]
7626 """
7627 Z3_solver_pop(self.ctx.ref(), self.solver, num)
7628
7629 def num_scopes(self):
7630 """Return the current number of backtracking points.
7631
7632 >>> s = Solver()
7633 >>> s.num_scopes()
7634 0
7635 >>> s.push()
7636 >>> s.num_scopes()
7637 1
7638 >>> s.push()
7639 >>> s.num_scopes()
7640 2
7641 >>> s.pop()
7642 >>> s.num_scopes()
7643 1
7644 """
7645 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
7646
7647 def reset(self):
7648 """Remove all asserted constraints and backtracking points created using `push()`.
7649
7650 >>> x = Int('x')
7651 >>> s = Solver()
7652 >>> s.add(x > 0)
7653 >>> s
7654 [x > 0]
7655 >>> s.reset()
7656 >>> s
7657 []
7658 """
7659 Z3_solver_reset(self.ctx.ref(), self.solver)
7660
7661 def assert_exprs(self, *args):
7662 """Assert constraints into the solver.
7663
7664 >>> x = Int('x')
7665 >>> s = Solver()
7666 >>> s.assert_exprs(x > 0, x < 2)
7667 >>> s
7668 [x > 0, x < 2]
7669 """
7670 args = _get_args(args)
7671 s = BoolSort(self.ctx)
7672 for arg in args:
7673 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7674 for f in arg:
7675 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7676 else:
7677 arg = s.cast(arg)
7678 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7679
7680 def add(self, *args):
7681 """Assert constraints into the solver.
7682
7683 >>> x = Int('x')
7684 >>> s = Solver()
7685 >>> s.add(x > 0, x < 2)
7686 >>> s
7687 [x > 0, x < 2]
7688 """
7689 self.assert_exprs(*args)
7690
7691 def __iadd__(self, fml):
7692 self.add(fml)
7693 return self
7694
7695 def append(self, *args):
7696 """Assert constraints into the solver.
7697
7698 >>> x = Int('x')
7699 >>> s = Solver()
7700 >>> s.append(x > 0, x < 2)
7701 >>> s
7702 [x > 0, x < 2]
7703 """
7704 self.assert_exprs(*args)
7705
7706 def insert(self, *args):
7707 """Assert constraints into the solver.
7708
7709 >>> x = Int('x')
7710 >>> s = Solver()
7711 >>> s.insert(x > 0, x < 2)
7712 >>> s
7713 [x > 0, x < 2]
7714 """
7715 self.assert_exprs(*args)
7716
7717 def assert_and_track(self, a, p):
7718 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7719
7720 If `p` is a string, it will be automatically converted into a Boolean constant.
7721
7722 >>> x = Int('x')
7723 >>> p3 = Bool('p3')
7724 >>> s = Solver()
7725 >>> s.set(unsat_core=True)
7726 >>> s.assert_and_track(x > 0, 'p1')
7727 >>> s.assert_and_track(x != 1, 'p2')
7728 >>> s.assert_and_track(x < 0, p3)
7729 >>> print(s.check())
7730 unsat
7731 >>> c = s.unsat_core()
7732 >>> len(c)
7733 2
7734 >>> Bool('p1') in c
7735 True
7736 >>> Bool('p2') in c
7737 False
7738 >>> p3 in c
7739 True
7740 """
7741 if isinstance(p, str):
7742 p = Bool(p, self.ctx)
7743 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7744 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7745 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7746
7747 def check(self, *assumptions):
7748 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7749
7750 >>> x = Int('x')
7751 >>> s = Solver()
7752 >>> s.check()
7753 sat
7754 >>> s.add(x > 0, x < 2)
7755 >>> s.check()
7756 sat
7757 >>> s.model().eval(x)
7758 1
7759 >>> s.add(x < 1)
7760 >>> s.check()
7761 unsat
7762 >>> s.reset()
7763 >>> s.add(2**x == 4)
7764 >>> s.check()
7765 sat
7766 """
7767 s = BoolSort(self.ctx)
7768 assumptions = _get_args(assumptions)
7769 num = len(assumptions)
7770 _assumptions = (Ast * num)()
7771 for i in range(num):
7772 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7773 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7774 return CheckSatResult(r)
7775
7776 def model(self):
7777 """Return a model for the last `check()`.
7778
7779 This function raises an exception if
7780 a model is not available (e.g., last `check()` returned unsat).
7781
7782 >>> s = Solver()
7783 >>> a = Int('a')
7784 >>> s.add(a + 2 == 0)
7785 >>> s.check()
7786 sat
7787 >>> s.model()
7788 [a = -2]
7789 """
7790 try:
7791 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7792 except Z3Exception:
7793 raise Z3Exception("model is not available")
7794
7795 def import_model_converter(self, other):
7796 """Import model converter from other into the current solver"""
7797 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7798
7799 def interrupt(self):
7800 """Interrupt the execution of the solver object.
7801 Remarks: This ensures that the interrupt applies only
7802 to the given solver object and it applies only if it is running.
7803 """
7804 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7805
7806 def unsat_core(self):
7807 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7808
7809 These are the assumptions Z3 used in the unsatisfiability proof.
7810 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7811 They may be also used to "retract" assumptions. Note that, assumptions are not really
7812 "soft constraints", but they can be used to implement them.
7813
7814 >>> p1, p2, p3 = Bools('p1 p2 p3')
7815 >>> x, y = Ints('x y')
7816 >>> s = Solver()
7817 >>> s.add(Implies(p1, x > 0))
7818 >>> s.add(Implies(p2, y > x))
7819 >>> s.add(Implies(p2, y < 1))
7820 >>> s.add(Implies(p3, y > -3))
7821 >>> s.check(p1, p2, p3)
7822 unsat
7823 >>> core = s.unsat_core()
7824 >>> len(core)
7825 2
7826 >>> p1 in core
7827 True
7828 >>> p2 in core
7829 True
7830 >>> p3 in core
7831 False
7832 >>> # "Retracting" p2
7833 >>> s.check(p1, p3)
7834 sat
7835 """
7836 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7837
7838 def consequences(self, assumptions, variables):
7839 """Determine fixed values for the variables based on the solver state and assumptions.
7840 >>> s = Solver()
7841 >>> a, b, c, d = Bools('a b c d')
7842 >>> s.add(Implies(a,b), Implies(b, c))
7843 >>> s.consequences([a],[b,c,d])
7844 (sat, [Implies(a, b), Implies(a, c)])
7845 >>> s.consequences([Not(c),d],[a,b,c,d])
7846 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7847 """
7848 if isinstance(assumptions, list):
7849 _asms = AstVector(None, self.ctx)
7850 for a in assumptions:
7851 _asms.push(a)
7852 assumptions = _asms
7853 if isinstance(variables, list):
7854 _vars = AstVector(None, self.ctx)
7855 for a in variables:
7856 _vars.push(a)
7857 variables = _vars
7858 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7859 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7860 consequences = AstVector(None, self.ctx)
7861 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7862 variables.vector, consequences.vector)
7863 sz = len(consequences)
7864 consequences = [consequences[i] for i in range(sz)]
7865 return CheckSatResult(r), consequences
7866
7867 def from_file(self, filename):
7868 """Parse assertions from a file"""
7869 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7870
7871 def from_string(self, s):
7872 """Parse assertions from a string"""
7873 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7874
7875 def cube(self, vars=None):
7876 """Get set of cubes
7877 The method takes an optional set of variables that restrict which
7878 variables may be used as a starting point for cubing.
7879 If vars is not None, then the first case split is based on a variable in
7880 this set.
7881 """
7882 self.cube_vs = AstVector(None, self.ctx)
7883 if vars is not None:
7884 for v in vars:
7885 self.cube_vs.push(v)
7886 while True:
7887 lvl = self.backtrack_level
7888 self.backtrack_level = 4000000000
7889 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7890 if (len(r) == 1 and is_false(r[0])):
7891 return
7892 yield r
7893 if (len(r) == 0):
7894 return
7895
7896 def cube_vars(self):
7897 """Access the set of variables that were touched by the most recently generated cube.
7898 This set of variables can be used as a starting point for additional cubes.
7899 The idea is that variables that appear in clauses that are reduced by the most recent
7900 cube are likely more useful to cube on."""
7901 return self.cube_vs
7902
7903 def congruence_root(self, t):
7904 """Retrieve congruence closure root of the term t relative to the current search state
7905 The function primarily works for SimpleSolver. Terms and variables that are
7906 eliminated during pre-processing are not visible to the congruence closure.
7907 """
7908 t = _py2expr(t, self.ctx)
7909 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
7910
7911 def congruence_next(self, t):
7912 """Retrieve congruence closure sibling of the term t relative to the current search state
7913 The function primarily works for SimpleSolver. Terms and variables that are
7914 eliminated during pre-processing are not visible to the congruence closure.
7915 """
7916 t = _py2expr(t, self.ctx)
7917 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
7918
7919 def congruence_explain(self, a, b):
7920 """Explain congruence of a and b relative to the current search state"""
7921 a = _py2expr(a, self.ctx)
7922 b = _py2expr(b, self.ctx)
7923 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
7924
7925
7926 def solve_for(self, ts):
7927 """Retrieve a solution for t relative to linear equations maintained in the current state."""
7928 vars = AstVector(ctx=self.ctx);
7929 terms = AstVector(ctx=self.ctx);
7930 guards = AstVector(ctx=self.ctx);
7931 for t in ts:
7932 t = _py2expr(t, self.ctx)
7933 vars.push(t)
7934 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
7935 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
7936
7937
7938 def proof(self):
7939 """Return a proof for the last `check()`. Proof construction must be enabled."""
7940 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7941
7942 def assertions(self):
7943 """Return an AST vector containing all added constraints.
7944
7945 >>> s = Solver()
7946 >>> s.assertions()
7947 []
7948 >>> a = Int('a')
7949 >>> s.add(a > 0)
7950 >>> s.add(a < 10)
7951 >>> s.assertions()
7952 [a > 0, a < 10]
7953 """
7954 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7955
7956 def units(self):
7957 """Return an AST vector containing all currently inferred units.
7958 """
7959 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7960
7961 def non_units(self):
7962 """Return an AST vector containing all atomic formulas in solver state that are not units.
7963 """
7964 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7965
7966 def trail_levels(self):
7967 """Return trail and decision levels of the solver state after a check() call.
7968 """
7969 trail = self.trail()
7970 levels = (ctypes.c_uint * len(trail))()
7971 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7972 return trail, levels
7973
7974 def set_initial_value(self, var, value):
7975 """initialize the solver's state by setting the initial value of var to value
7976 """
7977 s = var.sort()
7978 value = s.cast(value)
7979 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
7980
7981 def trail(self):
7982 """Return trail of the solver state after a check() call.
7983 """
7984 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7985
7986 def statistics(self):
7987 """Return statistics for the last `check()`.
7988
7989 >>> s = SimpleSolver()
7990 >>> x = Int('x')
7991 >>> s.add(x > 0)
7992 >>> s.check()
7993 sat
7994 >>> st = s.statistics()
7995 >>> st.get_key_value('final checks')
7996 1
7997 >>> len(st) > 0
7998 True
7999 >>> st[0] != 0
8000 True
8001 """
8002 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8003
8004 def reason_unknown(self):
8005 """Return a string describing why the last `check()` returned `unknown`.
8006
8007 >>> x = Int('x')
8008 >>> s = SimpleSolver()
8009 >>> s.add(x == 2**x)
8010 >>> s.check()
8011 unknown
8012 >>> s.reason_unknown()
8013 '(incomplete (theory arithmetic))'
8014 """
8015 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8016
8017 def help(self):
8018 """Display a string describing all available options."""
8019 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8020
8021 def param_descrs(self):
8022 """Return the parameter description set."""
8023 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8024
8025 def __repr__(self):
8026 """Return a formatted string with all added constraints."""
8027 return obj_to_string(self)
8028
8029 def translate(self, target):
8030 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8031
8032 >>> c1 = Context()
8033 >>> c2 = Context()
8034 >>> s1 = Solver(ctx=c1)
8035 >>> s2 = s1.translate(c2)
8036 """
8037 if z3_debug():
8038 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8039 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8040 return Solver(solver, target)
8041
8042 def __copy__(self):
8043 return self.translate(self.ctx)
8044
8045 def __deepcopy__(self, memo={}):
8046 return self.translate(self.ctx)
8047
8048 def sexpr(self):
8049 """Return a formatted string (in Lisp-like format) with all added constraints.
8050 """
8051 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8052
8053 def dimacs(self, include_names=True):
8054 """Return a textual representation of the solver in DIMACS format."""
8055 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8056
8057 def to_smt2(self):
8058 """return SMTLIB2 formatted benchmark for solver's assertions"""
8059 es = self.assertions()
8060 sz = len(es)
8061 sz1 = sz
8062 if sz1 > 0:
8063 sz1 -= 1
8064 v = (Ast * sz1)()
8065 for i in range(sz1):
8066 v[i] = es[i].as_ast()
8067 if sz > 0:
8068 e = es[sz1].as_ast()
8069 else:
8070 e = BoolVal(True, self.ctx).as_ast()
8071 return Z3_benchmark_to_smtlib_string(
8072 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8073 )
8074
8075 def solutions(self, t):
8076 """Returns an iterator over solutions that satisfy the constraints.
8077
8078 The parameter `t` is an expression whose values should be returned.
8079
8080 >>> s = Solver()
8081 >>> x, y, z = Ints("x y z")
8082 >>> s.add(x * x == 4)
8083 >>> print(list(s.solutions(x)))
8084 [-2, 2]
8085 >>> s.reset()
8086 >>> s.add(x >= 0, x < 10)
8087 >>> print(list(s.solutions(x)))
8088 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8089 >>> s.reset()
8090 >>> s.add(x >= 0, y < 10, y == 2*x)
8091 >>> print(list(s.solutions([x, y])))
8092 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8093 """
8094 s = Solver()
8095 s.add(self.assertions())
8096 t = _get_args(t)
8097 if isinstance(t, (list, tuple)):
8098 while s.check() == sat:
8099 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8100 yield result
8101 s.add(Or(t_ != result_ for t_, result_ in zip(t, result)))
8102 else:
8103 while s.check() == sat:
8104 result = s.model().eval(t, model_completion=True)
8105 yield result
8106 s.add(t != result)
8107
8108
8109def SolverFor(logic, ctx=None, logFile=None):
8110 """Create a solver customized for the given logic.
8111
8112 The parameter `logic` is a string. It should be contains
8113 the name of a SMT-LIB logic.
8114 See http://www.smtlib.org/ for the name of all available logics.
8115
8116 >>> s = SolverFor("QF_LIA")
8117 >>> x = Int('x')
8118 >>> s.add(x > 0)
8119 >>> s.add(x < 2)
8120 >>> s.check()
8121 sat
8122 >>> s.model()
8123 [x = 1]
8124 """
8125 ctx = _get_ctx(ctx)
8126 logic = to_symbol(logic)
8127 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8128
8129
8130def SimpleSolver(ctx=None, logFile=None):
8131 """Return a simple general purpose solver with limited amount of preprocessing.
8132
8133 >>> s = SimpleSolver()
8134 >>> x = Int('x')
8135 >>> s.add(x > 0)
8136 >>> s.check()
8137 sat
8138 """
8139 ctx = _get_ctx(ctx)
8140 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8141
8142#########################################
8143#
8144# Fixedpoint
8145#
8146#########################################
8147
8148
8149class Fixedpoint(Z3PPObject):
8150 """Fixedpoint API provides methods for solving with recursive predicates"""
8151
8152 def __init__(self, fixedpoint=None, ctx=None):
8153 assert fixedpoint is None or ctx is not None
8154 self.ctx = _get_ctx(ctx)
8155 self.fixedpoint = None
8156 if fixedpoint is None:
8157 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8158 else:
8159 self.fixedpoint = fixedpoint
8160 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8161 self.vars = []
8162
8163 def __deepcopy__(self, memo={}):
8164 return FixedPoint(self.fixedpoint, self.ctx)
8165
8166 def __del__(self):
8167 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8168 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8169
8170 def set(self, *args, **keys):
8171 """Set a configuration option. The method `help()` return a string containing all available options.
8172 """
8173 p = args2params(args, keys, self.ctx)
8174 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8175
8176 def help(self):
8177 """Display a string describing all available options."""
8178 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8179
8180 def param_descrs(self):
8181 """Return the parameter description set."""
8182 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8183
8184 def assert_exprs(self, *args):
8185 """Assert constraints as background axioms for the fixedpoint solver."""
8186 args = _get_args(args)
8187 s = BoolSort(self.ctx)
8188 for arg in args:
8189 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8190 for f in arg:
8191 f = self.abstract(f)
8192 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8193 else:
8194 arg = s.cast(arg)
8195 arg = self.abstract(arg)
8196 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8197
8198 def add(self, *args):
8199 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8200 self.assert_exprs(*args)
8201
8202 def __iadd__(self, fml):
8203 self.add(fml)
8204 return self
8205
8206 def append(self, *args):
8207 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8208 self.assert_exprs(*args)
8209
8210 def insert(self, *args):
8211 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8212 self.assert_exprs(*args)
8213
8214 def add_rule(self, head, body=None, name=None):
8215 """Assert rules defining recursive predicates to the fixedpoint solver.
8216 >>> a = Bool('a')
8217 >>> b = Bool('b')
8218 >>> s = Fixedpoint()
8219 >>> s.register_relation(a.decl())
8220 >>> s.register_relation(b.decl())
8221 >>> s.fact(a)
8222 >>> s.rule(b, a)
8223 >>> s.query(b)
8224 sat
8225 """
8226 if name is None:
8227 name = ""
8228 name = to_symbol(name, self.ctx)
8229 if body is None:
8230 head = self.abstract(head)
8231 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8232 else:
8233 body = _get_args(body)
8234 f = self.abstract(Implies(And(body, self.ctx), head))
8235 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8236
8237 def rule(self, head, body=None, name=None):
8238 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8239 self.add_rule(head, body, name)
8240
8241 def fact(self, head, name=None):
8242 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8243 self.add_rule(head, None, name)
8244
8245 def query(self, *query):
8246 """Query the fixedpoint engine whether formula is derivable.
8247 You can also pass an tuple or list of recursive predicates.
8248 """
8249 query = _get_args(query)
8250 sz = len(query)
8251 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8252 _decls = (FuncDecl * sz)()
8253 i = 0
8254 for q in query:
8255 _decls[i] = q.ast
8256 i = i + 1
8257 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8258 else:
8259 if sz == 1:
8260 query = query[0]
8261 else:
8262 query = And(query, self.ctx)
8263 query = self.abstract(query, False)
8264 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8265 return CheckSatResult(r)
8266
8267 def query_from_lvl(self, lvl, *query):
8268 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8269 """
8270 query = _get_args(query)
8271 sz = len(query)
8272 if sz >= 1 and isinstance(query[0], FuncDecl):
8273 _z3_assert(False, "unsupported")
8274 else:
8275 if sz == 1:
8276 query = query[0]
8277 else:
8278 query = And(query)
8279 query = self.abstract(query, False)
8280 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8281 return CheckSatResult(r)
8282
8283 def update_rule(self, head, body, name):
8284 """update rule"""
8285 if name is None:
8286 name = ""
8287 name = to_symbol(name, self.ctx)
8288 body = _get_args(body)
8289 f = self.abstract(Implies(And(body, self.ctx), head))
8290 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8291
8292 def get_answer(self):
8293 """Retrieve answer from last query call."""
8294 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8295 return _to_expr_ref(r, self.ctx)
8296
8297 def get_ground_sat_answer(self):
8298 """Retrieve a ground cex from last query call."""
8299 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8300 return _to_expr_ref(r, self.ctx)
8301
8302 def get_rules_along_trace(self):
8303 """retrieve rules along the counterexample trace"""
8304 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8305
8306 def get_rule_names_along_trace(self):
8307 """retrieve rule names along the counterexample trace"""
8308 # this is a hack as I don't know how to return a list of symbols from C++;
8309 # obtain names as a single string separated by semicolons
8310 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8311 # split into individual names
8312 return names.split(";")
8313
8314 def get_num_levels(self, predicate):
8315 """Retrieve number of levels used for predicate in PDR engine"""
8316 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8317
8318 def get_cover_delta(self, level, predicate):
8319 """Retrieve properties known about predicate for the level'th unfolding.
8320 -1 is treated as the limit (infinity)
8321 """
8322 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8323 return _to_expr_ref(r, self.ctx)
8324
8325 def add_cover(self, level, predicate, property):
8326 """Add property to predicate for the level'th unfolding.
8327 -1 is treated as infinity (infinity)
8328 """
8329 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8330
8331 def register_relation(self, *relations):
8332 """Register relation as recursive"""
8333 relations = _get_args(relations)
8334 for f in relations:
8335 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8336
8337 def set_predicate_representation(self, f, *representations):
8338 """Control how relation is represented"""
8339 representations = _get_args(representations)
8340 representations = [to_symbol(s) for s in representations]
8341 sz = len(representations)
8342 args = (Symbol * sz)()
8343 for i in range(sz):
8344 args[i] = representations[i]
8345 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8346
8347 def parse_string(self, s):
8348 """Parse rules and queries from a string"""
8349 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8350
8351 def parse_file(self, f):
8352 """Parse rules and queries from a file"""
8353 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8354
8355 def get_rules(self):
8356 """retrieve rules that have been added to fixedpoint context"""
8357 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8358
8359 def get_assertions(self):
8360 """retrieve assertions that have been added to fixedpoint context"""
8361 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8362
8363 def __repr__(self):
8364 """Return a formatted string with all added rules and constraints."""
8365 return self.sexpr()
8366
8367 def sexpr(self):
8368 """Return a formatted string (in Lisp-like format) with all added constraints.
8369 We say the string is in s-expression format.
8370 """
8371 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8372
8373 def to_string(self, queries):
8374 """Return a formatted string (in Lisp-like format) with all added constraints.
8375 We say the string is in s-expression format.
8376 Include also queries.
8377 """
8378 args, len = _to_ast_array(queries)
8379 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8380
8381 def statistics(self):
8382 """Return statistics for the last `query()`.
8383 """
8384 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8385
8386 def reason_unknown(self):
8387 """Return a string describing why the last `query()` returned `unknown`.
8388 """
8389 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8390
8391 def declare_var(self, *vars):
8392 """Add variable or several variables.
8393 The added variable or variables will be bound in the rules
8394 and queries
8395 """
8396 vars = _get_args(vars)
8397 for v in vars:
8398 self.vars += [v]
8399
8400 def abstract(self, fml, is_forall=True):
8401 if self.vars == []:
8402 return fml
8403 if is_forall:
8404 return ForAll(self.vars, fml)
8405 else:
8406 return Exists(self.vars, fml)
8407
8408
8409#########################################
8410#
8411# Finite domains
8412#
8413#########################################
8414
8415class FiniteDomainSortRef(SortRef):
8416 """Finite domain sort."""
8417
8418 def size(self):
8419 """Return the size of the finite domain sort"""
8420 r = (ctypes.c_ulonglong * 1)()
8421 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8422 return r[0]
8423 else:
8424 raise Z3Exception("Failed to retrieve finite domain sort size")
8425
8426
8427def FiniteDomainSort(name, sz, ctx=None):
8428 """Create a named finite domain sort of a given size sz"""
8429 if not isinstance(name, Symbol):
8430 name = to_symbol(name)
8431 ctx = _get_ctx(ctx)
8432 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8433
8434
8435def is_finite_domain_sort(s):
8436 """Return True if `s` is a Z3 finite-domain sort.
8437
8438 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8439 True
8440 >>> is_finite_domain_sort(IntSort())
8441 False
8442 """
8443 return isinstance(s, FiniteDomainSortRef)
8444
8445
8446class FiniteDomainRef(ExprRef):
8447 """Finite-domain expressions."""
8448
8449 def sort(self):
8450 """Return the sort of the finite-domain expression `self`."""
8451 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8452
8453 def as_string(self):
8454 """Return a Z3 floating point expression as a Python string."""
8455 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8456
8457
8458def is_finite_domain(a):
8459 """Return `True` if `a` is a Z3 finite-domain expression.
8460
8461 >>> s = FiniteDomainSort('S', 100)
8462 >>> b = Const('b', s)
8463 >>> is_finite_domain(b)
8464 True
8465 >>> is_finite_domain(Int('x'))
8466 False
8467 """
8468 return isinstance(a, FiniteDomainRef)
8469
8470
8471class FiniteDomainNumRef(FiniteDomainRef):
8472 """Integer values."""
8473
8474 def as_long(self):
8475 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8476
8477 >>> s = FiniteDomainSort('S', 100)
8478 >>> v = FiniteDomainVal(3, s)
8479 >>> v
8480 3
8481 >>> v.as_long() + 1
8482 4
8483 """
8484 return int(self.as_string())
8485
8486 def as_string(self):
8487 """Return a Z3 finite-domain numeral as a Python string.
8488
8489 >>> s = FiniteDomainSort('S', 100)
8490 >>> v = FiniteDomainVal(42, s)
8491 >>> v.as_string()
8492 '42'
8493 """
8494 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8495
8496
8497def FiniteDomainVal(val, sort, ctx=None):
8498 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8499
8500 >>> s = FiniteDomainSort('S', 256)
8501 >>> FiniteDomainVal(255, s)
8502 255
8503 >>> FiniteDomainVal('100', s)
8504 100
8505 """
8506 if z3_debug():
8507 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8508 ctx = sort.ctx
8509 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8510
8511
8512def is_finite_domain_value(a):
8513 """Return `True` if `a` is a Z3 finite-domain value.
8514
8515 >>> s = FiniteDomainSort('S', 100)
8516 >>> b = Const('b', s)
8517 >>> is_finite_domain_value(b)
8518 False
8519 >>> b = FiniteDomainVal(10, s)
8520 >>> b
8521 10
8522 >>> is_finite_domain_value(b)
8523 True
8524 """
8525 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8526
8527
8528#########################################
8529#
8530# Optimize
8531#
8532#########################################
8533
8534class OptimizeObjective:
8535 def __init__(self, opt, value, is_max):
8536 self._opt = opt
8537 self._value = value
8538 self._is_max = is_max
8539
8540 def lower(self):
8541 opt = self._opt
8542 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8543
8544 def upper(self):
8545 opt = self._opt
8546 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8547
8548 def lower_values(self):
8549 opt = self._opt
8550 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8551
8552 def upper_values(self):
8553 opt = self._opt
8554 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8555
8556 def value(self):
8557 if self._is_max:
8558 return self.upper()
8559 else:
8560 return self.lower()
8561
8562 def __str__(self):
8563 return "%s:%s" % (self._value, self._is_max)
8564
8565
8566_on_models = {}
8567
8568
8569def _global_on_model(ctx):
8570 (fn, mdl) = _on_models[ctx]
8571 fn(mdl)
8572
8573
8574_on_model_eh = on_model_eh_type(_global_on_model)
8575
8576
8577class Optimize(Z3PPObject):
8578 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8579
8580 def __init__(self, optimize=None, ctx=None):
8581 self.ctx = _get_ctx(ctx)
8582 if optimize is None:
8583 self.optimize = Z3_mk_optimize(self.ctx.ref())
8584 else:
8585 self.optimize = optimize
8586 self._on_models_id = None
8587 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8588
8589 def __copy__(self):
8590 return self.translate(self.ctx)
8591
8592 def __deepcopy__(self, memo={}):
8593 return self.translate(self.ctx)
8594
8595 def __del__(self):
8596 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8597 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8598 if self._on_models_id is not None:
8599 del _on_models[self._on_models_id]
8600
8601 def __enter__(self):
8602 self.push()
8603 return self
8604
8605 def __exit__(self, *exc_info):
8606 self.pop()
8607
8608 def set(self, *args, **keys):
8609 """Set a configuration option.
8610 The method `help()` return a string containing all available options.
8611 """
8612 p = args2params(args, keys, self.ctx)
8613 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8614
8615 def help(self):
8616 """Display a string describing all available options."""
8617 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8618
8619 def param_descrs(self):
8620 """Return the parameter description set."""
8621 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8622
8623 def assert_exprs(self, *args):
8624 """Assert constraints as background axioms for the optimize solver."""
8625 args = _get_args(args)
8626 s = BoolSort(self.ctx)
8627 for arg in args:
8628 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8629 for f in arg:
8630 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8631 else:
8632 arg = s.cast(arg)
8633 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8634
8635 def add(self, *args):
8636 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8637 self.assert_exprs(*args)
8638
8639 def __iadd__(self, fml):
8640 self.add(fml)
8641 return self
8642
8643 def assert_and_track(self, a, p):
8644 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8645
8646 If `p` is a string, it will be automatically converted into a Boolean constant.
8647
8648 >>> x = Int('x')
8649 >>> p3 = Bool('p3')
8650 >>> s = Optimize()
8651 >>> s.assert_and_track(x > 0, 'p1')
8652 >>> s.assert_and_track(x != 1, 'p2')
8653 >>> s.assert_and_track(x < 0, p3)
8654 >>> print(s.check())
8655 unsat
8656 >>> c = s.unsat_core()
8657 >>> len(c)
8658 2
8659 >>> Bool('p1') in c
8660 True
8661 >>> Bool('p2') in c
8662 False
8663 >>> p3 in c
8664 True
8665 """
8666 if isinstance(p, str):
8667 p = Bool(p, self.ctx)
8668 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8669 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8670 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8671
8672 def add_soft(self, arg, weight="1", id=None):
8673 """Add soft constraint with optional weight and optional identifier.
8674 If no weight is supplied, then the penalty for violating the soft constraint
8675 is 1.
8676 Soft constraints are grouped by identifiers. Soft constraints that are
8677 added without identifiers are grouped by default.
8678 """
8679 if _is_int(weight):
8680 weight = "%d" % weight
8681 elif isinstance(weight, float):
8682 weight = "%f" % weight
8683 if not isinstance(weight, str):
8684 raise Z3Exception("weight should be a string or an integer")
8685 if id is None:
8686 id = ""
8687 id = to_symbol(id, self.ctx)
8688
8689 def asoft(a):
8690 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8691 return OptimizeObjective(self, v, False)
8692 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8693 return [asoft(a) for a in arg]
8694 return asoft(arg)
8695
8696 def set_initial_value(self, var, value):
8697 """initialize the solver's state by setting the initial value of var to value
8698 """
8699 s = var.sort()
8700 value = s.cast(value)
8701 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8702
8703 def maximize(self, arg):
8704 """Add objective function to maximize."""
8705 return OptimizeObjective(
8706 self,
8707 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8708 is_max=True,
8709 )
8710
8711 def minimize(self, arg):
8712 """Add objective function to minimize."""
8713 return OptimizeObjective(
8714 self,
8715 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8716 is_max=False,
8717 )
8718
8719 def push(self):
8720 """create a backtracking point for added rules, facts and assertions"""
8721 Z3_optimize_push(self.ctx.ref(), self.optimize)
8722
8723 def pop(self):
8724 """restore to previously created backtracking point"""
8725 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8726
8727 def check(self, *assumptions):
8728 """Check consistency and produce optimal values."""
8729 assumptions = _get_args(assumptions)
8730 num = len(assumptions)
8731 _assumptions = (Ast * num)()
8732 for i in range(num):
8733 _assumptions[i] = assumptions[i].as_ast()
8734 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8735
8736 def reason_unknown(self):
8737 """Return a string that describes why the last `check()` returned `unknown`."""
8738 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8739
8740 def model(self):
8741 """Return a model for the last check()."""
8742 try:
8743 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8744 except Z3Exception:
8745 raise Z3Exception("model is not available")
8746
8747 def unsat_core(self):
8748 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8749
8750 def lower(self, obj):
8751 if not isinstance(obj, OptimizeObjective):
8752 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8753 return obj.lower()
8754
8755 def upper(self, obj):
8756 if not isinstance(obj, OptimizeObjective):
8757 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8758 return obj.upper()
8759
8760 def lower_values(self, obj):
8761 if not isinstance(obj, OptimizeObjective):
8762 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8763 return obj.lower_values()
8764
8765 def upper_values(self, obj):
8766 if not isinstance(obj, OptimizeObjective):
8767 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8768 return obj.upper_values()
8769
8770 def from_file(self, filename):
8771 """Parse assertions and objectives from a file"""
8772 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8773
8774 def from_string(self, s):
8775 """Parse assertions and objectives from a string"""
8776 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8777
8778 def assertions(self):
8779 """Return an AST vector containing all added constraints."""
8780 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8781
8782 def objectives(self):
8783 """returns set of objective functions"""
8784 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8785
8786 def __repr__(self):
8787 """Return a formatted string with all added rules and constraints."""
8788 return self.sexpr()
8789
8790 def sexpr(self):
8791 """Return a formatted string (in Lisp-like format) with all added constraints.
8792 We say the string is in s-expression format.
8793 """
8794 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8795
8796 def statistics(self):
8797 """Return statistics for the last check`.
8798 """
8799 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8800
8801 def translate(self, target):
8802 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8803
8804 >>> c1 = Context()
8805 >>> c2 = Context()
8806 >>> o1 = Optimize(ctx=c1)
8807 >>> o2 = o1.translate(c2)
8808 """
8809 if z3_debug():
8810 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8811 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8812 return Optimize(opt, target)
8813
8814 def set_on_model(self, on_model):
8815 """Register a callback that is invoked with every incremental improvement to
8816 objective values. The callback takes a model as argument.
8817 The life-time of the model is limited to the callback so the
8818 model has to be (deep) copied if it is to be used after the callback
8819 """
8820 id = len(_on_models) + 41
8821 mdl = Model(self.ctx)
8822 _on_models[id] = (on_model, mdl)
8823 self._on_models_id = id
8824 Z3_optimize_register_model_eh(
8825 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8826 )
8827
8828
8829#########################################
8830#
8831# ApplyResult
8832#
8833#########################################
8834class ApplyResult(Z3PPObject):
8835 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8836 It also contains model and proof converters.
8837 """
8838
8839 def __init__(self, result, ctx):
8840 self.result = result
8841 self.ctx = ctx
8842 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8843
8844 def __deepcopy__(self, memo={}):
8845 return ApplyResult(self.result, self.ctx)
8846
8847 def __del__(self):
8848 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8849 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8850
8851 def __len__(self):
8852 """Return the number of subgoals in `self`.
8853
8854 >>> a, b = Ints('a b')
8855 >>> g = Goal()
8856 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8857 >>> t = Tactic('split-clause')
8858 >>> r = t(g)
8859 >>> len(r)
8860 2
8861 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8862 >>> len(t(g))
8863 4
8864 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8865 >>> len(t(g))
8866 1
8867 """
8868 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8869
8870 def __getitem__(self, idx):
8871 """Return one of the subgoals stored in ApplyResult object `self`.
8872
8873 >>> a, b = Ints('a b')
8874 >>> g = Goal()
8875 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8876 >>> t = Tactic('split-clause')
8877 >>> r = t(g)
8878 >>> r[0]
8879 [a == 0, Or(b == 0, b == 1), a > b]
8880 >>> r[1]
8881 [a == 1, Or(b == 0, b == 1), a > b]
8882 """
8883 if idx < 0:
8884 idx += len(self)
8885 if idx < 0 or idx >= len(self):
8886 raise IndexError
8887 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8888
8889 def __repr__(self):
8890 return obj_to_string(self)
8891
8892 def sexpr(self):
8893 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8894 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8895
8896 def as_expr(self):
8897 """Return a Z3 expression consisting of all subgoals.
8898
8899 >>> x = Int('x')
8900 >>> g = Goal()
8901 >>> g.add(x > 1)
8902 >>> g.add(Or(x == 2, x == 3))
8903 >>> r = Tactic('simplify')(g)
8904 >>> r
8905 [[Not(x <= 1), Or(x == 2, x == 3)]]
8906 >>> r.as_expr()
8907 And(Not(x <= 1), Or(x == 2, x == 3))
8908 >>> r = Tactic('split-clause')(g)
8909 >>> r
8910 [[x > 1, x == 2], [x > 1, x == 3]]
8911 >>> r.as_expr()
8912 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8913 """
8914 sz = len(self)
8915 if sz == 0:
8916 return BoolVal(False, self.ctx)
8917 elif sz == 1:
8918 return self[0].as_expr()
8919 else:
8920 return Or([self[i].as_expr() for i in range(len(self))])
8921
8922#########################################
8923#
8924# Simplifiers
8925#
8926#########################################
8927
8928def num_simplifiers(ctx=None):
8929 """Return the number of simplifiers supported by the given context."""
8930 return Z3_get_num_simplifiers(_get_ctx(ctx).ref())
8931
8932
8933def simplifier_name(i, ctx=None):
8934 """Return the name of the i-th simplifier supported by the given context."""
8935 return Z3_get_simplifier_name(_get_ctx(ctx).ref(), i)
8936
8937
8938def simplifier_description(name, ctx=None):
8939 """Return the description of the simplifier identified by name."""
8940 return Z3_simplifier_get_descr(_get_ctx(ctx).ref(), name)
8941
8942
8943class Simplifier:
8944 """Simplifiers act as pre-processing utilities for solvers.
8945 Build a custom simplifier and add it to a solver"""
8946
8947 def __init__(self, simplifier, ctx=None):
8948 self.ctx = _get_ctx(ctx)
8949 self.simplifier = None
8950 if isinstance(simplifier, SimplifierObj):
8951 self.simplifier = simplifier
8952 elif isinstance(simplifier, list):
8953 simps = [Simplifier(s, ctx) for s in simplifier]
8954 self.simplifier = simps[0].simplifier
8955 for i in range(1, len(simps)):
8956 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
8957 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8958 return
8959 else:
8960 if z3_debug():
8961 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
8962 try:
8963 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
8964 except Z3Exception:
8965 raise Z3Exception("unknown simplifier '%s'" % simplifier)
8966 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8967
8968 def __deepcopy__(self, memo={}):
8969 return Simplifier(self.simplifier, self.ctx)
8970
8971 def __del__(self):
8972 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
8973 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
8974
8975 def using_params(self, *args, **keys):
8976 """Return a simplifier that uses the given configuration options"""
8977 p = args2params(args, keys, self.ctx)
8978 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
8979
8980 def add(self, solver):
8981 """Return a solver that applies the simplification pre-processing specified by the simplifier"""
8982 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
8983
8984 def help(self):
8985 """Display a string containing a description of the available options for the `self` simplifier."""
8986 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
8987
8988 def param_descrs(self):
8989 """Return the parameter description set."""
8990 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
8991
8992
8993#########################################
8994#
8995# Tactics
8996#
8997#########################################
8998
8999
9000class Tactic:
9001 """Tactics transform, solver and/or simplify sets of constraints (Goal).
9002 A Tactic can be converted into a Solver using the method solver().
9003
9004 Several combinators are available for creating new tactics using the built-in ones:
9005 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
9006 """
9007
9008 def __init__(self, tactic, ctx=None):
9009 self.ctx = _get_ctx(ctx)
9010 self.tactic = None
9011 if isinstance(tactic, TacticObj):
9012 self.tactic = tactic
9013 else:
9014 if z3_debug():
9015 _z3_assert(isinstance(tactic, str), "tactic name expected")
9016 try:
9017 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9018 except Z3Exception:
9019 raise Z3Exception("unknown tactic '%s'" % tactic)
9020 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9021
9022 def __deepcopy__(self, memo={}):
9023 return Tactic(self.tactic, self.ctx)
9024
9025 def __del__(self):
9026 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9027 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9028
9029 def solver(self, logFile=None):
9030 """Create a solver using the tactic `self`.
9031
9032 The solver supports the methods `push()` and `pop()`, but it
9033 will always solve each `check()` from scratch.
9034
9035 >>> t = Then('simplify', 'nlsat')
9036 >>> s = t.solver()
9037 >>> x = Real('x')
9038 >>> s.add(x**2 == 2, x > 0)
9039 >>> s.check()
9040 sat
9041 >>> s.model()
9042 [x = 1.4142135623?]
9043 """
9044 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9045
9046 def apply(self, goal, *arguments, **keywords):
9047 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9048
9049 >>> x, y = Ints('x y')
9050 >>> t = Tactic('solve-eqs')
9051 >>> t.apply(And(x == 0, y >= x + 1))
9052 [[y >= 1]]
9053 """
9054 if z3_debug():
9055 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9056 goal = _to_goal(goal)
9057 if len(arguments) > 0 or len(keywords) > 0:
9058 p = args2params(arguments, keywords, self.ctx)
9059 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9060 else:
9061 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9062
9063 def __call__(self, goal, *arguments, **keywords):
9064 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9065
9066 >>> x, y = Ints('x y')
9067 >>> t = Tactic('solve-eqs')
9068 >>> t(And(x == 0, y >= x + 1))
9069 [[y >= 1]]
9070 """
9071 return self.apply(goal, *arguments, **keywords)
9072
9073 def help(self):
9074 """Display a string containing a description of the available options for the `self` tactic."""
9075 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9076
9077 def param_descrs(self):
9078 """Return the parameter description set."""
9079 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9080
9081
9082def _to_goal(a):
9083 if isinstance(a, BoolRef):
9084 goal = Goal(ctx=a.ctx)
9085 goal.add(a)
9086 return goal
9087 else:
9088 return a
9089
9090
9091def _to_tactic(t, ctx=None):
9092 if isinstance(t, Tactic):
9093 return t
9094 else:
9095 return Tactic(t, ctx)
9096
9097
9098def _and_then(t1, t2, ctx=None):
9099 t1 = _to_tactic(t1, ctx)
9100 t2 = _to_tactic(t2, ctx)
9101 if z3_debug():
9102 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9103 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9104
9105
9106def _or_else(t1, t2, ctx=None):
9107 t1 = _to_tactic(t1, ctx)
9108 t2 = _to_tactic(t2, ctx)
9109 if z3_debug():
9110 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9111 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9112
9113
9114def AndThen(*ts, **ks):
9115 """Return a tactic that applies the tactics in `*ts` in sequence.
9116
9117 >>> x, y = Ints('x y')
9118 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9119 >>> t(And(x == 0, y > x + 1))
9120 [[Not(y <= 1)]]
9121 >>> t(And(x == 0, y > x + 1)).as_expr()
9122 Not(y <= 1)
9123 """
9124 if z3_debug():
9125 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9126 ctx = ks.get("ctx", None)
9127 num = len(ts)
9128 r = ts[0]
9129 for i in range(num - 1):
9130 r = _and_then(r, ts[i + 1], ctx)
9131 return r
9132
9133
9134def Then(*ts, **ks):
9135 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9136
9137 >>> x, y = Ints('x y')
9138 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9139 >>> t(And(x == 0, y > x + 1))
9140 [[Not(y <= 1)]]
9141 >>> t(And(x == 0, y > x + 1)).as_expr()
9142 Not(y <= 1)
9143 """
9144 return AndThen(*ts, **ks)
9145
9146
9147def OrElse(*ts, **ks):
9148 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9149
9150 >>> x = Int('x')
9151 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9152 >>> # Tactic split-clause fails if there is no clause in the given goal.
9153 >>> t(x == 0)
9154 [[x == 0]]
9155 >>> t(Or(x == 0, x == 1))
9156 [[x == 0], [x == 1]]
9157 """
9158 if z3_debug():
9159 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9160 ctx = ks.get("ctx", None)
9161 num = len(ts)
9162 r = ts[0]
9163 for i in range(num - 1):
9164 r = _or_else(r, ts[i + 1], ctx)
9165 return r
9166
9167
9168def ParOr(*ts, **ks):
9169 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9170
9171 >>> x = Int('x')
9172 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9173 >>> t(x + 1 == 2)
9174 [[x == 1]]
9175 """
9176 if z3_debug():
9177 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9178 ctx = _get_ctx(ks.get("ctx", None))
9179 ts = [_to_tactic(t, ctx) for t in ts]
9180 sz = len(ts)
9181 _args = (TacticObj * sz)()
9182 for i in range(sz):
9183 _args[i] = ts[i].tactic
9184 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9185
9186
9187def ParThen(t1, t2, ctx=None):
9188 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9189 The subgoals are processed in parallel.
9190
9191 >>> x, y = Ints('x y')
9192 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9193 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9194 [[x == 1, y == 2], [x == 2, y == 3]]
9195 """
9196 t1 = _to_tactic(t1, ctx)
9197 t2 = _to_tactic(t2, ctx)
9198 if z3_debug():
9199 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9200 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9201
9202
9203def ParAndThen(t1, t2, ctx=None):
9204 """Alias for ParThen(t1, t2, ctx)."""
9205 return ParThen(t1, t2, ctx)
9206
9207
9208def With(t, *args, **keys):
9209 """Return a tactic that applies tactic `t` using the given configuration options.
9210
9211 >>> x, y = Ints('x y')
9212 >>> t = With(Tactic('simplify'), som=True)
9213 >>> t((x + 1)*(y + 2) == 0)
9214 [[2*x + y + x*y == -2]]
9215 """
9216 ctx = keys.pop("ctx", None)
9217 t = _to_tactic(t, ctx)
9218 p = args2params(args, keys, t.ctx)
9219 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9220
9221
9222def WithParams(t, p):
9223 """Return a tactic that applies tactic `t` using the given configuration options.
9224
9225 >>> x, y = Ints('x y')
9226 >>> p = ParamsRef()
9227 >>> p.set("som", True)
9228 >>> t = WithParams(Tactic('simplify'), p)
9229 >>> t((x + 1)*(y + 2) == 0)
9230 [[2*x + y + x*y == -2]]
9231 """
9232 t = _to_tactic(t, None)
9233 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9234
9235
9236def Repeat(t, max=4294967295, ctx=None):
9237 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9238 or the maximum number of iterations `max` is reached.
9239
9240 >>> x, y = Ints('x y')
9241 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9242 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9243 >>> r = t(c)
9244 >>> for subgoal in r: print(subgoal)
9245 [x == 0, y == 0, x > y]
9246 [x == 0, y == 1, x > y]
9247 [x == 1, y == 0, x > y]
9248 [x == 1, y == 1, x > y]
9249 >>> t = Then(t, Tactic('propagate-values'))
9250 >>> t(c)
9251 [[x == 1, y == 0]]
9252 """
9253 t = _to_tactic(t, ctx)
9254 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9255
9256
9257def TryFor(t, ms, ctx=None):
9258 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9259
9260 If `t` does not terminate in `ms` milliseconds, then it fails.
9261 """
9262 t = _to_tactic(t, ctx)
9263 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9264
9265
9266def tactics(ctx=None):
9267 """Return a list of all available tactics in Z3.
9268
9269 >>> l = tactics()
9270 >>> l.count('simplify') == 1
9271 True
9272 """
9273 ctx = _get_ctx(ctx)
9274 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9275
9276
9277def tactic_description(name, ctx=None):
9278 """Return a short description for the tactic named `name`.
9279
9280 >>> d = tactic_description('simplify')
9281 """
9282 ctx = _get_ctx(ctx)
9283 return Z3_tactic_get_descr(ctx.ref(), name)
9284
9285
9286def describe_tactics():
9287 """Display a (tabular) description of all available tactics in Z3."""
9288 if in_html_mode():
9289 even = True
9290 print('<table border="1" cellpadding="2" cellspacing="0">')
9291 for t in tactics():
9292 if even:
9293 print('<tr style="background-color:#CFCFCF">')
9294 even = False
9295 else:
9296 print("<tr>")
9297 even = True
9298 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9299 print("</table>")
9300 else:
9301 for t in tactics():
9302 print("%s : %s" % (t, tactic_description(t)))
9303
9304
9305class Probe:
9306 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9307 to decide which solver and/or preprocessing step will be used.
9308 """
9309
9310 def __init__(self, probe, ctx=None):
9311 self.ctx = _get_ctx(ctx)
9312 self.probe = None
9313 if isinstance(probe, ProbeObj):
9314 self.probe = probe
9315 elif isinstance(probe, float):
9316 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9317 elif _is_int(probe):
9318 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9319 elif isinstance(probe, bool):
9320 if probe:
9321 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9322 else:
9323 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9324 else:
9325 if z3_debug():
9326 _z3_assert(isinstance(probe, str), "probe name expected")
9327 try:
9328 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9329 except Z3Exception:
9330 raise Z3Exception("unknown probe '%s'" % probe)
9331 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9332
9333 def __deepcopy__(self, memo={}):
9334 return Probe(self.probe, self.ctx)
9335
9336 def __del__(self):
9337 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9338 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9339
9340 def __lt__(self, other):
9341 """Return a probe that evaluates to "true" when the value returned by `self`
9342 is less than the value returned by `other`.
9343
9344 >>> p = Probe('size') < 10
9345 >>> x = Int('x')
9346 >>> g = Goal()
9347 >>> g.add(x > 0)
9348 >>> g.add(x < 10)
9349 >>> p(g)
9350 1.0
9351 """
9352 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9353
9354 def __gt__(self, other):
9355 """Return a probe that evaluates to "true" when the value returned by `self`
9356 is greater than the value returned by `other`.
9357
9358 >>> p = Probe('size') > 10
9359 >>> x = Int('x')
9360 >>> g = Goal()
9361 >>> g.add(x > 0)
9362 >>> g.add(x < 10)
9363 >>> p(g)
9364 0.0
9365 """
9366 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9367
9368 def __le__(self, other):
9369 """Return a probe that evaluates to "true" when the value returned by `self`
9370 is less than or equal to the value returned by `other`.
9371
9372 >>> p = Probe('size') <= 2
9373 >>> x = Int('x')
9374 >>> g = Goal()
9375 >>> g.add(x > 0)
9376 >>> g.add(x < 10)
9377 >>> p(g)
9378 1.0
9379 """
9380 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9381
9382 def __ge__(self, other):
9383 """Return a probe that evaluates to "true" when the value returned by `self`
9384 is greater than or equal to the value returned by `other`.
9385
9386 >>> p = Probe('size') >= 2
9387 >>> x = Int('x')
9388 >>> g = Goal()
9389 >>> g.add(x > 0)
9390 >>> g.add(x < 10)
9391 >>> p(g)
9392 1.0
9393 """
9394 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9395
9396 def __eq__(self, other):
9397 """Return a probe that evaluates to "true" when the value returned by `self`
9398 is equal to the value returned by `other`.
9399
9400 >>> p = Probe('size') == 2
9401 >>> x = Int('x')
9402 >>> g = Goal()
9403 >>> g.add(x > 0)
9404 >>> g.add(x < 10)
9405 >>> p(g)
9406 1.0
9407 """
9408 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9409
9410 def __ne__(self, other):
9411 """Return a probe that evaluates to "true" when the value returned by `self`
9412 is not equal to the value returned by `other`.
9413
9414 >>> p = Probe('size') != 2
9415 >>> x = Int('x')
9416 >>> g = Goal()
9417 >>> g.add(x > 0)
9418 >>> g.add(x < 10)
9419 >>> p(g)
9420 0.0
9421 """
9422 p = self.__eq__(other)
9423 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9424
9425 def __call__(self, goal):
9426 """Evaluate the probe `self` in the given goal.
9427
9428 >>> p = Probe('size')
9429 >>> x = Int('x')
9430 >>> g = Goal()
9431 >>> g.add(x > 0)
9432 >>> g.add(x < 10)
9433 >>> p(g)
9434 2.0
9435 >>> g.add(x < 20)
9436 >>> p(g)
9437 3.0
9438 >>> p = Probe('num-consts')
9439 >>> p(g)
9440 1.0
9441 >>> p = Probe('is-propositional')
9442 >>> p(g)
9443 0.0
9444 >>> p = Probe('is-qflia')
9445 >>> p(g)
9446 1.0
9447 """
9448 if z3_debug():
9449 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9450 goal = _to_goal(goal)
9451 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9452
9453
9454def is_probe(p):
9455 """Return `True` if `p` is a Z3 probe.
9456
9457 >>> is_probe(Int('x'))
9458 False
9459 >>> is_probe(Probe('memory'))
9460 True
9461 """
9462 return isinstance(p, Probe)
9463
9464
9465def _to_probe(p, ctx=None):
9466 if is_probe(p):
9467 return p
9468 else:
9469 return Probe(p, ctx)
9470
9471
9472def probes(ctx=None):
9473 """Return a list of all available probes in Z3.
9474
9475 >>> l = probes()
9476 >>> l.count('memory') == 1
9477 True
9478 """
9479 ctx = _get_ctx(ctx)
9480 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9481
9482
9483def probe_description(name, ctx=None):
9484 """Return a short description for the probe named `name`.
9485
9486 >>> d = probe_description('memory')
9487 """
9488 ctx = _get_ctx(ctx)
9489 return Z3_probe_get_descr(ctx.ref(), name)
9490
9491
9492def describe_probes():
9493 """Display a (tabular) description of all available probes in Z3."""
9494 if in_html_mode():
9495 even = True
9496 print('<table border="1" cellpadding="2" cellspacing="0">')
9497 for p in probes():
9498 if even:
9499 print('<tr style="background-color:#CFCFCF">')
9500 even = False
9501 else:
9502 print("<tr>")
9503 even = True
9504 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9505 print("</table>")
9506 else:
9507 for p in probes():
9508 print("%s : %s" % (p, probe_description(p)))
9509
9510
9511def _probe_nary(f, args, ctx):
9512 if z3_debug():
9513 _z3_assert(len(args) > 0, "At least one argument expected")
9514 num = len(args)
9515 r = _to_probe(args[0], ctx)
9516 for i in range(num - 1):
9517 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9518 return r
9519
9520
9521def _probe_and(args, ctx):
9522 return _probe_nary(Z3_probe_and, args, ctx)
9523
9524
9525def _probe_or(args, ctx):
9526 return _probe_nary(Z3_probe_or, args, ctx)
9527
9528
9529def FailIf(p, ctx=None):
9530 """Return a tactic that fails if the probe `p` evaluates to true.
9531 Otherwise, it returns the input goal unmodified.
9532
9533 In the following example, the tactic applies 'simplify' if and only if there are
9534 more than 2 constraints in the goal.
9535
9536 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9537 >>> x, y = Ints('x y')
9538 >>> g = Goal()
9539 >>> g.add(x > 0)
9540 >>> g.add(y > 0)
9541 >>> t(g)
9542 [[x > 0, y > 0]]
9543 >>> g.add(x == y + 1)
9544 >>> t(g)
9545 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9546 """
9547 p = _to_probe(p, ctx)
9548 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9549
9550
9551def When(p, t, ctx=None):
9552 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9553 Otherwise, it returns the input goal unmodified.
9554
9555 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9556 >>> x, y = Ints('x y')
9557 >>> g = Goal()
9558 >>> g.add(x > 0)
9559 >>> g.add(y > 0)
9560 >>> t(g)
9561 [[x > 0, y > 0]]
9562 >>> g.add(x == y + 1)
9563 >>> t(g)
9564 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9565 """
9566 p = _to_probe(p, ctx)
9567 t = _to_tactic(t, ctx)
9568 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9569
9570
9571def Cond(p, t1, t2, ctx=None):
9572 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9573
9574 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9575 """
9576 p = _to_probe(p, ctx)
9577 t1 = _to_tactic(t1, ctx)
9578 t2 = _to_tactic(t2, ctx)
9579 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9580
9581#########################################
9582#
9583# Utils
9584#
9585#########################################
9586
9587
9588def simplify(a, *arguments, **keywords):
9589 """Simplify the expression `a` using the given options.
9590
9591 This function has many options. Use `help_simplify` to obtain the complete list.
9592
9593 >>> x = Int('x')
9594 >>> y = Int('y')
9595 >>> simplify(x + 1 + y + x + 1)
9596 2 + 2*x + y
9597 >>> simplify((x + 1)*(y + 1), som=True)
9598 1 + x + y + x*y
9599 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9600 And(Not(x == y), Not(x == 1), Not(y == 1))
9601 >>> simplify(And(x == 0, y == 1), elim_and=True)
9602 Not(Or(Not(x == 0), Not(y == 1)))
9603 """
9604 if z3_debug():
9605 _z3_assert(is_expr(a), "Z3 expression expected")
9606 if len(arguments) > 0 or len(keywords) > 0:
9607 p = args2params(arguments, keywords, a.ctx)
9608 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9609 else:
9610 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9611
9612
9613def help_simplify():
9614 """Return a string describing all options available for Z3 `simplify` procedure."""
9615 print(Z3_simplify_get_help(main_ctx().ref()))
9616
9617
9618def simplify_param_descrs():
9619 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9620 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9621
9622
9623def substitute(t, *m):
9624 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9625 Every occurrence in t of from is replaced with to.
9626
9627 >>> x = Int('x')
9628 >>> y = Int('y')
9629 >>> substitute(x + 1, (x, y + 1))
9630 y + 1 + 1
9631 >>> f = Function('f', IntSort(), IntSort())
9632 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9633 1 + 1
9634 """
9635 if isinstance(m, tuple):
9636 m1 = _get_args(m)
9637 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9638 m = m1
9639 if z3_debug():
9640 _z3_assert(is_expr(t), "Z3 expression expected")
9641 _z3_assert(
9642 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9643 "Z3 invalid substitution, expression pairs expected.")
9644 _z3_assert(
9645 all([p[0].sort().eq(p[1].sort()) for p in m]),
9646 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9647 num = len(m)
9648 _from = (Ast * num)()
9649 _to = (Ast * num)()
9650 for i in range(num):
9651 _from[i] = m[i][0].as_ast()
9652 _to[i] = m[i][1].as_ast()
9653 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9654
9655
9656def substitute_vars(t, *m):
9657 """Substitute the free variables in t with the expression in m.
9658
9659 >>> v0 = Var(0, IntSort())
9660 >>> v1 = Var(1, IntSort())
9661 >>> x = Int('x')
9662 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9663 >>> # replace v0 with x+1 and v1 with x
9664 >>> substitute_vars(f(v0, v1), x + 1, x)
9665 f(x + 1, x)
9666 """
9667 if z3_debug():
9668 _z3_assert(is_expr(t), "Z3 expression expected")
9669 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9670 num = len(m)
9671 _to = (Ast * num)()
9672 for i in range(num):
9673 _to[i] = m[i].as_ast()
9674 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9675
9676def substitute_funs(t, *m):
9677 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9678 Every occurrence in to of the function from is replaced with the expression to.
9679 The expression to can have free variables, that refer to the arguments of from.
9680 For examples, see
9681 """
9682 if isinstance(m, tuple):
9683 m1 = _get_args(m)
9684 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9685 m = m1
9686 if z3_debug():
9687 _z3_assert(is_expr(t), "Z3 expression expected")
9688 _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, function pairs expected.")
9689 num = len(m)
9690 _from = (FuncDecl * num)()
9691 _to = (Ast * num)()
9692 for i in range(num):
9693 _from[i] = m[i][0].as_func_decl()
9694 _to[i] = m[i][1].as_ast()
9695 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9696
9697
9698def Sum(*args):
9699 """Create the sum of the Z3 expressions.
9700
9701 >>> a, b, c = Ints('a b c')
9702 >>> Sum(a, b, c)
9703 a + b + c
9704 >>> Sum([a, b, c])
9705 a + b + c
9706 >>> A = IntVector('a', 5)
9707 >>> Sum(A)
9708 a__0 + a__1 + a__2 + a__3 + a__4
9709 """
9710 args = _get_args(args)
9711 if len(args) == 0:
9712 return 0
9713 ctx = _ctx_from_ast_arg_list(args)
9714 if ctx is None:
9715 return _reduce(lambda a, b: a + b, args, 0)
9716 args = _coerce_expr_list(args, ctx)
9717 if is_bv(args[0]):
9718 return _reduce(lambda a, b: a + b, args, 0)
9719 else:
9720 _args, sz = _to_ast_array(args)
9721 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9722
9723
9724def Product(*args):
9725 """Create the product of the Z3 expressions.
9726
9727 >>> a, b, c = Ints('a b c')
9728 >>> Product(a, b, c)
9729 a*b*c
9730 >>> Product([a, b, c])
9731 a*b*c
9732 >>> A = IntVector('a', 5)
9733 >>> Product(A)
9734 a__0*a__1*a__2*a__3*a__4
9735 """
9736 args = _get_args(args)
9737 if len(args) == 0:
9738 return 1
9739 ctx = _ctx_from_ast_arg_list(args)
9740 if ctx is None:
9741 return _reduce(lambda a, b: a * b, args, 1)
9742 args = _coerce_expr_list(args, ctx)
9743 if is_bv(args[0]):
9744 return _reduce(lambda a, b: a * b, args, 1)
9745 else:
9746 _args, sz = _to_ast_array(args)
9747 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9748
9749def Abs(arg):
9750 """Create the absolute value of an arithmetic expression"""
9751 return If(arg > 0, arg, -arg)
9752
9753
9754def AtMost(*args):
9755 """Create an at-most Pseudo-Boolean k constraint.
9756
9757 >>> a, b, c = Bools('a b c')
9758 >>> f = AtMost(a, b, c, 2)
9759 """
9760 args = _get_args(args)
9761 if z3_debug():
9762 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9763 ctx = _ctx_from_ast_arg_list(args)
9764 if z3_debug():
9765 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9766 args1 = _coerce_expr_list(args[:-1], ctx)
9767 k = args[-1]
9768 _args, sz = _to_ast_array(args1)
9769 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9770
9771
9772def AtLeast(*args):
9773 """Create an at-least Pseudo-Boolean k constraint.
9774
9775 >>> a, b, c = Bools('a b c')
9776 >>> f = AtLeast(a, b, c, 2)
9777 """
9778 args = _get_args(args)
9779 if z3_debug():
9780 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9781 ctx = _ctx_from_ast_arg_list(args)
9782 if z3_debug():
9783 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9784 args1 = _coerce_expr_list(args[:-1], ctx)
9785 k = args[-1]
9786 _args, sz = _to_ast_array(args1)
9787 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9788
9789
9790def _reorder_pb_arg(arg):
9791 a, b = arg
9792 if not _is_int(b) and _is_int(a):
9793 return b, a
9794 return arg
9795
9796
9797def _pb_args_coeffs(args, default_ctx=None):
9798 args = _get_args_ast_list(args)
9799 if len(args) == 0:
9800 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9801 args = [_reorder_pb_arg(arg) for arg in args]
9802 args, coeffs = zip(*args)
9803 if z3_debug():
9804 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9805 ctx = _ctx_from_ast_arg_list(args)
9806 if z3_debug():
9807 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9808 args = _coerce_expr_list(args, ctx)
9809 _args, sz = _to_ast_array(args)
9810 _coeffs = (ctypes.c_int * len(coeffs))()
9811 for i in range(len(coeffs)):
9812 _z3_check_cint_overflow(coeffs[i], "coefficient")
9813 _coeffs[i] = coeffs[i]
9814 return ctx, sz, _args, _coeffs, args
9815
9816
9817def PbLe(args, k):
9818 """Create a Pseudo-Boolean inequality k constraint.
9819
9820 >>> a, b, c = Bools('a b c')
9821 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9822 """
9823 _z3_check_cint_overflow(k, "k")
9824 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9825 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9826
9827
9828def PbGe(args, k):
9829 """Create a Pseudo-Boolean inequality k constraint.
9830
9831 >>> a, b, c = Bools('a b c')
9832 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9833 """
9834 _z3_check_cint_overflow(k, "k")
9835 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9836 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9837
9838
9839def PbEq(args, k, ctx=None):
9840 """Create a Pseudo-Boolean equality k constraint.
9841
9842 >>> a, b, c = Bools('a b c')
9843 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9844 """
9845 _z3_check_cint_overflow(k, "k")
9846 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9847 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9848
9849
9850def solve(*args, **keywords):
9851 """Solve the constraints `*args`.
9852
9853 This is a simple function for creating demonstrations. It creates a solver,
9854 configure it using the options in `keywords`, adds the constraints
9855 in `args`, and invokes check.
9856
9857 >>> a = Int('a')
9858 >>> solve(a > 0, a < 2)
9859 [a = 1]
9860 """
9861 show = keywords.pop("show", False)
9862 s = Solver()
9863 s.set(**keywords)
9864 s.add(*args)
9865 if show:
9866 print(s)
9867 r = s.check()
9868 if r == unsat:
9869 print("no solution")
9870 elif r == unknown:
9871 print("failed to solve")
9872 try:
9873 print(s.model())
9874 except Z3Exception:
9875 return
9876 else:
9877 print(s.model())
9878
9879
9880def solve_using(s, *args, **keywords):
9881 """Solve the constraints `*args` using solver `s`.
9882
9883 This is a simple function for creating demonstrations. It is similar to `solve`,
9884 but it uses the given solver `s`.
9885 It configures solver `s` using the options in `keywords`, adds the constraints
9886 in `args`, and invokes check.
9887 """
9888 show = keywords.pop("show", False)
9889 if z3_debug():
9890 _z3_assert(isinstance(s, Solver), "Solver object expected")
9891 s.set(**keywords)
9892 s.add(*args)
9893 if show:
9894 print("Problem:")
9895 print(s)
9896 r = s.check()
9897 if r == unsat:
9898 print("no solution")
9899 elif r == unknown:
9900 print("failed to solve")
9901 try:
9902 print(s.model())
9903 except Z3Exception:
9904 return
9905 else:
9906 if show:
9907 print("Solution:")
9908 print(s.model())
9909
9910
9911def prove(claim, show=False, **keywords):
9912 """Try to prove the given claim.
9913
9914 This is a simple function for creating demonstrations. It tries to prove
9915 `claim` by showing the negation is unsatisfiable.
9916
9917 >>> p, q = Bools('p q')
9918 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9919 proved
9920 """
9921 if z3_debug():
9922 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9923 s = Solver()
9924 s.set(**keywords)
9925 s.add(Not(claim))
9926 if show:
9927 print(s)
9928 r = s.check()
9929 if r == unsat:
9930 print("proved")
9931 elif r == unknown:
9932 print("failed to prove")
9933 print(s.model())
9934 else:
9935 print("counterexample")
9936 print(s.model())
9937
9938
9939def _solve_html(*args, **keywords):
9940 """Version of function `solve` that renders HTML output."""
9941 show = keywords.pop("show", False)
9942 s = Solver()
9943 s.set(**keywords)
9944 s.add(*args)
9945 if show:
9946 print("<b>Problem:</b>")
9947 print(s)
9948 r = s.check()
9949 if r == unsat:
9950 print("<b>no solution</b>")
9951 elif r == unknown:
9952 print("<b>failed to solve</b>")
9953 try:
9954 print(s.model())
9955 except Z3Exception:
9956 return
9957 else:
9958 if show:
9959 print("<b>Solution:</b>")
9960 print(s.model())
9961
9962
9963def _solve_using_html(s, *args, **keywords):
9964 """Version of function `solve_using` that renders HTML."""
9965 show = keywords.pop("show", False)
9966 if z3_debug():
9967 _z3_assert(isinstance(s, Solver), "Solver object expected")
9968 s.set(**keywords)
9969 s.add(*args)
9970 if show:
9971 print("<b>Problem:</b>")
9972 print(s)
9973 r = s.check()
9974 if r == unsat:
9975 print("<b>no solution</b>")
9976 elif r == unknown:
9977 print("<b>failed to solve</b>")
9978 try:
9979 print(s.model())
9980 except Z3Exception:
9981 return
9982 else:
9983 if show:
9984 print("<b>Solution:</b>")
9985 print(s.model())
9986
9987
9988def _prove_html(claim, show=False, **keywords):
9989 """Version of function `prove` that renders HTML."""
9990 if z3_debug():
9991 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9992 s = Solver()
9993 s.set(**keywords)
9994 s.add(Not(claim))
9995 if show:
9996 print(s)
9997 r = s.check()
9998 if r == unsat:
9999 print("<b>proved</b>")
10000 elif r == unknown:
10001 print("<b>failed to prove</b>")
10002 print(s.model())
10003 else:
10004 print("<b>counterexample</b>")
10005 print(s.model())
10006
10007
10008def _dict2sarray(sorts, ctx):
10009 sz = len(sorts)
10010 _names = (Symbol * sz)()
10011 _sorts = (Sort * sz)()
10012 i = 0
10013 for k in sorts:
10014 v = sorts[k]
10015 if z3_debug():
10016 _z3_assert(isinstance(k, str), "String expected")
10017 _z3_assert(is_sort(v), "Z3 sort expected")
10018 _names[i] = to_symbol(k, ctx)
10019 _sorts[i] = v.ast
10020 i = i + 1
10021 return sz, _names, _sorts
10022
10023
10024def _dict2darray(decls, ctx):
10025 sz = len(decls)
10026 _names = (Symbol * sz)()
10027 _decls = (FuncDecl * sz)()
10028 i = 0
10029 for k in decls:
10030 v = decls[k]
10031 if z3_debug():
10032 _z3_assert(isinstance(k, str), "String expected")
10033 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10034 _names[i] = to_symbol(k, ctx)
10035 if is_const(v):
10036 _decls[i] = v.decl().ast
10037 else:
10038 _decls[i] = v.ast
10039 i = i + 1
10040 return sz, _names, _decls
10041
10042class ParserContext:
10043 def __init__(self, ctx= None):
10044 self.ctx = _get_ctx(ctx)
10045 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10046 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10047
10048 def __del__(self):
10049 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10050 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10051 self.pctx = None
10052
10053 def add_sort(self, sort):
10054 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10055
10056 def add_decl(self, decl):
10057 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10058
10059 def from_string(self, s):
10060 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10061
10062def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10063 """Parse a string in SMT 2.0 format using the given sorts and decls.
10064
10065 The arguments sorts and decls are Python dictionaries used to initialize
10066 the symbol table used for the SMT 2.0 parser.
10067
10068 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10069 [x > 0, x < 10]
10070 >>> x, y = Ints('x y')
10071 >>> f = Function('f', IntSort(), IntSort())
10072 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10073 [x + f(y) > 0]
10074 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10075 [a > 0]
10076 """
10077 ctx = _get_ctx(ctx)
10078 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10079 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10080 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10081
10082
10083def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10084 """Parse a file in SMT 2.0 format using the given sorts and decls.
10085
10086 This function is similar to parse_smt2_string().
10087 """
10088 ctx = _get_ctx(ctx)
10089 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10090 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10091 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10092
10093
10094#########################################
10095#
10096# Floating-Point Arithmetic
10097#
10098#########################################
10099
10100
10101# Global default rounding mode
10102_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10103_dflt_fpsort_ebits = 11
10104_dflt_fpsort_sbits = 53
10105
10106
10107def get_default_rounding_mode(ctx=None):
10108 """Retrieves the global default rounding mode."""
10109 global _dflt_rounding_mode
10110 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10111 return RTZ(ctx)
10112 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10113 return RTN(ctx)
10114 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10115 return RTP(ctx)
10116 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10117 return RNE(ctx)
10118 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10119 return RNA(ctx)
10120
10121
10122_ROUNDING_MODES = frozenset({
10123 Z3_OP_FPA_RM_TOWARD_ZERO,
10124 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10125 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10126 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10127 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10128})
10129
10130
10131def set_default_rounding_mode(rm, ctx=None):
10132 global _dflt_rounding_mode
10133 if is_fprm_value(rm):
10134 _dflt_rounding_mode = rm.kind()
10135 else:
10136 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10137 _dflt_rounding_mode = rm
10138
10139
10140def get_default_fp_sort(ctx=None):
10141 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10142
10143
10144def set_default_fp_sort(ebits, sbits, ctx=None):
10145 global _dflt_fpsort_ebits
10146 global _dflt_fpsort_sbits
10147 _dflt_fpsort_ebits = ebits
10148 _dflt_fpsort_sbits = sbits
10149
10150
10151def _dflt_rm(ctx=None):
10152 return get_default_rounding_mode(ctx)
10153
10154
10155def _dflt_fps(ctx=None):
10156 return get_default_fp_sort(ctx)
10157
10158
10159def _coerce_fp_expr_list(alist, ctx):
10160 first_fp_sort = None
10161 for a in alist:
10162 if is_fp(a):
10163 if first_fp_sort is None:
10164 first_fp_sort = a.sort()
10165 elif first_fp_sort == a.sort():
10166 pass # OK, same as before
10167 else:
10168 # we saw at least 2 different float sorts; something will
10169 # throw a sort mismatch later, for now assume None.
10170 first_fp_sort = None
10171 break
10172
10173 r = []
10174 for i in range(len(alist)):
10175 a = alist[i]
10176 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10177 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10178 r.append(FPVal(a, None, first_fp_sort, ctx))
10179 else:
10180 r.append(a)
10181 return _coerce_expr_list(r, ctx)
10182
10183
10184# FP Sorts
10185
10186class FPSortRef(SortRef):
10187 """Floating-point sort."""
10188
10189 def ebits(self):
10190 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10191 >>> b = FPSort(8, 24)
10192 >>> b.ebits()
10193 8
10194 """
10195 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10196
10197 def sbits(self):
10198 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10199 >>> b = FPSort(8, 24)
10200 >>> b.sbits()
10201 24
10202 """
10203 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10204
10205 def cast(self, val):
10206 """Try to cast `val` as a floating-point expression.
10207 >>> b = FPSort(8, 24)
10208 >>> b.cast(1.0)
10209 1
10210 >>> b.cast(1.0).sexpr()
10211 '(fp #b0 #x7f #b00000000000000000000000)'
10212 """
10213 if is_expr(val):
10214 if z3_debug():
10215 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10216 return val
10217 else:
10218 return FPVal(val, None, self, self.ctx)
10219
10220
10221def Float16(ctx=None):
10222 """Floating-point 16-bit (half) sort."""
10223 ctx = _get_ctx(ctx)
10224 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10225
10226
10227def FloatHalf(ctx=None):
10228 """Floating-point 16-bit (half) sort."""
10229 ctx = _get_ctx(ctx)
10230 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10231
10232
10233def Float32(ctx=None):
10234 """Floating-point 32-bit (single) sort."""
10235 ctx = _get_ctx(ctx)
10236 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10237
10238
10239def FloatSingle(ctx=None):
10240 """Floating-point 32-bit (single) sort."""
10241 ctx = _get_ctx(ctx)
10242 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10243
10244
10245def Float64(ctx=None):
10246 """Floating-point 64-bit (double) sort."""
10247 ctx = _get_ctx(ctx)
10248 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10249
10250
10251def FloatDouble(ctx=None):
10252 """Floating-point 64-bit (double) sort."""
10253 ctx = _get_ctx(ctx)
10254 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10255
10256
10257def Float128(ctx=None):
10258 """Floating-point 128-bit (quadruple) sort."""
10259 ctx = _get_ctx(ctx)
10260 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10261
10262
10263def FloatQuadruple(ctx=None):
10264 """Floating-point 128-bit (quadruple) sort."""
10265 ctx = _get_ctx(ctx)
10266 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10267
10268
10269class FPRMSortRef(SortRef):
10270 """"Floating-point rounding mode sort."""
10271
10272
10273def is_fp_sort(s):
10274 """Return True if `s` is a Z3 floating-point sort.
10275
10276 >>> is_fp_sort(FPSort(8, 24))
10277 True
10278 >>> is_fp_sort(IntSort())
10279 False
10280 """
10281 return isinstance(s, FPSortRef)
10282
10283
10284def is_fprm_sort(s):
10285 """Return True if `s` is a Z3 floating-point rounding mode sort.
10286
10287 >>> is_fprm_sort(FPSort(8, 24))
10288 False
10289 >>> is_fprm_sort(RNE().sort())
10290 True
10291 """
10292 return isinstance(s, FPRMSortRef)
10293
10294# FP Expressions
10295
10296
10297class FPRef(ExprRef):
10298 """Floating-point expressions."""
10299
10300 def sort(self):
10301 """Return the sort of the floating-point expression `self`.
10302
10303 >>> x = FP('1.0', FPSort(8, 24))
10304 >>> x.sort()
10305 FPSort(8, 24)
10306 >>> x.sort() == FPSort(8, 24)
10307 True
10308 """
10309 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10310
10311 def ebits(self):
10312 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10313 >>> b = FPSort(8, 24)
10314 >>> b.ebits()
10315 8
10316 """
10317 return self.sort().ebits()
10318
10319 def sbits(self):
10320 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10321 >>> b = FPSort(8, 24)
10322 >>> b.sbits()
10323 24
10324 """
10325 return self.sort().sbits()
10326
10327 def as_string(self):
10328 """Return a Z3 floating point expression as a Python string."""
10329 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10330
10331 def __le__(self, other):
10332 return fpLEQ(self, other, self.ctx)
10333
10334 def __lt__(self, other):
10335 return fpLT(self, other, self.ctx)
10336
10337 def __ge__(self, other):
10338 return fpGEQ(self, other, self.ctx)
10339
10340 def __gt__(self, other):
10341 return fpGT(self, other, self.ctx)
10342
10343 def __add__(self, other):
10344 """Create the Z3 expression `self + other`.
10345
10346 >>> x = FP('x', FPSort(8, 24))
10347 >>> y = FP('y', FPSort(8, 24))
10348 >>> x + y
10349 x + y
10350 >>> (x + y).sort()
10351 FPSort(8, 24)
10352 """
10353 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10354 return fpAdd(_dflt_rm(), a, b, self.ctx)
10355
10356 def __radd__(self, other):
10357 """Create the Z3 expression `other + self`.
10358
10359 >>> x = FP('x', FPSort(8, 24))
10360 >>> 10 + x
10361 1.25*(2**3) + x
10362 """
10363 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10364 return fpAdd(_dflt_rm(), a, b, self.ctx)
10365
10366 def __sub__(self, other):
10367 """Create the Z3 expression `self - other`.
10368
10369 >>> x = FP('x', FPSort(8, 24))
10370 >>> y = FP('y', FPSort(8, 24))
10371 >>> x - y
10372 x - y
10373 >>> (x - y).sort()
10374 FPSort(8, 24)
10375 """
10376 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10377 return fpSub(_dflt_rm(), a, b, self.ctx)
10378
10379 def __rsub__(self, other):
10380 """Create the Z3 expression `other - self`.
10381
10382 >>> x = FP('x', FPSort(8, 24))
10383 >>> 10 - x
10384 1.25*(2**3) - x
10385 """
10386 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10387 return fpSub(_dflt_rm(), a, b, self.ctx)
10388
10389 def __mul__(self, other):
10390 """Create the Z3 expression `self * other`.
10391
10392 >>> x = FP('x', FPSort(8, 24))
10393 >>> y = FP('y', FPSort(8, 24))
10394 >>> x * y
10395 x * y
10396 >>> (x * y).sort()
10397 FPSort(8, 24)
10398 >>> 10 * y
10399 1.25*(2**3) * y
10400 """
10401 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10402 return fpMul(_dflt_rm(), a, b, self.ctx)
10403
10404 def __rmul__(self, other):
10405 """Create the Z3 expression `other * self`.
10406
10407 >>> x = FP('x', FPSort(8, 24))
10408 >>> y = FP('y', FPSort(8, 24))
10409 >>> x * y
10410 x * y
10411 >>> x * 10
10412 x * 1.25*(2**3)
10413 """
10414 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10415 return fpMul(_dflt_rm(), a, b, self.ctx)
10416
10417 def __pos__(self):
10418 """Create the Z3 expression `+self`."""
10419 return self
10420
10421 def __neg__(self):
10422 """Create the Z3 expression `-self`.
10423
10424 >>> x = FP('x', Float32())
10425 >>> -x
10426 -x
10427 """
10428 return fpNeg(self)
10429
10430 def __div__(self, other):
10431 """Create the Z3 expression `self / other`.
10432
10433 >>> x = FP('x', FPSort(8, 24))
10434 >>> y = FP('y', FPSort(8, 24))
10435 >>> x / y
10436 x / y
10437 >>> (x / y).sort()
10438 FPSort(8, 24)
10439 >>> 10 / y
10440 1.25*(2**3) / y
10441 """
10442 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10443 return fpDiv(_dflt_rm(), a, b, self.ctx)
10444
10445 def __rdiv__(self, other):
10446 """Create the Z3 expression `other / self`.
10447
10448 >>> x = FP('x', FPSort(8, 24))
10449 >>> y = FP('y', FPSort(8, 24))
10450 >>> x / y
10451 x / y
10452 >>> x / 10
10453 x / 1.25*(2**3)
10454 """
10455 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10456 return fpDiv(_dflt_rm(), a, b, self.ctx)
10457
10458 def __truediv__(self, other):
10459 """Create the Z3 expression division `self / other`."""
10460 return self.__div__(other)
10461
10462 def __rtruediv__(self, other):
10463 """Create the Z3 expression division `other / self`."""
10464 return self.__rdiv__(other)
10465
10466 def __mod__(self, other):
10467 """Create the Z3 expression mod `self % other`."""
10468 return fpRem(self, other)
10469
10470 def __rmod__(self, other):
10471 """Create the Z3 expression mod `other % self`."""
10472 return fpRem(other, self)
10473
10474
10475class FPRMRef(ExprRef):
10476 """Floating-point rounding mode expressions"""
10477
10478 def as_string(self):
10479 """Return a Z3 floating point expression as a Python string."""
10480 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10481
10482
10483def RoundNearestTiesToEven(ctx=None):
10484 ctx = _get_ctx(ctx)
10485 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10486
10487
10488def RNE(ctx=None):
10489 ctx = _get_ctx(ctx)
10490 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10491
10492
10493def RoundNearestTiesToAway(ctx=None):
10494 ctx = _get_ctx(ctx)
10495 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10496
10497
10498def RNA(ctx=None):
10499 ctx = _get_ctx(ctx)
10500 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10501
10502
10503def RoundTowardPositive(ctx=None):
10504 ctx = _get_ctx(ctx)
10505 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10506
10507
10508def RTP(ctx=None):
10509 ctx = _get_ctx(ctx)
10510 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10511
10512
10513def RoundTowardNegative(ctx=None):
10514 ctx = _get_ctx(ctx)
10515 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10516
10517
10518def RTN(ctx=None):
10519 ctx = _get_ctx(ctx)
10520 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10521
10522
10523def RoundTowardZero(ctx=None):
10524 ctx = _get_ctx(ctx)
10525 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10526
10527
10528def RTZ(ctx=None):
10529 ctx = _get_ctx(ctx)
10530 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10531
10532
10533def is_fprm(a):
10534 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10535
10536 >>> rm = RNE()
10537 >>> is_fprm(rm)
10538 True
10539 >>> rm = 1.0
10540 >>> is_fprm(rm)
10541 False
10542 """
10543 return isinstance(a, FPRMRef)
10544
10545
10546def is_fprm_value(a):
10547 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10548 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10549
10550# FP Numerals
10551
10552
10553class FPNumRef(FPRef):
10554 """The sign of the numeral.
10555
10556 >>> x = FPVal(+1.0, FPSort(8, 24))
10557 >>> x.sign()
10558 False
10559 >>> x = FPVal(-1.0, FPSort(8, 24))
10560 >>> x.sign()
10561 True
10562 """
10563
10564 def sign(self):
10565 num = ctypes.c_bool()
10566 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10567 if nsign is False:
10568 raise Z3Exception("error retrieving the sign of a numeral.")
10569 return num.value != 0
10570
10571 """The sign of a floating-point numeral as a bit-vector expression.
10572
10573 Remark: NaN's are invalid arguments.
10574 """
10575
10576 def sign_as_bv(self):
10577 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10578
10579 """The significand of the numeral.
10580
10581 >>> x = FPVal(2.5, FPSort(8, 24))
10582 >>> x.significand()
10583 1.25
10584 """
10585
10586 def significand(self):
10587 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10588
10589 """The significand of the numeral as a long.
10590
10591 >>> x = FPVal(2.5, FPSort(8, 24))
10592 >>> x.significand_as_long()
10593 1.25
10594 """
10595
10596 def significand_as_long(self):
10597 ptr = (ctypes.c_ulonglong * 1)()
10598 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10599 raise Z3Exception("error retrieving the significand of a numeral.")
10600 return ptr[0]
10601
10602 """The significand of the numeral as a bit-vector expression.
10603
10604 Remark: NaN are invalid arguments.
10605 """
10606
10607 def significand_as_bv(self):
10608 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10609
10610 """The exponent of the numeral.
10611
10612 >>> x = FPVal(2.5, FPSort(8, 24))
10613 >>> x.exponent()
10614 1
10615 """
10616
10617 def exponent(self, biased=True):
10618 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10619
10620 """The exponent of the numeral as a long.
10621
10622 >>> x = FPVal(2.5, FPSort(8, 24))
10623 >>> x.exponent_as_long()
10624 1
10625 """
10626
10627 def exponent_as_long(self, biased=True):
10628 ptr = (ctypes.c_longlong * 1)()
10629 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10630 raise Z3Exception("error retrieving the exponent of a numeral.")
10631 return ptr[0]
10632
10633 """The exponent of the numeral as a bit-vector expression.
10634
10635 Remark: NaNs are invalid arguments.
10636 """
10637
10638 def exponent_as_bv(self, biased=True):
10639 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10640
10641 """Indicates whether the numeral is a NaN."""
10642
10643 def isNaN(self):
10644 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10645
10646 """Indicates whether the numeral is +oo or -oo."""
10647
10648 def isInf(self):
10649 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10650
10651 """Indicates whether the numeral is +zero or -zero."""
10652
10653 def isZero(self):
10654 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10655
10656 """Indicates whether the numeral is normal."""
10657
10658 def isNormal(self):
10659 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10660
10661 """Indicates whether the numeral is subnormal."""
10662
10663 def isSubnormal(self):
10664 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10665
10666 """Indicates whether the numeral is positive."""
10667
10668 def isPositive(self):
10669 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10670
10671 """Indicates whether the numeral is negative."""
10672
10673 def isNegative(self):
10674 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10675
10676 """
10677 The string representation of the numeral.
10678
10679 >>> x = FPVal(20, FPSort(8, 24))
10680 >>> x.as_string()
10681 1.25*(2**4)
10682 """
10683
10684 def as_string(self):
10685 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10686 return ("FPVal(%s, %s)" % (s, self.sort()))
10687
10688 def py_value(self):
10689 bv = simplify(fpToIEEEBV(self))
10690 binary = bv.py_value()
10691 if not isinstance(binary, int):
10692 return None
10693 # Decode the IEEE 754 binary representation
10694 import struct
10695 bytes_rep = binary.to_bytes(8, byteorder='big')
10696 return struct.unpack('>d', bytes_rep)[0]
10697
10698
10699def is_fp(a):
10700 """Return `True` if `a` is a Z3 floating-point expression.
10701
10702 >>> b = FP('b', FPSort(8, 24))
10703 >>> is_fp(b)
10704 True
10705 >>> is_fp(b + 1.0)
10706 True
10707 >>> is_fp(Int('x'))
10708 False
10709 """
10710 return isinstance(a, FPRef)
10711
10712
10713def is_fp_value(a):
10714 """Return `True` if `a` is a Z3 floating-point numeral value.
10715
10716 >>> b = FP('b', FPSort(8, 24))
10717 >>> is_fp_value(b)
10718 False
10719 >>> b = FPVal(1.0, FPSort(8, 24))
10720 >>> b
10721 1
10722 >>> is_fp_value(b)
10723 True
10724 """
10725 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10726
10727
10728def FPSort(ebits, sbits, ctx=None):
10729 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10730
10731 >>> Single = FPSort(8, 24)
10732 >>> Double = FPSort(11, 53)
10733 >>> Single
10734 FPSort(8, 24)
10735 >>> x = Const('x', Single)
10736 >>> eq(x, FP('x', FPSort(8, 24)))
10737 True
10738 """
10739 ctx = _get_ctx(ctx)
10740 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10741
10742
10743def _to_float_str(val, exp=0):
10744 if isinstance(val, float):
10745 if math.isnan(val):
10746 res = "NaN"
10747 elif val == 0.0:
10748 sone = math.copysign(1.0, val)
10749 if sone < 0.0:
10750 return "-0.0"
10751 else:
10752 return "+0.0"
10753 elif val == float("+inf"):
10754 res = "+oo"
10755 elif val == float("-inf"):
10756 res = "-oo"
10757 else:
10758 v = val.as_integer_ratio()
10759 num = v[0]
10760 den = v[1]
10761 rvs = str(num) + "/" + str(den)
10762 res = rvs + "p" + _to_int_str(exp)
10763 elif isinstance(val, bool):
10764 if val:
10765 res = "1.0"
10766 else:
10767 res = "0.0"
10768 elif _is_int(val):
10769 res = str(val)
10770 elif isinstance(val, str):
10771 inx = val.find("*(2**")
10772 if inx == -1:
10773 res = val
10774 elif val[-1] == ")":
10775 res = val[0:inx]
10776 exp = str(int(val[inx + 5:-1]) + int(exp))
10777 else:
10778 _z3_assert(False, "String does not have floating-point numeral form.")
10779 elif z3_debug():
10780 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10781 if exp == 0:
10782 return res
10783 else:
10784 return res + "p" + exp
10785
10786
10787def fpNaN(s):
10788 """Create a Z3 floating-point NaN term.
10789
10790 >>> s = FPSort(8, 24)
10791 >>> set_fpa_pretty(True)
10792 >>> fpNaN(s)
10793 NaN
10794 >>> pb = get_fpa_pretty()
10795 >>> set_fpa_pretty(False)
10796 >>> fpNaN(s)
10797 fpNaN(FPSort(8, 24))
10798 >>> set_fpa_pretty(pb)
10799 """
10800 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10801 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10802
10803
10804def fpPlusInfinity(s):
10805 """Create a Z3 floating-point +oo term.
10806
10807 >>> s = FPSort(8, 24)
10808 >>> pb = get_fpa_pretty()
10809 >>> set_fpa_pretty(True)
10810 >>> fpPlusInfinity(s)
10811 +oo
10812 >>> set_fpa_pretty(False)
10813 >>> fpPlusInfinity(s)
10814 fpPlusInfinity(FPSort(8, 24))
10815 >>> set_fpa_pretty(pb)
10816 """
10817 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10818 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10819
10820
10821def fpMinusInfinity(s):
10822 """Create a Z3 floating-point -oo term."""
10823 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10824 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10825
10826
10827def fpInfinity(s, negative):
10828 """Create a Z3 floating-point +oo or -oo term."""
10829 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10830 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10831 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10832
10833
10834def fpPlusZero(s):
10835 """Create a Z3 floating-point +0.0 term."""
10836 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10837 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10838
10839
10840def fpMinusZero(s):
10841 """Create a Z3 floating-point -0.0 term."""
10842 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10843 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10844
10845
10846def fpZero(s, negative):
10847 """Create a Z3 floating-point +0.0 or -0.0 term."""
10848 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10849 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10850 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10851
10852
10853def FPVal(sig, exp=None, fps=None, ctx=None):
10854 """Return a floating-point value of value `val` and sort `fps`.
10855 If `ctx=None`, then the global context is used.
10856
10857 >>> v = FPVal(20.0, FPSort(8, 24))
10858 >>> v
10859 1.25*(2**4)
10860 >>> print("0x%.8x" % v.exponent_as_long(False))
10861 0x00000004
10862 >>> v = FPVal(2.25, FPSort(8, 24))
10863 >>> v
10864 1.125*(2**1)
10865 >>> v = FPVal(-2.25, FPSort(8, 24))
10866 >>> v
10867 -1.125*(2**1)
10868 >>> FPVal(-0.0, FPSort(8, 24))
10869 -0.0
10870 >>> FPVal(0.0, FPSort(8, 24))
10871 +0.0
10872 >>> FPVal(+0.0, FPSort(8, 24))
10873 +0.0
10874 """
10875 ctx = _get_ctx(ctx)
10876 if is_fp_sort(exp):
10877 fps = exp
10878 exp = None
10879 elif fps is None:
10880 fps = _dflt_fps(ctx)
10881 _z3_assert(is_fp_sort(fps), "sort mismatch")
10882 if exp is None:
10883 exp = 0
10884 val = _to_float_str(sig)
10885 if val == "NaN" or val == "nan":
10886 return fpNaN(fps)
10887 elif val == "-0.0":
10888 return fpMinusZero(fps)
10889 elif val == "0.0" or val == "+0.0":
10890 return fpPlusZero(fps)
10891 elif val == "+oo" or val == "+inf" or val == "+Inf":
10892 return fpPlusInfinity(fps)
10893 elif val == "-oo" or val == "-inf" or val == "-Inf":
10894 return fpMinusInfinity(fps)
10895 else:
10896 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10897
10898
10899def FP(name, fpsort, ctx=None):
10900 """Return a floating-point constant named `name`.
10901 `fpsort` is the floating-point sort.
10902 If `ctx=None`, then the global context is used.
10903
10904 >>> x = FP('x', FPSort(8, 24))
10905 >>> is_fp(x)
10906 True
10907 >>> x.ebits()
10908 8
10909 >>> x.sort()
10910 FPSort(8, 24)
10911 >>> word = FPSort(8, 24)
10912 >>> x2 = FP('x', word)
10913 >>> eq(x, x2)
10914 True
10915 """
10916 if isinstance(fpsort, FPSortRef) and ctx is None:
10917 ctx = fpsort.ctx
10918 else:
10919 ctx = _get_ctx(ctx)
10920 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10921
10922
10923def FPs(names, fpsort, ctx=None):
10924 """Return an array of floating-point constants.
10925
10926 >>> x, y, z = FPs('x y z', FPSort(8, 24))
10927 >>> x.sort()
10928 FPSort(8, 24)
10929 >>> x.sbits()
10930 24
10931 >>> x.ebits()
10932 8
10933 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10934 (x + y) * z
10935 """
10936 ctx = _get_ctx(ctx)
10937 if isinstance(names, str):
10938 names = names.split(" ")
10939 return [FP(name, fpsort, ctx) for name in names]
10940
10941
10942def fpAbs(a, ctx=None):
10943 """Create a Z3 floating-point absolute value expression.
10944
10945 >>> s = FPSort(8, 24)
10946 >>> rm = RNE()
10947 >>> x = FPVal(1.0, s)
10948 >>> fpAbs(x)
10949 fpAbs(1)
10950 >>> y = FPVal(-20.0, s)
10951 >>> y
10952 -1.25*(2**4)
10953 >>> fpAbs(y)
10954 fpAbs(-1.25*(2**4))
10955 >>> fpAbs(-1.25*(2**4))
10956 fpAbs(-1.25*(2**4))
10957 >>> fpAbs(x).sort()
10958 FPSort(8, 24)
10959 """
10960 ctx = _get_ctx(ctx)
10961 [a] = _coerce_fp_expr_list([a], ctx)
10962 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10963
10964
10965def fpNeg(a, ctx=None):
10966 """Create a Z3 floating-point addition expression.
10967
10968 >>> s = FPSort(8, 24)
10969 >>> rm = RNE()
10970 >>> x = FP('x', s)
10971 >>> fpNeg(x)
10972 -x
10973 >>> fpNeg(x).sort()
10974 FPSort(8, 24)
10975 """
10976 ctx = _get_ctx(ctx)
10977 [a] = _coerce_fp_expr_list([a], ctx)
10978 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10979
10980
10981def _mk_fp_unary(f, rm, a, ctx):
10982 ctx = _get_ctx(ctx)
10983 [a] = _coerce_fp_expr_list([a], ctx)
10984 if z3_debug():
10985 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10986 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10987 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10988
10989
10990def _mk_fp_unary_pred(f, a, ctx):
10991 ctx = _get_ctx(ctx)
10992 [a] = _coerce_fp_expr_list([a], ctx)
10993 if z3_debug():
10994 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10995 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10996
10997
10998def _mk_fp_bin(f, rm, a, b, ctx):
10999 ctx = _get_ctx(ctx)
11000 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11001 if z3_debug():
11002 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11003 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
11004 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
11005
11006
11007def _mk_fp_bin_norm(f, a, b, ctx):
11008 ctx = _get_ctx(ctx)
11009 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11010 if z3_debug():
11011 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11012 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11013
11014
11015def _mk_fp_bin_pred(f, a, b, ctx):
11016 ctx = _get_ctx(ctx)
11017 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11018 if z3_debug():
11019 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11020 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11021
11022
11023def _mk_fp_tern(f, rm, a, b, c, ctx):
11024 ctx = _get_ctx(ctx)
11025 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11026 if z3_debug():
11027 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11028 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11029 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11030 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11031
11032
11033def fpAdd(rm, a, b, ctx=None):
11034 """Create a Z3 floating-point addition expression.
11035
11036 >>> s = FPSort(8, 24)
11037 >>> rm = RNE()
11038 >>> x = FP('x', s)
11039 >>> y = FP('y', s)
11040 >>> fpAdd(rm, x, y)
11041 x + y
11042 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11043 fpAdd(RTZ(), x, y)
11044 >>> fpAdd(rm, x, y).sort()
11045 FPSort(8, 24)
11046 """
11047 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11048
11049
11050def fpSub(rm, a, b, ctx=None):
11051 """Create a Z3 floating-point subtraction expression.
11052
11053 >>> s = FPSort(8, 24)
11054 >>> rm = RNE()
11055 >>> x = FP('x', s)
11056 >>> y = FP('y', s)
11057 >>> fpSub(rm, x, y)
11058 x - y
11059 >>> fpSub(rm, x, y).sort()
11060 FPSort(8, 24)
11061 """
11062 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11063
11064
11065def fpMul(rm, a, b, ctx=None):
11066 """Create a Z3 floating-point multiplication expression.
11067
11068 >>> s = FPSort(8, 24)
11069 >>> rm = RNE()
11070 >>> x = FP('x', s)
11071 >>> y = FP('y', s)
11072 >>> fpMul(rm, x, y)
11073 x * y
11074 >>> fpMul(rm, x, y).sort()
11075 FPSort(8, 24)
11076 """
11077 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11078
11079
11080def fpDiv(rm, a, b, ctx=None):
11081 """Create a Z3 floating-point division expression.
11082
11083 >>> s = FPSort(8, 24)
11084 >>> rm = RNE()
11085 >>> x = FP('x', s)
11086 >>> y = FP('y', s)
11087 >>> fpDiv(rm, x, y)
11088 x / y
11089 >>> fpDiv(rm, x, y).sort()
11090 FPSort(8, 24)
11091 """
11092 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11093
11094
11095def fpRem(a, b, ctx=None):
11096 """Create a Z3 floating-point remainder expression.
11097
11098 >>> s = FPSort(8, 24)
11099 >>> x = FP('x', s)
11100 >>> y = FP('y', s)
11101 >>> fpRem(x, y)
11102 fpRem(x, y)
11103 >>> fpRem(x, y).sort()
11104 FPSort(8, 24)
11105 """
11106 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11107
11108
11109def fpMin(a, b, ctx=None):
11110 """Create a Z3 floating-point minimum expression.
11111
11112 >>> s = FPSort(8, 24)
11113 >>> rm = RNE()
11114 >>> x = FP('x', s)
11115 >>> y = FP('y', s)
11116 >>> fpMin(x, y)
11117 fpMin(x, y)
11118 >>> fpMin(x, y).sort()
11119 FPSort(8, 24)
11120 """
11121 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11122
11123
11124def fpMax(a, b, ctx=None):
11125 """Create a Z3 floating-point maximum expression.
11126
11127 >>> s = FPSort(8, 24)
11128 >>> rm = RNE()
11129 >>> x = FP('x', s)
11130 >>> y = FP('y', s)
11131 >>> fpMax(x, y)
11132 fpMax(x, y)
11133 >>> fpMax(x, y).sort()
11134 FPSort(8, 24)
11135 """
11136 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11137
11138
11139def fpFMA(rm, a, b, c, ctx=None):
11140 """Create a Z3 floating-point fused multiply-add expression.
11141 """
11142 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11143
11144
11145def fpSqrt(rm, a, ctx=None):
11146 """Create a Z3 floating-point square root expression.
11147 """
11148 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11149
11150
11151def fpRoundToIntegral(rm, a, ctx=None):
11152 """Create a Z3 floating-point roundToIntegral expression.
11153 """
11154 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11155
11156
11157def fpIsNaN(a, ctx=None):
11158 """Create a Z3 floating-point isNaN expression.
11159
11160 >>> s = FPSort(8, 24)
11161 >>> x = FP('x', s)
11162 >>> y = FP('y', s)
11163 >>> fpIsNaN(x)
11164 fpIsNaN(x)
11165 """
11166 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11167
11168
11169def fpIsInf(a, ctx=None):
11170 """Create a Z3 floating-point isInfinite expression.
11171
11172 >>> s = FPSort(8, 24)
11173 >>> x = FP('x', s)
11174 >>> fpIsInf(x)
11175 fpIsInf(x)
11176 """
11177 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11178
11179
11180def fpIsZero(a, ctx=None):
11181 """Create a Z3 floating-point isZero expression.
11182 """
11183 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11184
11185
11186def fpIsNormal(a, ctx=None):
11187 """Create a Z3 floating-point isNormal expression.
11188 """
11189 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11190
11191
11192def fpIsSubnormal(a, ctx=None):
11193 """Create a Z3 floating-point isSubnormal expression.
11194 """
11195 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11196
11197
11198def fpIsNegative(a, ctx=None):
11199 """Create a Z3 floating-point isNegative expression.
11200 """
11201 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11202
11203
11204def fpIsPositive(a, ctx=None):
11205 """Create a Z3 floating-point isPositive expression.
11206 """
11207 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11208
11209
11210def _check_fp_args(a, b):
11211 if z3_debug():
11212 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11213
11214
11215def fpLT(a, b, ctx=None):
11216 """Create the Z3 floating-point expression `other < self`.
11217
11218 >>> x, y = FPs('x y', FPSort(8, 24))
11219 >>> fpLT(x, y)
11220 x < y
11221 >>> (x < y).sexpr()
11222 '(fp.lt x y)'
11223 """
11224 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11225
11226
11227def fpLEQ(a, b, ctx=None):
11228 """Create the Z3 floating-point expression `other <= self`.
11229
11230 >>> x, y = FPs('x y', FPSort(8, 24))
11231 >>> fpLEQ(x, y)
11232 x <= y
11233 >>> (x <= y).sexpr()
11234 '(fp.leq x y)'
11235 """
11236 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11237
11238
11239def fpGT(a, b, ctx=None):
11240 """Create the Z3 floating-point expression `other > self`.
11241
11242 >>> x, y = FPs('x y', FPSort(8, 24))
11243 >>> fpGT(x, y)
11244 x > y
11245 >>> (x > y).sexpr()
11246 '(fp.gt x y)'
11247 """
11248 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11249
11250
11251def fpGEQ(a, b, ctx=None):
11252 """Create the Z3 floating-point expression `other >= self`.
11253
11254 >>> x, y = FPs('x y', FPSort(8, 24))
11255 >>> fpGEQ(x, y)
11256 x >= y
11257 >>> (x >= y).sexpr()
11258 '(fp.geq x y)'
11259 """
11260 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11261
11262
11263def fpEQ(a, b, ctx=None):
11264 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11265
11266 >>> x, y = FPs('x y', FPSort(8, 24))
11267 >>> fpEQ(x, y)
11268 fpEQ(x, y)
11269 >>> fpEQ(x, y).sexpr()
11270 '(fp.eq x y)'
11271 """
11272 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11273
11274
11275def fpNEQ(a, b, ctx=None):
11276 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11277
11278 >>> x, y = FPs('x y', FPSort(8, 24))
11279 >>> fpNEQ(x, y)
11280 Not(fpEQ(x, y))
11281 >>> (x != y).sexpr()
11282 '(distinct x y)'
11283 """
11284 return Not(fpEQ(a, b, ctx))
11285
11286
11287def fpFP(sgn, exp, sig, ctx=None):
11288 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11289
11290 >>> s = FPSort(8, 24)
11291 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11292 >>> print(x)
11293 fpFP(1, 127, 4194304)
11294 >>> xv = FPVal(-1.5, s)
11295 >>> print(xv)
11296 -1.5
11297 >>> slvr = Solver()
11298 >>> slvr.add(fpEQ(x, xv))
11299 >>> slvr.check()
11300 sat
11301 >>> xv = FPVal(+1.5, s)
11302 >>> print(xv)
11303 1.5
11304 >>> slvr = Solver()
11305 >>> slvr.add(fpEQ(x, xv))
11306 >>> slvr.check()
11307 unsat
11308 """
11309 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11310 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11311 ctx = _get_ctx(ctx)
11312 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11313 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11314
11315
11316def fpToFP(a1, a2=None, a3=None, ctx=None):
11317 """Create a Z3 floating-point conversion expression from other term sorts
11318 to floating-point.
11319
11320 From a bit-vector term in IEEE 754-2008 format:
11321 >>> x = FPVal(1.0, Float32())
11322 >>> x_bv = fpToIEEEBV(x)
11323 >>> simplify(fpToFP(x_bv, Float32()))
11324 1
11325
11326 From a floating-point term with different precision:
11327 >>> x = FPVal(1.0, Float32())
11328 >>> x_db = fpToFP(RNE(), x, Float64())
11329 >>> x_db.sort()
11330 FPSort(11, 53)
11331
11332 From a real term:
11333 >>> x_r = RealVal(1.5)
11334 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11335 1.5
11336
11337 From a signed bit-vector term:
11338 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11339 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11340 -1.25*(2**2)
11341 """
11342 ctx = _get_ctx(ctx)
11343 if is_bv(a1) and is_fp_sort(a2):
11344 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11345 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11346 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11347 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11348 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11349 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11350 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11351 else:
11352 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11353
11354
11355def fpBVToFP(v, sort, ctx=None):
11356 """Create a Z3 floating-point conversion expression that represents the
11357 conversion from a bit-vector term to a floating-point term.
11358
11359 >>> x_bv = BitVecVal(0x3F800000, 32)
11360 >>> x_fp = fpBVToFP(x_bv, Float32())
11361 >>> x_fp
11362 fpToFP(1065353216)
11363 >>> simplify(x_fp)
11364 1
11365 """
11366 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11367 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11368 ctx = _get_ctx(ctx)
11369 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11370
11371
11372def fpFPToFP(rm, v, sort, ctx=None):
11373 """Create a Z3 floating-point conversion expression that represents the
11374 conversion from a floating-point term to a floating-point term of different precision.
11375
11376 >>> x_sgl = FPVal(1.0, Float32())
11377 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11378 >>> x_dbl
11379 fpToFP(RNE(), 1)
11380 >>> simplify(x_dbl)
11381 1
11382 >>> x_dbl.sort()
11383 FPSort(11, 53)
11384 """
11385 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11386 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11387 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11388 ctx = _get_ctx(ctx)
11389 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11390
11391
11392def fpRealToFP(rm, v, sort, ctx=None):
11393 """Create a Z3 floating-point conversion expression that represents the
11394 conversion from a real term to a floating-point term.
11395
11396 >>> x_r = RealVal(1.5)
11397 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11398 >>> x_fp
11399 fpToFP(RNE(), 3/2)
11400 >>> simplify(x_fp)
11401 1.5
11402 """
11403 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11404 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11405 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11406 ctx = _get_ctx(ctx)
11407 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11408
11409
11410def fpSignedToFP(rm, v, sort, ctx=None):
11411 """Create a Z3 floating-point conversion expression that represents the
11412 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11413
11414 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11415 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11416 >>> x_fp
11417 fpToFP(RNE(), 4294967291)
11418 >>> simplify(x_fp)
11419 -1.25*(2**2)
11420 """
11421 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11422 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11423 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11424 ctx = _get_ctx(ctx)
11425 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11426
11427
11428def fpUnsignedToFP(rm, v, sort, ctx=None):
11429 """Create a Z3 floating-point conversion expression that represents the
11430 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11431
11432 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11433 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11434 >>> x_fp
11435 fpToFPUnsigned(RNE(), 4294967291)
11436 >>> simplify(x_fp)
11437 1*(2**32)
11438 """
11439 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11440 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11441 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11442 ctx = _get_ctx(ctx)
11443 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11444
11445
11446def fpToFPUnsigned(rm, x, s, ctx=None):
11447 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11448 if z3_debug():
11449 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11450 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11451 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11452 ctx = _get_ctx(ctx)
11453 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11454
11455
11456def fpToSBV(rm, x, s, ctx=None):
11457 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11458
11459 >>> x = FP('x', FPSort(8, 24))
11460 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11461 >>> print(is_fp(x))
11462 True
11463 >>> print(is_bv(y))
11464 True
11465 >>> print(is_fp(y))
11466 False
11467 >>> print(is_bv(x))
11468 False
11469 """
11470 if z3_debug():
11471 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11472 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11473 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11474 ctx = _get_ctx(ctx)
11475 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11476
11477
11478def fpToUBV(rm, x, s, ctx=None):
11479 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11480
11481 >>> x = FP('x', FPSort(8, 24))
11482 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11483 >>> print(is_fp(x))
11484 True
11485 >>> print(is_bv(y))
11486 True
11487 >>> print(is_fp(y))
11488 False
11489 >>> print(is_bv(x))
11490 False
11491 """
11492 if z3_debug():
11493 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11494 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11495 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11496 ctx = _get_ctx(ctx)
11497 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11498
11499
11500def fpToReal(x, ctx=None):
11501 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11502
11503 >>> x = FP('x', FPSort(8, 24))
11504 >>> y = fpToReal(x)
11505 >>> print(is_fp(x))
11506 True
11507 >>> print(is_real(y))
11508 True
11509 >>> print(is_fp(y))
11510 False
11511 >>> print(is_real(x))
11512 False
11513 """
11514 if z3_debug():
11515 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11516 ctx = _get_ctx(ctx)
11517 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11518
11519
11520def fpToIEEEBV(x, ctx=None):
11521 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11522
11523 The size of the resulting bit-vector is automatically determined.
11524
11525 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11526 knows only one NaN and it will always produce the same bit-vector representation of
11527 that NaN.
11528
11529 >>> x = FP('x', FPSort(8, 24))
11530 >>> y = fpToIEEEBV(x)
11531 >>> print(is_fp(x))
11532 True
11533 >>> print(is_bv(y))
11534 True
11535 >>> print(is_fp(y))
11536 False
11537 >>> print(is_bv(x))
11538 False
11539 """
11540 if z3_debug():
11541 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11542 ctx = _get_ctx(ctx)
11543 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11544
11545
11546#########################################
11547#
11548# Strings, Sequences and Regular expressions
11549#
11550#########################################
11551
11552class SeqSortRef(SortRef):
11553 """Sequence sort."""
11554
11555 def is_string(self):
11556 """Determine if sort is a string
11557 >>> s = StringSort()
11558 >>> s.is_string()
11559 True
11560 >>> s = SeqSort(IntSort())
11561 >>> s.is_string()
11562 False
11563 """
11564 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11565
11566 def basis(self):
11567 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11568
11569class CharSortRef(SortRef):
11570 """Character sort."""
11571
11572
11573def StringSort(ctx=None):
11574 """Create a string sort
11575 >>> s = StringSort()
11576 >>> print(s)
11577 String
11578 """
11579 ctx = _get_ctx(ctx)
11580 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11581
11582def CharSort(ctx=None):
11583 """Create a character sort
11584 >>> ch = CharSort()
11585 >>> print(ch)
11586 Char
11587 """
11588 ctx = _get_ctx(ctx)
11589 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11590
11591
11592def SeqSort(s):
11593 """Create a sequence sort over elements provided in the argument
11594 >>> s = SeqSort(IntSort())
11595 >>> s == Unit(IntVal(1)).sort()
11596 True
11597 """
11598 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11599
11600
11601class SeqRef(ExprRef):
11602 """Sequence expression."""
11603
11604 def sort(self):
11605 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11606
11607 def __add__(self, other):
11608 return Concat(self, other)
11609
11610 def __radd__(self, other):
11611 return Concat(other, self)
11612
11613 def __getitem__(self, i):
11614 if _is_int(i):
11615 i = IntVal(i, self.ctx)
11616 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11617
11618 def at(self, i):
11619 if _is_int(i):
11620 i = IntVal(i, self.ctx)
11621 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11622
11623 def is_string(self):
11624 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11625
11626 def is_string_value(self):
11627 return Z3_is_string(self.ctx_ref(), self.as_ast())
11628
11629 def as_string(self):
11630 """Return a string representation of sequence expression."""
11631 if self.is_string_value():
11632 string_length = ctypes.c_uint()
11633 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11634 return string_at(chars, size=string_length.value).decode("latin-1")
11635 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11636
11637 def py_value(self):
11638 return self.as_string()
11639
11640 def __le__(self, other):
11641 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11642
11643 def __lt__(self, other):
11644 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11645
11646 def __ge__(self, other):
11647 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11648
11649 def __gt__(self, other):
11650 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11651
11652
11653def _coerce_char(ch, ctx=None):
11654 if isinstance(ch, str):
11655 ctx = _get_ctx(ctx)
11656 ch = CharVal(ch, ctx)
11657 if not is_expr(ch):
11658 raise Z3Exception("Character expression expected")
11659 return ch
11660
11661class CharRef(ExprRef):
11662 """Character expression."""
11663
11664 def __le__(self, other):
11665 other = _coerce_char(other, self.ctx)
11666 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11667
11668 def to_int(self):
11669 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11670
11671 def to_bv(self):
11672 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11673
11674 def is_digit(self):
11675 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11676
11677
11678def CharVal(ch, ctx=None):
11679 ctx = _get_ctx(ctx)
11680 if isinstance(ch, str):
11681 ch = ord(ch)
11682 if not isinstance(ch, int):
11683 raise Z3Exception("character value should be an ordinal")
11684 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11685
11686def CharFromBv(bv):
11687 if not is_expr(bv):
11688 raise Z3Exception("Bit-vector expression needed")
11689 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11690
11691def CharToBv(ch, ctx=None):
11692 ch = _coerce_char(ch, ctx)
11693 return ch.to_bv()
11694
11695def CharToInt(ch, ctx=None):
11696 ch = _coerce_char(ch, ctx)
11697 return ch.to_int()
11698
11699def CharIsDigit(ch, ctx=None):
11700 ch = _coerce_char(ch, ctx)
11701 return ch.is_digit()
11702
11703def _coerce_seq(s, ctx=None):
11704 if isinstance(s, str):
11705 ctx = _get_ctx(ctx)
11706 s = StringVal(s, ctx)
11707 if not is_expr(s):
11708 raise Z3Exception("Non-expression passed as a sequence")
11709 if not is_seq(s):
11710 raise Z3Exception("Non-sequence passed as a sequence")
11711 return s
11712
11713
11714def _get_ctx2(a, b, ctx=None):
11715 if is_expr(a):
11716 return a.ctx
11717 if is_expr(b):
11718 return b.ctx
11719 if ctx is None:
11720 ctx = main_ctx()
11721 return ctx
11722
11723
11724def is_seq(a):
11725 """Return `True` if `a` is a Z3 sequence expression.
11726 >>> print (is_seq(Unit(IntVal(0))))
11727 True
11728 >>> print (is_seq(StringVal("abc")))
11729 True
11730 """
11731 return isinstance(a, SeqRef)
11732
11733
11734def is_string(a: Any) -> bool:
11735 """Return `True` if `a` is a Z3 string expression.
11736 >>> print (is_string(StringVal("ab")))
11737 True
11738 """
11739 return isinstance(a, SeqRef) and a.is_string()
11740
11741
11742def is_string_value(a: Any) -> bool:
11743 """return 'True' if 'a' is a Z3 string constant expression.
11744 >>> print (is_string_value(StringVal("a")))
11745 True
11746 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11747 False
11748 """
11749 return isinstance(a, SeqRef) and a.is_string_value()
11750
11751def StringVal(s, ctx=None):
11752 """create a string expression"""
11753 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11754 ctx = _get_ctx(ctx)
11755 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11756
11757
11758def String(name, ctx=None):
11759 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11760
11761 >>> x = String('x')
11762 """
11763 ctx = _get_ctx(ctx)
11764 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11765
11766
11767def Strings(names, ctx=None):
11768 """Return a tuple of String constants. """
11769 ctx = _get_ctx(ctx)
11770 if isinstance(names, str):
11771 names = names.split(" ")
11772 return [String(name, ctx) for name in names]
11773
11774
11775def SubString(s, offset, length):
11776 """Extract substring or subsequence starting at offset.
11777
11778 This is a convenience function that redirects to Extract(s, offset, length).
11779
11780 >>> s = StringVal("hello world")
11781 >>> SubString(s, 6, 5) # Extract "world"
11782 str.substr("hello world", 6, 5)
11783 >>> simplify(SubString(StringVal("hello"), 1, 3))
11784 "ell"
11785 """
11786 return Extract(s, offset, length)
11787
11788
11789def SubSeq(s, offset, length):
11790 """Extract substring or subsequence starting at offset.
11791
11792 This is a convenience function that redirects to Extract(s, offset, length).
11793
11794 >>> s = StringVal("hello world")
11795 >>> SubSeq(s, 0, 5) # Extract "hello"
11796 str.substr("hello world", 0, 5)
11797 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11798 "stin"
11799 """
11800 return Extract(s, offset, length)
11801
11802
11803def Empty(s):
11804 """Create the empty sequence of the given sort
11805 >>> e = Empty(StringSort())
11806 >>> e2 = StringVal("")
11807 >>> print(e.eq(e2))
11808 True
11809 >>> e3 = Empty(SeqSort(IntSort()))
11810 >>> print(e3)
11811 Empty(Seq(Int))
11812 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11813 >>> print(e4)
11814 Empty(ReSort(Seq(Int)))
11815 """
11816 if isinstance(s, SeqSortRef):
11817 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11818 if isinstance(s, ReSortRef):
11819 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11820 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11821
11822
11823def Full(s):
11824 """Create the regular expression that accepts the universal language
11825 >>> e = Full(ReSort(SeqSort(IntSort())))
11826 >>> print(e)
11827 Full(ReSort(Seq(Int)))
11828 >>> e1 = Full(ReSort(StringSort()))
11829 >>> print(e1)
11830 Full(ReSort(String))
11831 """
11832 if isinstance(s, ReSortRef):
11833 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11834 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11835
11836
11837
11838def Unit(a):
11839 """Create a singleton sequence"""
11840 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11841
11842
11843def PrefixOf(a, b):
11844 """Check if 'a' is a prefix of 'b'
11845 >>> s1 = PrefixOf("ab", "abc")
11846 >>> simplify(s1)
11847 True
11848 >>> s2 = PrefixOf("bc", "abc")
11849 >>> simplify(s2)
11850 False
11851 """
11852 ctx = _get_ctx2(a, b)
11853 a = _coerce_seq(a, ctx)
11854 b = _coerce_seq(b, ctx)
11855 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11856
11857
11858def SuffixOf(a, b):
11859 """Check if 'a' is a suffix of 'b'
11860 >>> s1 = SuffixOf("ab", "abc")
11861 >>> simplify(s1)
11862 False
11863 >>> s2 = SuffixOf("bc", "abc")
11864 >>> simplify(s2)
11865 True
11866 """
11867 ctx = _get_ctx2(a, b)
11868 a = _coerce_seq(a, ctx)
11869 b = _coerce_seq(b, ctx)
11870 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11871
11872
11873def Contains(a, b):
11874 """Check if 'a' contains 'b'
11875 >>> s1 = Contains("abc", "ab")
11876 >>> simplify(s1)
11877 True
11878 >>> s2 = Contains("abc", "bc")
11879 >>> simplify(s2)
11880 True
11881 >>> x, y, z = Strings('x y z')
11882 >>> s3 = Contains(Concat(x,y,z), y)
11883 >>> simplify(s3)
11884 True
11885 """
11886 ctx = _get_ctx2(a, b)
11887 a = _coerce_seq(a, ctx)
11888 b = _coerce_seq(b, ctx)
11889 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11890
11891
11892def Replace(s, src, dst):
11893 """Replace the first occurrence of 'src' by 'dst' in 's'
11894 >>> r = Replace("aaa", "a", "b")
11895 >>> simplify(r)
11896 "baa"
11897 """
11898 ctx = _get_ctx2(dst, s)
11899 if ctx is None and is_expr(src):
11900 ctx = src.ctx
11901 src = _coerce_seq(src, ctx)
11902 dst = _coerce_seq(dst, ctx)
11903 s = _coerce_seq(s, ctx)
11904 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11905
11906
11907def IndexOf(s, substr, offset=None):
11908 """Retrieve the index of substring within a string starting at a specified offset.
11909 >>> simplify(IndexOf("abcabc", "bc", 0))
11910 1
11911 >>> simplify(IndexOf("abcabc", "bc", 2))
11912 4
11913 """
11914 if offset is None:
11915 offset = IntVal(0)
11916 ctx = None
11917 if is_expr(offset):
11918 ctx = offset.ctx
11919 ctx = _get_ctx2(s, substr, ctx)
11920 s = _coerce_seq(s, ctx)
11921 substr = _coerce_seq(substr, ctx)
11922 if _is_int(offset):
11923 offset = IntVal(offset, ctx)
11924 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11925
11926
11927def LastIndexOf(s, substr):
11928 """Retrieve the last index of substring within a string"""
11929 ctx = None
11930 ctx = _get_ctx2(s, substr, ctx)
11931 s = _coerce_seq(s, ctx)
11932 substr = _coerce_seq(substr, ctx)
11933 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11934
11935
11936def Length(s):
11937 """Obtain the length of a sequence 's'
11938 >>> l = Length(StringVal("abc"))
11939 >>> simplify(l)
11940 3
11941 """
11942 s = _coerce_seq(s)
11943 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11944
11945def SeqMap(f, s):
11946 """Map function 'f' over sequence 's'"""
11947 ctx = _get_ctx2(f, s)
11948 s = _coerce_seq(s, ctx)
11949 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
11950
11951def SeqMapI(f, i, s):
11952 """Map function 'f' over sequence 's' at index 'i'"""
11953 ctx = _get_ctx2(f, s)
11954 s = _coerce_seq(s, ctx)
11955 if not is_expr(i):
11956 i = _py2expr(i)
11957 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
11958
11959def SeqFoldLeft(f, a, s):
11960 ctx = _get_ctx2(f, s)
11961 s = _coerce_seq(s, ctx)
11962 a = _py2expr(a)
11963 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
11964
11965def SeqFoldLeftI(f, i, a, s):
11966 ctx = _get_ctx2(f, s)
11967 s = _coerce_seq(s, ctx)
11968 a = _py2expr(a)
11969 i = _py2expr(i)
11970 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
11971
11972def StrToInt(s):
11973 """Convert string expression to integer
11974 >>> a = StrToInt("1")
11975 >>> simplify(1 == a)
11976 True
11977 >>> b = StrToInt("2")
11978 >>> simplify(1 == b)
11979 False
11980 >>> c = StrToInt(IntToStr(2))
11981 >>> simplify(1 == c)
11982 False
11983 """
11984 s = _coerce_seq(s)
11985 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11986
11987
11988def IntToStr(s):
11989 """Convert integer expression to string"""
11990 if not is_expr(s):
11991 s = _py2expr(s)
11992 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11993
11994
11995def StrToCode(s):
11996 """Convert a unit length string to integer code"""
11997 if not is_expr(s):
11998 s = _py2expr(s)
11999 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
12000
12001def StrFromCode(c):
12002 """Convert code to a string"""
12003 if not is_expr(c):
12004 c = _py2expr(c)
12005 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
12006
12007def Re(s, ctx=None):
12008 """The regular expression that accepts sequence 's'
12009 >>> s1 = Re("ab")
12010 >>> s2 = Re(StringVal("ab"))
12011 >>> s3 = Re(Unit(BoolVal(True)))
12012 """
12013 s = _coerce_seq(s, ctx)
12014 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12015
12016
12017# Regular expressions
12018
12019class ReSortRef(SortRef):
12020 """Regular expression sort."""
12021
12022 def basis(self):
12023 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12024
12025
12026def ReSort(s):
12027 if is_ast(s):
12028 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12029 if s is None or isinstance(s, Context):
12030 ctx = _get_ctx(s)
12031 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12032 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12033
12034
12035class ReRef(ExprRef):
12036 """Regular expressions."""
12037
12038 def __add__(self, other):
12039 return Union(self, other)
12040
12041
12042def is_re(s):
12043 return isinstance(s, ReRef)
12044
12045
12046def InRe(s, re):
12047 """Create regular expression membership test
12048 >>> re = Union(Re("a"),Re("b"))
12049 >>> print (simplify(InRe("a", re)))
12050 True
12051 >>> print (simplify(InRe("b", re)))
12052 True
12053 >>> print (simplify(InRe("c", re)))
12054 False
12055 """
12056 s = _coerce_seq(s, re.ctx)
12057 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12058
12059
12060def Union(*args):
12061 """Create union of regular expressions.
12062 >>> re = Union(Re("a"), Re("b"), Re("c"))
12063 >>> print (simplify(InRe("d", re)))
12064 False
12065 """
12066 args = _get_args(args)
12067 sz = len(args)
12068 if z3_debug():
12069 _z3_assert(sz > 0, "At least one argument expected.")
12070 arg0 = args[0]
12071 if is_finite_set(arg0):
12072 for a in args[1:]:
12073 if not is_finite_set(a):
12074 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12075 arg0 = arg0 | a
12076 return arg0
12077 if z3_debug():
12078 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12079 if sz == 1:
12080 return args[0]
12081 ctx = args[0].ctx
12082 v = (Ast * sz)()
12083 for i in range(sz):
12084 v[i] = args[i].as_ast()
12085 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12086
12087
12088def Intersect(*args):
12089 """Create intersection of regular expressions.
12090 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12091 """
12092 args = _get_args(args)
12093 sz = len(args)
12094 if z3_debug():
12095 _z3_assert(sz > 0, "At least one argument expected.")
12096 arg0 = args[0]
12097 if is_finite_set(arg0):
12098 for a in args[1:]:
12099 if not is_finite_set(a):
12100 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12101 arg0 = arg0 & a
12102 return arg0
12103 if z3_debug():
12104 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12105 if sz == 1:
12106 return args[0]
12107 ctx = args[0].ctx
12108 v = (Ast * sz)()
12109 for i in range(sz):
12110 v[i] = args[i].as_ast()
12111 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12112
12113
12114def Plus(re):
12115 """Create the regular expression accepting one or more repetitions of argument.
12116 >>> re = Plus(Re("a"))
12117 >>> print(simplify(InRe("aa", re)))
12118 True
12119 >>> print(simplify(InRe("ab", re)))
12120 False
12121 >>> print(simplify(InRe("", re)))
12122 False
12123 """
12124 if z3_debug():
12125 _z3_assert(is_expr(re), "expression expected")
12126 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12127
12128
12129def Option(re):
12130 """Create the regular expression that optionally accepts the argument.
12131 >>> re = Option(Re("a"))
12132 >>> print(simplify(InRe("a", re)))
12133 True
12134 >>> print(simplify(InRe("", re)))
12135 True
12136 >>> print(simplify(InRe("aa", re)))
12137 False
12138 """
12139 if z3_debug():
12140 _z3_assert(is_expr(re), "expression expected")
12141 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12142
12143
12144def Complement(re):
12145 """Create the complement regular expression."""
12146 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12147
12148
12149def Star(re):
12150 """Create the regular expression accepting zero or more repetitions of argument.
12151 >>> re = Star(Re("a"))
12152 >>> print(simplify(InRe("aa", re)))
12153 True
12154 >>> print(simplify(InRe("ab", re)))
12155 False
12156 >>> print(simplify(InRe("", re)))
12157 True
12158 """
12159 if z3_debug():
12160 _z3_assert(is_expr(re), "expression expected")
12161 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12162
12163
12164def Loop(re, lo, hi=0):
12165 """Create the regular expression accepting between a lower and upper bound repetitions
12166 >>> re = Loop(Re("a"), 1, 3)
12167 >>> print(simplify(InRe("aa", re)))
12168 True
12169 >>> print(simplify(InRe("aaaa", re)))
12170 False
12171 >>> print(simplify(InRe("", re)))
12172 False
12173 """
12174 if z3_debug():
12175 _z3_assert(is_expr(re), "expression expected")
12176 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12177
12178
12179def Range(lo, hi, ctx=None):
12180 """Create the range regular expression over two sequences of length 1
12181 >>> range = Range("a","z")
12182 >>> print(simplify(InRe("b", range)))
12183 True
12184 >>> print(simplify(InRe("bb", range)))
12185 False
12186 """
12187 lo = _coerce_seq(lo, ctx)
12188 hi = _coerce_seq(hi, ctx)
12189 if z3_debug():
12190 _z3_assert(is_expr(lo), "expression expected")
12191 _z3_assert(is_expr(hi), "expression expected")
12192 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12193
12194def Diff(a, b, ctx=None):
12195 """Create the difference regular expression
12196 """
12197 if z3_debug():
12198 _z3_assert(is_expr(a), "expression expected")
12199 _z3_assert(is_expr(b), "expression expected")
12200 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12201
12202def AllChar(regex_sort, ctx=None):
12203 """Create a regular expression that accepts all single character strings
12204 """
12205 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12206
12207# Special Relations
12208
12209
12210def PartialOrder(a, index):
12211 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12212
12213
12214def LinearOrder(a, index):
12215 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12216
12217
12218def TreeOrder(a, index):
12219 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12220
12221
12222def PiecewiseLinearOrder(a, index):
12223 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12224
12225
12226def TransitiveClosure(f):
12227 """Given a binary relation R, such that the two arguments have the same sort
12228 create the transitive closure relation R+.
12229 The transitive closure R+ is a new relation.
12230 """
12231 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12232
12233def to_Ast(ptr,):
12234 ast = Ast(ptr)
12235 super(ctypes.c_void_p, ast).__init__(ptr)
12236 return ast
12237
12238def to_ContextObj(ptr,):
12239 ctx = ContextObj(ptr)
12240 super(ctypes.c_void_p, ctx).__init__(ptr)
12241 return ctx
12242
12243def to_AstVectorObj(ptr,):
12244 v = AstVectorObj(ptr)
12245 super(ctypes.c_void_p, v).__init__(ptr)
12246 return v
12247
12248# NB. my-hacky-class only works for a single instance of OnClause
12249# it should be replaced with a proper correlation between OnClause
12250# and object references that can be passed over the FFI.
12251# for UserPropagator we use a global dictionary, which isn't great code.
12252
12253_my_hacky_class = None
12254def on_clause_eh(ctx, p, n, dep, clause):
12255 onc = _my_hacky_class
12256 p = _to_expr_ref(to_Ast(p), onc.ctx)
12257 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12258 deps = [dep[i] for i in range(n)]
12259 onc.on_clause(p, deps, clause)
12260
12261_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12262
12263class OnClause:
12264 def __init__(self, s, on_clause):
12265 self.s = s
12266 self.ctx = s.ctx
12267 self.on_clause = on_clause
12268 self.idx = 22
12269 global _my_hacky_class
12270 _my_hacky_class = self
12271 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12272
12273
12274class PropClosures:
12275 def __init__(self):
12276 self.bases = {}
12277 self.lock = None
12278
12279 def set_threaded(self):
12280 if self.lock is None:
12281 import threading
12282 self.lock = threading.Lock()
12283
12284 def get(self, ctx):
12285 if self.lock:
12286 with self.lock:
12287 r = self.bases[ctx]
12288 else:
12289 r = self.bases[ctx]
12290 return r
12291
12292 def set(self, ctx, r):
12293 if self.lock:
12294 with self.lock:
12295 self.bases[ctx] = r
12296 else:
12297 self.bases[ctx] = r
12298
12299 def insert(self, r):
12300 if self.lock:
12301 with self.lock:
12302 id = len(self.bases) + 3
12303 self.bases[id] = r
12304 else:
12305 id = len(self.bases) + 3
12306 self.bases[id] = r
12307 return id
12308
12309
12310_prop_closures = None
12311
12312
12313def ensure_prop_closures():
12314 global _prop_closures
12315 if _prop_closures is None:
12316 _prop_closures = PropClosures()
12317
12318
12319def user_prop_push(ctx, cb):
12320 prop = _prop_closures.get(ctx)
12321 prop.cb = cb
12322 prop.push()
12323
12324
12325def user_prop_pop(ctx, cb, num_scopes):
12326 prop = _prop_closures.get(ctx)
12327 prop.cb = cb
12328 prop.pop(num_scopes)
12329
12330
12331def user_prop_fresh(ctx, _new_ctx):
12332 _prop_closures.set_threaded()
12333 prop = _prop_closures.get(ctx)
12334 nctx = Context()
12335 Z3_del_context(nctx.ctx)
12336 new_ctx = to_ContextObj(_new_ctx)
12337 nctx.ctx = new_ctx
12338 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12339 nctx.owner = False
12340 new_prop = prop.fresh(nctx)
12341 _prop_closures.set(new_prop.id, new_prop)
12342 return new_prop.id
12343
12344
12345def user_prop_fixed(ctx, cb, id, value):
12346 prop = _prop_closures.get(ctx)
12347 old_cb = prop.cb
12348 prop.cb = cb
12349 id = _to_expr_ref(to_Ast(id), prop.ctx())
12350 value = _to_expr_ref(to_Ast(value), prop.ctx())
12351 prop.fixed(id, value)
12352 prop.cb = old_cb
12353
12354def user_prop_created(ctx, cb, id):
12355 prop = _prop_closures.get(ctx)
12356 old_cb = prop.cb
12357 prop.cb = cb
12358 id = _to_expr_ref(to_Ast(id), prop.ctx())
12359 prop.created(id)
12360 prop.cb = old_cb
12361
12362
12363def user_prop_final(ctx, cb):
12364 prop = _prop_closures.get(ctx)
12365 old_cb = prop.cb
12366 prop.cb = cb
12367 prop.final()
12368 prop.cb = old_cb
12369
12370def user_prop_eq(ctx, cb, x, y):
12371 prop = _prop_closures.get(ctx)
12372 old_cb = prop.cb
12373 prop.cb = cb
12374 x = _to_expr_ref(to_Ast(x), prop.ctx())
12375 y = _to_expr_ref(to_Ast(y), prop.ctx())
12376 prop.eq(x, y)
12377 prop.cb = old_cb
12378
12379def user_prop_diseq(ctx, cb, x, y):
12380 prop = _prop_closures.get(ctx)
12381 old_cb = prop.cb
12382 prop.cb = cb
12383 x = _to_expr_ref(to_Ast(x), prop.ctx())
12384 y = _to_expr_ref(to_Ast(y), prop.ctx())
12385 prop.diseq(x, y)
12386 prop.cb = old_cb
12387
12388def user_prop_decide(ctx, cb, t_ref, idx, phase):
12389 prop = _prop_closures.get(ctx)
12390 old_cb = prop.cb
12391 prop.cb = cb
12392 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12393 prop.decide(t, idx, phase)
12394 prop.cb = old_cb
12395
12396def user_prop_binding(ctx, cb, q_ref, inst_ref):
12397 prop = _prop_closures.get(ctx)
12398 old_cb = prop.cb
12399 prop.cb = cb
12400 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12401 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12402 r = prop.binding(q, inst)
12403 prop.cb = old_cb
12404 return r
12405
12406
12407_user_prop_push = Z3_push_eh(user_prop_push)
12408_user_prop_pop = Z3_pop_eh(user_prop_pop)
12409_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12410_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12411_user_prop_created = Z3_created_eh(user_prop_created)
12412_user_prop_final = Z3_final_eh(user_prop_final)
12413_user_prop_eq = Z3_eq_eh(user_prop_eq)
12414_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12415_user_prop_decide = Z3_decide_eh(user_prop_decide)
12416_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12417
12418
12419def PropagateFunction(name, *sig):
12420 """Create a function that gets tracked by user propagator.
12421 Every term headed by this function symbol is tracked.
12422 If a term is fixed and the fixed callback is registered a
12423 callback is invoked that the term headed by this function is fixed.
12424 """
12425 sig = _get_args(sig)
12426 if z3_debug():
12427 _z3_assert(len(sig) > 0, "At least two arguments expected")
12428 arity = len(sig) - 1
12429 rng = sig[arity]
12430 if z3_debug():
12431 _z3_assert(is_sort(rng), "Z3 sort expected")
12432 dom = (Sort * arity)()
12433 for i in range(arity):
12434 if z3_debug():
12435 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12436 dom[i] = sig[i].ast
12437 ctx = rng.ctx
12438 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12439
12440
12441
12442class UserPropagateBase:
12443
12444 #
12445 # Either solver is set or ctx is set.
12446 # Propagators that are created through callbacks
12447 # to "fresh" inherit the context of that is supplied
12448 # as argument to the callback.
12449 # This context should not be deleted. It is owned by the solver.
12450 #
12451 def __init__(self, s, ctx=None):
12452 assert s is None or ctx is None
12453 ensure_prop_closures()
12454 self.solver = s
12455 self._ctx = None
12456 self.fresh_ctx = None
12457 self.cb = None
12458 self.id = _prop_closures.insert(self)
12459 self.fixed = None
12460 self.final = None
12461 self.eq = None
12462 self.diseq = None
12463 self.decide = None
12464 self.created = None
12465 self.binding = None
12466 if ctx:
12467 self.fresh_ctx = ctx
12468 if s:
12469 Z3_solver_propagate_init(self.ctx_ref(),
12470 s.solver,
12471 ctypes.c_void_p(self.id),
12472 _user_prop_push,
12473 _user_prop_pop,
12474 _user_prop_fresh)
12475
12476 def __del__(self):
12477 if self._ctx:
12478 self._ctx.ctx = None
12479
12480 def ctx(self):
12481 if self.fresh_ctx:
12482 return self.fresh_ctx
12483 else:
12484 return self.solver.ctx
12485
12486 def ctx_ref(self):
12487 return self.ctx().ref()
12488
12489 def add_fixed(self, fixed):
12490 if self.fixed:
12491 raise Z3Exception("fixed callback already registered")
12492 if self._ctx:
12493 raise Z3Exception("context already initialized")
12494 if self.solver:
12495 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12496 self.fixed = fixed
12497
12498 def add_created(self, created):
12499 if self.created:
12500 raise Z3Exception("created callback already registered")
12501 if self._ctx:
12502 raise Z3Exception("context already initialized")
12503 if self.solver:
12504 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12505 self.created = created
12506
12507 def add_final(self, final):
12508 if self.final:
12509 raise Z3Exception("final callback already registered")
12510 if self._ctx:
12511 raise Z3Exception("context already initialized")
12512 if self.solver:
12513 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12514 self.final = final
12515
12516 def add_eq(self, eq):
12517 if self.eq:
12518 raise Z3Exception("eq callback already registered")
12519 if self._ctx:
12520 raise Z3Exception("context already initialized")
12521 if self.solver:
12522 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12523 self.eq = eq
12524
12525 def add_diseq(self, diseq):
12526 if self.diseq:
12527 raise Z3Exception("diseq callback already registered")
12528 if self._ctx:
12529 raise Z3Exception("context already initialized")
12530 if self.solver:
12531 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12532 self.diseq = diseq
12533
12534 def add_decide(self, decide):
12535 if self.decide:
12536 raise Z3Exception("decide callback already registered")
12537 if self._ctx:
12538 raise Z3Exception("context already initialized")
12539 if self.solver:
12540 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12541 self.decide = decide
12542
12543 def add_on_binding(self, binding):
12544 if self.binding:
12545 raise Z3Exception("binding callback already registered")
12546 if self._ctx:
12547 raise Z3Exception("context already initialized")
12548 if self.solver:
12549 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12550 self.binding = binding
12551
12552 def push(self):
12553 raise Z3Exception("push needs to be overwritten")
12554
12555 def pop(self, num_scopes):
12556 raise Z3Exception("pop needs to be overwritten")
12557
12558 def fresh(self, new_ctx):
12559 raise Z3Exception("fresh needs to be overwritten")
12560
12561 def add(self, e):
12562 if self._ctx:
12563 raise Z3Exception("context already initialized")
12564 if self.solver:
12565 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12566 else:
12567 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12568
12569 #
12570 # Tell the solver to perform the next split on a given term
12571 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12572 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12573 #
12574 def next_split(self, t, idx, phase):
12575 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12576
12577 #
12578 # Propagation can only be invoked as during a fixed or final callback.
12579 #
12580 def propagate(self, e, ids, eqs=[]):
12581 _ids, num_fixed = _to_ast_array(ids)
12582 num_eqs = len(eqs)
12583 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12584 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12585 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12586 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12587
12588 def conflict(self, deps = [], eqs = []):
12589 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
approx(self, precision=10)
Definition z3py.py:3258
as_decimal(self, prec)
Definition z3py.py:3270
__rmod__(self, other)
Definition z3py.py:2729
__mod__(self, other)
Definition z3py.py:2714
__pow__(self, other)
Definition z3py.py:2638
__gt__(self, other)
Definition z3py.py:2787
__lt__(self, other)
Definition z3py.py:2774
__rtruediv__(self, other)
Definition z3py.py:2710
__rmul__(self, other)
Definition z3py.py:2605
__abs__(self)
Definition z3py.py:2813
__rsub__(self, other)
Definition z3py.py:2628
__add__(self, other)
Definition z3py.py:2567
__sub__(self, other)
Definition z3py.py:2615
is_real(self)
Definition z3py.py:2556
is_int(self)
Definition z3py.py:2542
__radd__(self, other)
Definition z3py.py:2580
__truediv__(self, other)
Definition z3py.py:2689
__le__(self, other)
Definition z3py.py:2761
__rpow__(self, other)
Definition z3py.py:2652
__pos__(self)
Definition z3py.py:2752
sort(self)
Definition z3py.py:2532
__mul__(self, other)
Definition z3py.py:2590
__rdiv__(self, other)
Definition z3py.py:2693
__ge__(self, other)
Definition z3py.py:2800
__neg__(self)
Definition z3py.py:2741
__div__(self, other)
Definition z3py.py:2666
Arithmetic.
Definition z3py.py:2437
subsort(self, other)
Definition z3py.py:2471
cast(self, val)
Definition z3py.py:2475
domain(self)
Definition z3py.py:4795
domain_n(self, i)
Definition z3py.py:4804
__getitem__(self, arg)
Definition z3py.py:4817
range(self)
Definition z3py.py:4808
sort(self)
Definition z3py.py:4786
default(self)
Definition z3py.py:4829
domain_n(self, i)
Definition z3py.py:4768
erase(self, k)
Definition z3py.py:6708
__deepcopy__(self, memo={})
Definition z3py.py:6645
__init__(self, m=None, ctx=None)
Definition z3py.py:6634
__repr__(self)
Definition z3py.py:6705
__len__(self)
Definition z3py.py:6652
keys(self)
Definition z3py.py:6737
__setitem__(self, k, v)
Definition z3py.py:6689
__contains__(self, key)
Definition z3py.py:6665
__del__(self)
Definition z3py.py:6648
__getitem__(self, key)
Definition z3py.py:6678
reset(self)
Definition z3py.py:6722
__deepcopy__(self, memo={})
Definition z3py.py:382
__nonzero__(self)
Definition z3py.py:397
as_ast(self)
Definition z3py.py:419
translate(self, target)
Definition z3py.py:448
__hash__(self)
Definition z3py.py:394
__init__(self, ast, ctx=None)
Definition z3py.py:372
__str__(self)
Definition z3py.py:385
ctx_ref(self)
Definition z3py.py:427
py_value(self)
Definition z3py.py:477
__repr__(self)
Definition z3py.py:388
get_id(self)
Definition z3py.py:423
hash(self)
Definition z3py.py:467
__eq__(self, other)
Definition z3py.py:391
eq(self, other)
Definition z3py.py:431
sexpr(self)
Definition z3py.py:410
__del__(self)
Definition z3py.py:377
__bool__(self)
Definition z3py.py:400
__copy__(self)
Definition z3py.py:464
__deepcopy__(self, memo={})
Definition z3py.py:6614
translate(self, other_ctx)
Definition z3py.py:6595
__repr__(self)
Definition z3py.py:6617
__len__(self)
Definition z3py.py:6487
__init__(self, v=None, ctx=None)
Definition z3py.py:6472
push(self, v)
Definition z3py.py:6547
__getitem__(self, i)
Definition z3py.py:6500
sexpr(self)
Definition z3py.py:6620
__del__(self)
Definition z3py.py:6483
__setitem__(self, i, v)
Definition z3py.py:6529
__contains__(self, item)
Definition z3py.py:6572
__copy__(self)
Definition z3py.py:6611
resize(self, sz)
Definition z3py.py:6559
as_binary_string(self)
Definition z3py.py:4108
as_signed_long(self)
Definition z3py.py:4082
as_string(self)
Definition z3py.py:4105
__and__(self, other)
Definition z3py.py:3772
__rmod__(self, other)
Definition z3py.py:3913
__rrshift__(self, other)
Definition z3py.py:4039
__mod__(self, other)
Definition z3py.py:3892
__or__(self, other)
Definition z3py.py:3749
__rlshift__(self, other)
Definition z3py.py:4053
__gt__(self, other)
Definition z3py.py:3963
__lt__(self, other)
Definition z3py.py:3947
__invert__(self)
Definition z3py.py:3838
__rtruediv__(self, other)
Definition z3py.py:3888
__rmul__(self, other)
Definition z3py.py:3716
__rxor__(self, other)
Definition z3py.py:3808
__ror__(self, other)
Definition z3py.py:3762
__rsub__(self, other)
Definition z3py.py:3739
__add__(self, other)
Definition z3py.py:3680
__sub__(self, other)
Definition z3py.py:3726
__radd__(self, other)
Definition z3py.py:3693
size(self)
Definition z3py.py:3669
__rand__(self, other)
Definition z3py.py:3785
__truediv__(self, other)
Definition z3py.py:3868
__le__(self, other)
Definition z3py.py:3931
__xor__(self, other)
Definition z3py.py:3795
__lshift__(self, other)
Definition z3py.py:4025
__pos__(self)
Definition z3py.py:3818
sort(self)
Definition z3py.py:3658
__mul__(self, other)
Definition z3py.py:3703
__rdiv__(self, other)
Definition z3py.py:3872
__ge__(self, other)
Definition z3py.py:3979
__neg__(self)
Definition z3py.py:3827
__rshift__(self, other)
Definition z3py.py:3995
__div__(self, other)
Definition z3py.py:3849
Bit-Vectors.
Definition z3py.py:3611
subsort(self, other)
Definition z3py.py:3623
cast(self, val)
Definition z3py.py:3626
__and__(self, other)
Definition z3py.py:1688
__or__(self, other)
Definition z3py.py:1691
__invert__(self)
Definition z3py.py:1697
__rmul__(self, other)
Definition z3py.py:1674
__add__(self, other)
Definition z3py.py:1666
py_value(self)
Definition z3py.py:1700
__radd__(self, other)
Definition z3py.py:1671
__xor__(self, other)
Definition z3py.py:1694
sort(self)
Definition z3py.py:1663
__mul__(self, other)
Definition z3py.py:1677
Booleans.
Definition z3py.py:1624
subsort(self, other)
Definition z3py.py:1650
is_bool(self)
Definition z3py.py:1656
cast(self, val)
Definition z3py.py:1627
__deepcopy__(self, memo={})
Definition z3py.py:7504
__eq__(self, other)
Definition z3py.py:7507
__ne__(self, other)
Definition z3py.py:7510
__init__(self, r)
Definition z3py.py:7501
param_descrs(self)
Definition z3py.py:240
set_ast_print_mode(self, mode)
Definition z3py.py:244
__init__(self, *args, **kws)
Definition z3py.py:202
interrupt(self)
Definition z3py.py:232
__del__(self)
Definition z3py.py:222
ref(self)
Definition z3py.py:228
bool owner
Definition z3py.py:217
__deepcopy__(self, memo={})
Definition z3py.py:5560
create(self)
Definition z3py.py:5599
__init__(self, name, ctx=None)
Definition z3py.py:5555
__repr__(self)
Definition z3py.py:5596
list constructors
Definition z3py.py:5558
declare(self, name, *args)
Definition z3py.py:5575
create_polymorphic(self, type_params)
Definition z3py.py:5615
declare_core(self, name, rec_name, *args)
Definition z3py.py:5565
update_field(self, field_accessor, new_value)
Definition z3py.py:5924
constructor(self, idx)
Definition z3py.py:5836
accessor(self, i, j)
Definition z3py.py:5883
num_constructors(self)
Definition z3py.py:5823
recognizer(self, idx)
Definition z3py.py:5855
Expressions.
Definition z3py.py:1020
update(self, *args)
Definition z3py.py:1176
as_ast(self)
Definition z3py.py:1031
__hash__(self)
Definition z3py.py:1077
kind(self)
Definition z3py.py:1117
children(self)
Definition z3py.py:1161
serialize(self)
Definition z3py.py:1203
get_id(self)
Definition z3py.py:1034
num_args(self)
Definition z3py.py:1124
__eq__(self, other)
Definition z3py.py:1060
__ne__(self, other)
Definition z3py.py:1081
from_string(self, s)
Definition z3py.py:1200
sort_kind(self)
Definition z3py.py:1049
arg(self, idx)
Definition z3py.py:1140
sort(self)
Definition z3py.py:1037
params(self)
Definition z3py.py:1099
decl(self)
Definition z3py.py:1102
__and__(self, other)
Definition z3py.py:5375
__or__(self, other)
Definition z3py.py:5371
__sub__(self, other)
Definition z3py.py:5379
Finite Sets.
Definition z3py.py:5303
subsort(self, other)
Definition z3py.py:5325
cast(self, val)
Definition z3py.py:5310
Function Declarations.
Definition z3py.py:777
as_func_decl(self)
Definition z3py.py:791
domain(self, i)
Definition z3py.py:815
as_ast(self)
Definition z3py.py:785
__call__(self, *args)
Definition z3py.py:878
arity(self)
Definition z3py.py:805
get_id(self)
Definition z3py.py:788
range(self)
Definition z3py.py:827
params(self)
Definition z3py.py:850
Definition z3py.py:6756
__deepcopy__(self, memo={})
Definition z3py.py:6764
ctx
Definition z3py.py:6761
__repr__(self)
Definition z3py.py:6861
num_args(self)
Definition z3py.py:6771
entry
Definition z3py.py:6760
value(self)
Definition z3py.py:6820
__init__(self, entry, ctx)
Definition z3py.py:6759
__del__(self)
Definition z3py.py:6767
as_list(self)
Definition z3py.py:6842
arg_value(self, idx)
Definition z3py.py:6789
__deepcopy__(self, memo={})
Definition z3py.py:6959
translate(self, other_ctx)
Definition z3py.py:6951
arity(self)
Definition z3py.py:6917
__repr__(self)
Definition z3py.py:6979
num_entries(self)
Definition z3py.py:6901
__init__(self, f, ctx)
Definition z3py.py:6868
__del__(self)
Definition z3py.py:6874
as_list(self)
Definition z3py.py:6962
else_value(self)
Definition z3py.py:6878
entry(self, idx)
Definition z3py.py:6931
__copy__(self)
Definition z3py.py:6956
__deepcopy__(self, memo={})
Definition z3py.py:6417
get(self, i)
Definition z3py.py:6273
prec(self)
Definition z3py.py:6217
translate(self, target)
Definition z3py.py:6391
append(self, *args)
Definition z3py.py:6318
as_expr(self)
Definition z3py.py:6440
assert_exprs(self, *args)
Definition z3py.py:6303
__repr__(self)
Definition z3py.py:6380
__len__(self)
Definition z3py.py:6260
inconsistent(self)
Definition z3py.py:6199
dimacs(self, include_names=True)
Definition z3py.py:6387
__getitem__(self, arg)
Definition z3py.py:6286
size(self)
Definition z3py.py:6247
precision(self)
Definition z3py.py:6238
simplify(self, *arguments, **keywords)
Definition z3py.py:6420
sexpr(self)
Definition z3py.py:6383
add(self, *args)
Definition z3py.py:6340
__del__(self)
Definition z3py.py:6177
convert_model(self, model)
Definition z3py.py:6351
insert(self, *args)
Definition z3py.py:6329
depth(self)
Definition z3py.py:6181
__init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition z3py.py:6167
__copy__(self)
Definition z3py.py:6414
as_binary_string(self)
Definition z3py.py:3143
py_value(self)
Definition z3py.py:3151
as_long(self)
Definition z3py.py:3122
as_string(self)
Definition z3py.py:3135
__deepcopy__(self, memo={})
Definition z3py.py:7327
eval(self, t, model_completion=False)
Definition z3py.py:7003
translate(self, target)
Definition z3py.py:7292
__getitem__(self, idx)
Definition z3py.py:7204
num_sorts(self)
Definition z3py.py:7129
get_universe(self, s)
Definition z3py.py:7184
get_sort(self, idx)
Definition z3py.py:7144
project(self, vars, fml)
Definition z3py.py:7300
__repr__(self)
Definition z3py.py:6996
__len__(self)
Definition z3py.py:7060
get_interp(self, decl)
Definition z3py.py:7077
__init__(self, m, ctx)
Definition z3py.py:6986
sexpr(self)
Definition z3py.py:6999
sorts(self)
Definition z3py.py:7167
__del__(self)
Definition z3py.py:6992
decls(self)
Definition z3py.py:7251
project_with_witness(self, vars, fml)
Definition z3py.py:7312
update_value(self, x, value)
Definition z3py.py:7270
evaluate(self, t, model_completion=False)
Definition z3py.py:7034
__copy__(self)
Definition z3py.py:7324
__deepcopy__(self, memo={})
Definition z3py.py:6111
__init__(self, descr, ctx=None)
Definition z3py.py:6105
get_kind(self, n)
Definition z3py.py:6133
get_documentation(self, n)
Definition z3py.py:6138
__getitem__(self, arg)
Definition z3py.py:6143
get_name(self, i)
Definition z3py.py:6128
Parameter Sets.
Definition z3py.py:6032
__deepcopy__(self, memo={})
Definition z3py.py:6046
validate(self, ds)
Definition z3py.py:6073
__repr__(self)
Definition z3py.py:6070
__init__(self, ctx=None, params=None)
Definition z3py.py:6038
set(self, name, val)
Definition z3py.py:6053
__del__(self)
Definition z3py.py:6049
Patterns.
Definition z3py.py:2060
as_ast(self)
Definition z3py.py:2065
get_id(self)
Definition z3py.py:2068
Quantifiers.
Definition z3py.py:2127
num_no_patterns(self)
Definition z3py.py:2245
no_pattern(self, idx)
Definition z3py.py:2249
num_patterns(self)
Definition z3py.py:2215
var_name(self, idx)
Definition z3py.py:2278
__getitem__(self, arg)
Definition z3py.py:2184
var_sort(self, idx)
Definition z3py.py:2294
pattern(self, idx)
Definition z3py.py:2227
numerator_as_long(self)
Definition z3py.py:3184
is_int_value(self)
Definition z3py.py:3214
as_fraction(self)
Definition z3py.py:3242
py_value(self)
Definition z3py.py:3251
numerator(self)
Definition z3py.py:3158
is_real(self)
Definition z3py.py:3211
as_long(self)
Definition z3py.py:3217
is_int(self)
Definition z3py.py:3208
denominator_as_long(self)
Definition z3py.py:3197
as_string(self)
Definition z3py.py:3233
denominator(self)
Definition z3py.py:3173
as_decimal(self, prec)
Definition z3py.py:3221
__init__(self, c, ctx)
Definition z3py.py:5633
__init__(self, c, ctx)
Definition z3py.py:5645
Strings, Sequences and Regular expressions.
Definition z3py.py:11552
__init__(self, solver=None, ctx=None, logFile=None)
Definition z3py.py:7548
assert_and_track(self, a, p)
Definition z3py.py:7717
num_scopes(self)
Definition z3py.py:7629
append(self, *args)
Definition z3py.py:7695
__iadd__(self, fml)
Definition z3py.py:7691
pop(self, num=1)
Definition z3py.py:7607
import_model_converter(self, other)
Definition z3py.py:7795
assert_exprs(self, *args)
Definition z3py.py:7661
model(self)
Definition z3py.py:7776
set(self, *args, **keys)
Definition z3py.py:7572
__enter__(self)
Definition z3py.py:7565
add(self, *args)
Definition z3py.py:7680
__del__(self)
Definition z3py.py:7561
int backtrack_level
Definition z3py.py:7551
insert(self, *args)
Definition z3py.py:7706
check(self, *assumptions)
Definition z3py.py:7747
push(self)
Definition z3py.py:7585
__exit__(self, *exc_info)
Definition z3py.py:7569
reset(self)
Definition z3py.py:7647
subsort(self, other)
Definition z3py.py:616
as_ast(self)
Definition z3py.py:593
__hash__(self)
Definition z3py.py:677
kind(self)
Definition z3py.py:599
__gt__(self, other)
Definition z3py.py:673
get_id(self)
Definition z3py.py:596
__eq__(self, other)
Definition z3py.py:649
__ne__(self, other)
Definition z3py.py:662
cast(self, val)
Definition z3py.py:624
name(self)
Definition z3py.py:639
Statistics.
Definition z3py.py:7357
__deepcopy__(self, memo={})
Definition z3py.py:7365
__getattr__(self, name)
Definition z3py.py:7460
__getitem__(self, idx)
Definition z3py.py:7404
__init__(self, stats, ctx)
Definition z3py.py:7360
__repr__(self)
Definition z3py.py:7372
__len__(self)
Definition z3py.py:7390
__del__(self)
Definition z3py.py:7368
get_key_value(self, key)
Definition z3py.py:7440
subsort(self, other)
Definition z3py.py:753
cast(self, val)
Definition z3py.py:756
ASTs base class.
Definition z3py.py:355
_repr_html_(self)
Definition z3py.py:361
use_pp(self)
Definition z3py.py:358
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_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.
Z3_ast Z3_API Z3_mk_bvxnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise xnor.
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_mk_bvnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nor.
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_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.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
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_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_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
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_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_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.
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_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_ast Z3_API Z3_mk_finite_set_empty(Z3_context c, Z3_sort set_sort)
Create an empty finite set of the given sort.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
bool Z3_API Z3_is_finite_set_sort(Z3_context c, Z3_sort s)
Check if a sort is a finite set sort.
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.
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_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
Z3_ast Z3_API Z3_mk_finite_set_difference(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the set difference of two finite sets.
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_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_symbol Z3_API Z3_get_quantifier_skolem_id(Z3_context c, Z3_ast a)
Obtain skolem id of quantifier.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_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].
Z3_ast Z3_API Z3_mk_finite_set_subset(Z3_context c, Z3_ast s1, Z3_ast s2)
Check if one finite set is a subset of another.
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
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_sort Z3_API Z3_mk_polymorphic_datatype(Z3_context c, Z3_symbol name, unsigned num_parameters, Z3_sort parameters[], unsigned num_constructors, Z3_constructor constructors[])
Create a parametric datatype with explicit type parameters.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_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_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
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_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context....
Z3_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_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.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
Z3_ast Z3_API Z3_datatype_update_field(Z3_context c, Z3_func_decl field_access, Z3_ast t, Z3_ast value)
Update record field with a value.
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_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.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_sort Z3_API Z3_get_finite_set_sort_basis(Z3_context c, Z3_sort s)
Get the element sort of a finite set sort.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_finite_set_filter(Z3_context c, Z3_ast f, Z3_ast set)
Filter a finite set using a predicate.
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_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.
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_finite_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check if an element is a member of a finite set.
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
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.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_sort Z3_API Z3_mk_datatype_sort(Z3_context c, Z3_symbol name, unsigned num_params, Z3_sort const params[])
create a forward reference to a recursive datatype being declared. The forward reference can be used ...
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.
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_ast Z3_API Z3_mk_finite_set_union(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the union of two finite sets.
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_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
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.
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_finite_set_intersect(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the intersection of two finite sets.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
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_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_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...
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
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.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_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.
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.
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_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
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.
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_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
unsigned Z3_API Z3_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_ast Z3_API Z3_update_term(Z3_context c, Z3_ast a, unsigned num_args, Z3_ast const args[])
Update the arguments of term a using the arguments args. The number of arguments num_args should coin...
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
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.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
void Z3_API Z3_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_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_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_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
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.
Z3_ast Z3_API Z3_mk_bvnand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nand.
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_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_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_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
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_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
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.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a variable.
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
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_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_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.
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.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
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_ast Z3_API Z3_mk_finite_set_singleton(Z3_context c, Z3_ast elem)
Create a singleton finite set.
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.
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.
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_ast Z3_API Z3_mk_finite_set_map(Z3_context c, Z3_ast f, Z3_ast set)
Apply a function to all elements of a finite set.
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_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_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_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
Z3_sort Z3_API Z3_mk_finite_set_sort(Z3_context c, Z3_sort elem_sort)
Create a finite set sort.
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_ast Z3_API Z3_mk_finite_set_size(Z3_context c, Z3_ast set)
Get the size (cardinality) of a finite set.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
Z3_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_ast Z3_API Z3_mk_finite_set_range(Z3_context c, Z3_ast low, Z3_ast high)
Create a finite set of integers in the range [low, high].
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
Z3_ast Z3_API Z3_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.
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_type_variable(Z3_context c, Z3_symbol s)
Create a type variable.
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_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_ast Z3_API Z3_mk_as_array(Z3_context c, Z3_func_decl f)
Create array with the same interpretation as a function. The array satisfies the property (f x) = (se...
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_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
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_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 const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
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.
double Z3_API Z3_get_numeral_double(Z3_context c, Z3_ast a)
Return numeral as a double.
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_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_symbol Z3_API Z3_get_quantifier_id(Z3_context c, Z3_ast a)
Obtain id of quantifier.
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.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
void Z3_API Z3_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.
_py2expr(a, ctx=None)
Definition z3py.py:3289
RotateRight(a, b)
Definition z3py.py:4543
_symbol2py(ctx, s)
Definition z3py.py:140
BitVecVal(val, bv, ctx=None)
Definition z3py.py:4193
BVSNegNoOverflow(a)
Definition z3py.py:4729
SetAdd(s, e)
Definition z3py.py:5221
SetSort(s)
Sets.
Definition z3py.py:5164
_coerce_exprs(a, b, ctx=None)
Definition z3py.py:1308
UGT(a, b)
Definition z3py.py:4414
is_probe(p)
Definition z3py.py:9454
SetDel(s, e)
Definition z3py.py:5234
bool is_le(Any a)
Definition z3py.py:3029
BoolSort(ctx=None)
Definition z3py.py:1830
is_bv_sort(s)
Definition z3py.py:3644
_ctx_from_ast_args(*args)
Definition z3py.py:542
RatVal(a, b, ctx=None)
Definition z3py.py:3381
_to_func_decl_ref(a, ctx)
Definition z3py.py:964
SetUnion(*args)
Definition z3py.py:5189
_valid_accessor(acc)
Datatypes.
Definition z3py.py:5519
BitVec(name, bv, ctx=None)
Definition z3py.py:4210
EmptySet(s)
Definition z3py.py:5169
BVMulNoUnderflow(a, b)
Definition z3py.py:4743
CreateDatatypes(*ds)
Definition z3py.py:5654
is_func_decl(a)
Definition z3py.py:909
FiniteSetUnion(s1, s2)
Definition z3py.py:5412
get_as_array_func(n)
Definition z3py.py:7344
Distinct(*args)
Definition z3py.py:1513
RecAddDefinition(f, args, body)
Definition z3py.py:986
ToInt(a)
Definition z3py.py:3544
Implies(a, b, ctx=None)
Definition z3py.py:1924
UGE(a, b)
Definition z3py.py:4396
Ext(a, b)
Definition z3py.py:5103
_to_ast_array(args)
Definition z3py.py:554
bool is_sort(Any s)
Definition z3py.py:682
_check_bv_args(a, b)
Definition z3py.py:4355
RealSort(ctx=None)
Definition z3py.py:3321
IsSubset(a, b)
Definition z3py.py:5283
DeclareTypeVar(name, ctx=None)
Definition z3py.py:760
_get_args_ast_list(args)
Definition z3py.py:168
bool is_to_real(Any a)
Definition z3py.py:3089
_to_ref_array(ref, args)
Definition z3py.py:562
get_map_func(a)
Definition z3py.py:4911
is_finite_set(a)
Definition z3py.py:5344
_z3_check_cint_overflow(n, name)
Definition z3py.py:118
bool is_and(Any a)
Definition z3py.py:1760
TupleSort(name, sorts, ctx=None)
Definition z3py.py:5975
_coerce_expr_list(alist, ctx=None)
Definition z3py.py:1339
is_select(a)
Definition z3py.py:5133
SignExt(n, a)
Definition z3py.py:4559
Int(name, ctx=None)
Definition z3py.py:3414
Bools(names, ctx=None)
Definition z3py.py:1879
_probe_and(args, ctx)
Definition z3py.py:9521
Int2BV(a, num_bits)
Definition z3py.py:4169
Lambda(vs, body)
Definition z3py.py:2410
_to_param_value(val)
Definition z3py.py:178
FreshFunction(*sig)
Definition z3py.py:945
RealVector(prefix, sz, ctx=None)
Definition z3py.py:3495
BVRedOr(a)
Definition z3py.py:4648
is_finite_set_sort(s)
Definition z3py.py:5355
SRem(a, b)
Definition z3py.py:4474
FiniteSetFilter(f, set)
Definition z3py.py:5491
SortRef _sort(Context ctx, Any a)
Definition z3py.py:728
set_option(*args, **kws)
Definition z3py.py:328
ExprRef RealVar(int idx, ctx=None)
Definition z3py.py:1596
bool is_sub(Any a)
Definition z3py.py:2976
is_bv(a)
Definition z3py.py:4117
SetDifference(a, b)
Definition z3py.py:5257
bool is_arith_sort(Any s)
Definition z3py.py:2513
BitVecs(names, bv, ctx=None)
Definition z3py.py:4234
_check_same_sort(a, b, ctx=None)
Definition z3py.py:1295
bool is_mod(Any a)
Definition z3py.py:3017
BoolVector(prefix, sz, ctx=None)
Definition z3py.py:1895
FiniteSetEmpty(set_sort)
Definition z3py.py:5393
_has_probe(args)
Definition z3py.py:1980
IsMember(e, s)
Definition z3py.py:5270
get_param(name)
Definition z3py.py:334
BVAddNoUnderflow(a, b)
Definition z3py.py:4701
deserialize(st)
Definition z3py.py:1209
bool is_not(Any a)
Definition z3py.py:1796
BvXnor(a, b)
Definition z3py.py:4681
FiniteSetMap(f, set)
Definition z3py.py:5478
Extract(high, low, a)
Definition z3py.py:4301
Function(name, *sig)
Definition z3py.py:922
get_version()
Definition z3py.py:100
FreshConst(sort, prefix="c")
Definition z3py.py:1573
ULT(a, b)
Definition z3py.py:4378
EnumSort(name, values, ctx=None)
Definition z3py.py:5999
bool is_is_int(Any a)
Definition z3py.py:3077
_to_int_str(val)
Definition z3py.py:3338
is_algebraic_value(a)
Definition z3py.py:2938
is_bv_value(a)
Definition z3py.py:4131
BVSDivNoOverflow(a, b)
Definition z3py.py:4722
bool is_eq(Any a)
Definition z3py.py:1808
Context main_ctx()
Definition z3py.py:266
CreatePolymorphicDatatype(d, type_params)
Definition z3py.py:5750
BvNand(a, b)
Definition z3py.py:4655
SetIntersect(*args)
Definition z3py.py:5205
simplify(a, *arguments, **keywords)
Utils.
Definition z3py.py:9588
BV2Int(a, is_signed=False)
Definition z3py.py:4146
FreshInt(prefix="x", ctx=None)
Definition z3py.py:3453
_to_ast_ref(a, ctx)
Definition z3py.py:570
_to_func_decl_array(args)
Definition z3py.py:546
disable_trace(msg)
Definition z3py.py:87
bool is_to_int(Any a)
Definition z3py.py:3104
is_map(a)
Definition z3py.py:4886
Context _get_ctx(ctx)
Definition z3py.py:287
Or(*args)
Definition z3py.py:2021
is_re(s)
Definition z3py.py:12042
FiniteSetIntersect(s1, s2)
Definition z3py.py:5423
args2params(arguments, keywords, ctx=None)
Definition z3py.py:6078
bool is_idiv(Any a)
Definition z3py.py:3005
Consts(names, sort)
Definition z3py.py:1558
Cond(p, t1, t2, ctx=None)
Definition z3py.py:9571
_to_pattern(arg)
Definition z3py.py:2114
RealVarVector(int n, ctx=None)
Definition z3py.py:1606
is_arith(a)
Definition z3py.py:2825
bool is_true(Any a)
Definition z3py.py:1728
bool is_false(Any a)
Definition z3py.py:1746
bool is_int(a)
Definition z3py.py:2846
If(a, b, c, ctx=None)
Definition z3py.py:1490
bool eq(AstRef a, AstRef b)
Definition z3py.py:503
is_app_of(a, k)
Definition z3py.py:1477
is_app(a)
Definition z3py.py:1374
bool is_add(Any a)
Definition z3py.py:2952
z3_error_handler(c, e)
Definition z3py.py:184
None reset_params()
Definition z3py.py:322
Reals(names, ctx=None)
Definition z3py.py:3480
is_int_value(a)
Definition z3py.py:2892
set_param(*args, **kws)
Definition z3py.py:298
is_pattern(a)
Definition z3py.py:2072
_coerce_seq(s, ctx=None)
Definition z3py.py:11703
bool is_distinct(Any a)
Definition z3py.py:1818
bool is_lt(Any a)
Definition z3py.py:3041
FiniteSetRange(low, high)
Definition z3py.py:5504
ULE(a, b)
Definition z3py.py:4360
is_real(a)
Definition z3py.py:2865
Abs(arg)
Definition z3py.py:9749
FullSet(s)
Definition z3py.py:5180
to_symbol(s, ctx=None)
Definition z3py.py:132
FiniteSetMember(elem, set)
Definition z3py.py:5445
bool is_mul(Any a)
Definition z3py.py:2964
bool is_ast(Any a)
Definition z3py.py:482
_get_args(args)
Definition z3py.py:152
Singleton(elem)
Definition z3py.py:5403
And(*args)
Definition z3py.py:1988
RepeatBitVec(n, a)
Definition z3py.py:4617
FiniteSetDifference(s1, s2)
Definition z3py.py:5434
get_version_string()
Definition z3py.py:91
FreshReal(prefix="b", ctx=None)
Definition z3py.py:3510
Array(name, *sorts)
Definition z3py.py:4968
Concat(*args)
Definition z3py.py:4255
_reduce(func, sequence, initial)
Definition z3py.py:1332
_is_algebraic(ctx, a)
Definition z3py.py:2888
Ints(names, ctx=None)
Definition z3py.py:3427
Select(a, *args)
Definition z3py.py:5042
Const(name, sort)
Definition z3py.py:1546
is_array_sort(a)
Definition z3py.py:4842
bool is_div(Any a)
Definition z3py.py:2988
ExprRef Var(int idx, SortRef s)
Definition z3py.py:1581
BVAddNoOverflow(a, b, signed)
Definition z3py.py:4694
BvNor(a, b)
Definition z3py.py:4668
Real(name, ctx=None)
Definition z3py.py:3467
FreshBool(prefix="b", ctx=None)
Definition z3py.py:1910
BitVecSort(sz, ctx=None)
Definition z3py.py:4178
open_log(fname)
Definition z3py.py:122
RecFunction(name, *sig)
Definition z3py.py:968
FiniteSetSize(set)
Definition z3py.py:5457
bool is_ge(Any a)
Definition z3py.py:3053
Model(ctx=None, eval={})
Definition z3py.py:7331
BVSubNoOverflow(a, b)
Definition z3py.py:4708
bool is_gt(Any a)
Definition z3py.py:3065
In(elem, set)
Definition z3py.py:5454
is_default(a)
Definition z3py.py:4902
is_K(a)
Definition z3py.py:4873
Bool(name, ctx=None)
Definition z3py.py:1867
_is_int(v)
Definition z3py.py:76
is_const_array(a)
Definition z3py.py:4860
Sqrt(a, ctx=None)
Definition z3py.py:3579
FiniteSetSort(elem_sort)
Definition z3py.py:5384
Default(a)
Definition z3py.py:5014
_ctx_from_ast_arg_list(args, default_ctx=None)
Definition z3py.py:528
SetComplement(s)
Definition z3py.py:5247
is_as_array(n)
Definition z3py.py:7339
is_store(a)
Definition z3py.py:5146
FiniteSetSubset(s1, s2)
Definition z3py.py:5467
bool is_or(Any a)
Definition z3py.py:1772
is_quantifier(a)
Definition z3py.py:2322
_mk_bin(f, a, b)
Definition z3py.py:1537
K(dom, v)
Definition z3py.py:5081
Xor(a, b, ctx=None)
Definition z3py.py:1938
Store(a, *args)
Definition z3py.py:5025
bool is_array(Any a)
Definition z3py.py:4846
mk_not(a)
Definition z3py.py:1973
is_expr(a)
Definition z3py.py:1351
_array_select(ar, arg)
Definition z3py.py:4833
is_const(a)
Definition z3py.py:1400
BoolVal(val, ctx=None)
Definition z3py.py:1848
RealVal(val, ctx=None)
Definition z3py.py:3362
bool is_implies(Any a)
Definition z3py.py:1784
z3_debug()
Definition z3py.py:70
get_full_version()
Definition z3py.py:109
IntVector(prefix, sz, ctx=None)
Definition z3py.py:3440
_coerce_expr_merge(s, a)
Definition z3py.py:1277
Context get_ctx(ctx)
Definition z3py.py:294
LShR(a, b)
Definition z3py.py:4495
ArraySort(*sig)
Definition z3py.py:4935
Map(f, *args)
Definition z3py.py:5058
is_rational_value(a)
Definition z3py.py:2916
_probe_or(args, ctx)
Definition z3py.py:9525
BVRedAnd(a)
Definition z3py.py:4641
Cbrt(a, ctx=None)
Definition z3py.py:3592
_to_expr_ref(a, ctx)
Definition z3py.py:1223
DisjointSum(name, sorts, ctx=None)
Definition z3py.py:5987
IntSort(ctx=None)
Definition z3py.py:3304
is_seq(a)
Definition z3py.py:11724
Not(a, ctx=None)
Definition z3py.py:1954
_to_sort_ref(s, ctx)
Definition z3py.py:695
enable_trace(msg)
Definition z3py.py:83
Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2389
ToReal(a)
Definition z3py.py:3524
URem(a, b)
Definition z3py.py:4453
bool is_bool(Any a)
Definition z3py.py:1710
StringVal(s, ctx=None)
Definition z3py.py:11751
IsInt(a)
Definition z3py.py:3562
_is_numeral(ctx, a)
Definition z3py.py:2884
MultiPattern(*args)
Definition z3py.py:2090
ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2371
ZeroExt(n, a)
Definition z3py.py:4589
_sort_kind(ctx, s)
Sorts.
Definition z3py.py:586
int _ast_kind(Context ctx, Any a)
Definition z3py.py:522
DatatypeSort(name, params=None, ctx=None)
Definition z3py.py:5950
BVSubNoUnderflow(a, b, signed)
Definition z3py.py:4715
UDiv(a, b)
Definition z3py.py:4432
Q(a, b, ctx=None)
Definition z3py.py:3401
Update(a, *args)
Definition z3py.py:4982
get_var_index(a)
Definition z3py.py:1444
append_log(s)
Definition z3py.py:127
AsArray(f)
Definition z3py.py:5115
is_var(a)
Definition z3py.py:1419
SortRef DeclareSort(name, ctx=None)
Definition z3py.py:732
IntVal(val, ctx=None)
Definition z3py.py:3350
BVMulNoOverflow(a, b, signed)
Definition z3py.py:4736
RotateLeft(a, b)
Definition z3py.py:4527
_mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2336
_z3_assert(cond, msg)
Definition z3py.py:113