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.astast)
595
596 def get_id(self):
597 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_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.ctxctx, self.astast)
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.ctxctx, Z3_get_sort_name(self.ctx_ref(), self.astast))
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.astast, 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.astast, 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_COMPLEX_SORT:
706 return ComplexSortRef(s, ctx)
707 elif k == Z3_BV_SORT:
708 return BitVecSortRef(s, ctx)
709 elif k == Z3_ARRAY_SORT:
710 return ArraySortRef(s, ctx)
711 elif k == Z3_DATATYPE_SORT:
712 return DatatypeSortRef(s, ctx)
713 elif k == Z3_FINITE_FIELD_SORT:
714 return FiniteFieldSortRef(s, ctx)
715 elif k == Z3_FINITE_DOMAIN_SORT:
716 return FiniteDomainSortRef(s, ctx)
717 elif k == Z3_FLOATING_POINT_SORT:
718 return FPSortRef(s, ctx)
719 elif k == Z3_ROUNDING_MODE_SORT:
720 return FPRMSortRef(s, ctx)
721 elif k == Z3_RE_SORT:
722 return ReSortRef(s, ctx)
723 elif k == Z3_SEQ_SORT:
724 return SeqSortRef(s, ctx)
725 elif k == Z3_CHAR_SORT:
726 return CharSortRef(s, ctx)
727 elif k == Z3_TYPE_VAR:
728 return TypeVarRef(s, ctx)
729 return SortRef(s, ctx)
730
731
732def _sort(ctx : Context, a : Any) -> SortRef:
733 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
734
735
736def DeclareSort(name, ctx= None) -> SortRef:
737 """Create a new uninterpreted sort named `name`.
738
739 If `ctx=None`, then the new sort is declared in the global Z3Py context.
740
741 >>> A = DeclareSort('A')
742 >>> a = Const('a', A)
743 >>> b = Const('b', A)
744 >>> a.sort() == A
745 True
746 >>> b.sort() == A
747 True
748 >>> a == b
749 a == b
750 """
751 ctx = _get_ctx(ctx)
752 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
753
755 """Type variable reference"""
756
757 def subsort(self, other):
758 return True
759
760 def cast(self, val):
761 return val
762
763
764def DeclareTypeVar(name, ctx=None):
765 """Create a new type variable named `name`.
766
767 If `ctx=None`, then the new sort is declared in the global Z3Py context.
768
769 """
770 ctx = _get_ctx(ctx)
771 return TypeVarRef(Z3_mk_type_variable(ctx.ref(), to_symbol(name, ctx)), ctx)
772
773
774
779
780
782 """Function declaration. Every constant and function have an associated declaration.
783
784 The declaration assigns a name, a sort (i.e., type), and for function
785 the sort (i.e., type) of each of its arguments. Note that, in Z3,
786 a constant is a function with 0 arguments.
787 """
788
789 def as_ast(self):
790 return Z3_func_decl_to_ast(self.ctx_ref(), self.astast)
791
792 def get_id(self):
793 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
794
795 def as_func_decl(self):
796 return self.astast
797
798 def name(self):
799 """Return the name of the function declaration `self`.
800
801 >>> f = Function('f', IntSort(), IntSort())
802 >>> f.name()
803 'f'
804 >>> isinstance(f.name(), str)
805 True
806 """
807 return _symbol2py(self.ctxctx, Z3_get_decl_name(self.ctx_ref(), self.astast))
808
809 def arity(self):
810 """Return the number of arguments of a function declaration.
811 If `self` is a constant, then `self.arity()` is 0.
812
813 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
814 >>> f.arity()
815 2
816 """
817 return int(Z3_get_arity(self.ctx_ref(), self.astast))
818
819 def domain(self, i):
820 """Return the sort of the argument `i` of a function declaration.
821 This method assumes that `0 <= i < self.arity()`.
822
823 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
824 >>> f.domain(0)
825 Int
826 >>> f.domain(1)
827 Real
828 """
829 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.astast, i), self.ctxctx)
830
831 def range(self):
832 """Return the sort of the range of a function declaration.
833 For constants, this is the sort of the constant.
834
835 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
836 >>> f.range()
837 Bool
838 """
839 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.astast), self.ctxctx)
840
841 def kind(self):
842 """Return the internal kind of a function declaration.
843 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
844
845 >>> x = Int('x')
846 >>> d = (x + 1).decl()
847 >>> d.kind() == Z3_OP_ADD
848 True
849 >>> d.kind() == Z3_OP_MUL
850 False
851 """
852 return Z3_get_decl_kind(self.ctx_ref(), self.astast)
853
854 def params(self):
855 ctx = self.ctxctx
857 result = [None for i in range(n)]
858 for i in range(n):
859 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.astast, i)
860 if k == Z3_PARAMETER_INT:
861 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.astast, i)
862 elif k == Z3_PARAMETER_DOUBLE:
863 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.astast, i)
864 elif k == Z3_PARAMETER_RATIONAL:
865 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.astast, i)
866 elif k == Z3_PARAMETER_SYMBOL:
867 result[i] = _symbol2py(ctx, Z3_get_decl_symbol_parameter(self.ctx_ref(), self.astast, i))
868 elif k == Z3_PARAMETER_SORT:
869 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.astast, i), ctx)
870 elif k == Z3_PARAMETER_AST:
871 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.astast, i), ctx)
872 elif k == Z3_PARAMETER_FUNC_DECL:
873 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.astast, i), ctx)
874 elif k == Z3_PARAMETER_INTERNAL:
875 result[i] = "internal parameter"
876 elif k == Z3_PARAMETER_ZSTRING:
877 result[i] = "internal string"
878 else:
879 raise Z3Exception("Unexpected parameter kind")
880 return result
881
882 def __call__(self, *args):
883 """Create a Z3 application expression using the function `self`, and the given arguments.
884
885 The arguments must be Z3 expressions. This method assumes that
886 the sorts of the elements in `args` match the sorts of the
887 domain. Limited coercion is supported. For example, if
888 args[0] is a Python integer, and the function expects a Z3
889 integer, then the argument is automatically converted into a
890 Z3 integer.
891
892 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
893 >>> x = Int('x')
894 >>> y = Real('y')
895 >>> f(x, y)
896 f(x, y)
897 >>> f(x, x)
898 f(x, ToReal(x))
899 """
900 args = _get_args(args)
901 num = len(args)
902 _args = (Ast * num)()
903 saved = []
904 for i in range(num):
905 # self.domain(i).cast(args[i]) may create a new Z3 expression,
906 # then we must save in 'saved' to prevent it from being garbage collected.
907 tmp = self.domain(i).cast(args[i])
908 saved.append(tmp)
909 _args[i] = tmp.as_ast()
910 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.astast, len(args), _args), self.ctxctx)
911
912
914 """Return `True` if `a` is a Z3 function declaration.
915
916 >>> f = Function('f', IntSort(), IntSort())
917 >>> is_func_decl(f)
918 True
919 >>> x = Real('x')
920 >>> is_func_decl(x)
921 False
922 """
923 return isinstance(a, FuncDeclRef)
924
925
926def Function(name, *sig):
927 """Create a new Z3 uninterpreted function with the given sorts.
928
929 >>> f = Function('f', IntSort(), IntSort())
930 >>> f(f(0))
931 f(f(0))
932 """
933 sig = _get_args(sig)
934 if z3_debug():
935 _z3_assert(len(sig) > 0, "At least two arguments expected")
936 arity = len(sig) - 1
937 rng = sig[arity]
938 if z3_debug():
939 _z3_assert(is_sort(rng), "Z3 sort expected")
940 dom = (Sort * arity)()
941 for i in range(arity):
942 if z3_debug():
943 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
944 dom[i] = sig[i].ast
945 ctx = rng.ctx
946 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
947
948
950 """Create a new fresh Z3 uninterpreted function with the given sorts.
951 """
952 sig = _get_args(sig)
953 if z3_debug():
954 _z3_assert(len(sig) > 0, "At least two arguments expected")
955 arity = len(sig) - 1
956 rng = sig[arity]
957 if z3_debug():
958 _z3_assert(is_sort(rng), "Z3 sort expected")
959 dom = (z3.Sort * arity)()
960 for i in range(arity):
961 if z3_debug():
962 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
963 dom[i] = sig[i].ast
964 ctx = rng.ctx
965 return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
966
967
969 return FuncDeclRef(a, ctx)
970
971
972def RecFunction(name, *sig):
973 """Create a new Z3 recursive with the given sorts."""
974 sig = _get_args(sig)
975 if z3_debug():
976 _z3_assert(len(sig) > 0, "At least two arguments expected")
977 arity = len(sig) - 1
978 rng = sig[arity]
979 if z3_debug():
980 _z3_assert(is_sort(rng), "Z3 sort expected")
981 dom = (Sort * arity)()
982 for i in range(arity):
983 if z3_debug():
984 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
985 dom[i] = sig[i].ast
986 ctx = rng.ctx
987 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
988
989
990def RecAddDefinition(f, args, body):
991 """Set the body of a recursive function.
992 Recursive definitions can be simplified if they are applied to ground
993 arguments.
994 >>> ctx = Context()
995 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
996 >>> n = Int('n', ctx)
997 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
998 >>> simplify(fac(5))
999 120
1000 >>> s = Solver(ctx=ctx)
1001 >>> s.add(fac(n) < 3)
1002 >>> s.check()
1003 sat
1004 >>> s.model().eval(fac(5))
1005 120
1006 """
1007 if is_app(args):
1008 args = [args]
1009 ctx = body.ctx
1010 args = _get_args(args)
1011 n = len(args)
1012 _args = (Ast * n)()
1013 for i in range(n):
1014 _args[i] = args[i].ast
1015 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
1016
1017
1022
1023
1025 """Constraints, formulas and terms are expressions in Z3.
1026
1027 Expressions are ASTs. Every expression has a sort.
1028 There are three main kinds of expressions:
1029 function applications, quantifiers and bounded variables.
1030 A constant is a function application with 0 arguments.
1031 For quantifier free problems, all expressions are
1032 function applications.
1033 """
1034
1035 def as_ast(self):
1036 return self.astast
1037
1038 def get_id(self):
1039 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
1040
1041 def sort(self):
1042 """Return the sort of expression `self`.
1043
1044 >>> x = Int('x')
1045 >>> (x + 1).sort()
1046 Int
1047 >>> y = Real('y')
1048 >>> (x + y).sort()
1049 Real
1050 """
1051 return _sort(self.ctxctx, self.as_astas_ast())
1052
1053 def sort_kind(self):
1054 """Shorthand for `self.sort().kind()`.
1055
1056 >>> a = Array('a', IntSort(), IntSort())
1057 >>> a.sort_kind() == Z3_ARRAY_SORT
1058 True
1059 >>> a.sort_kind() == Z3_INT_SORT
1060 False
1061 """
1062 return self.sort().kind()
1063
1064 def __eq__(self, other):
1065 """Return a Z3 expression that represents the constraint `self == other`.
1066
1067 If `other` is `None`, then this method simply returns `False`.
1068
1069 >>> a = Int('a')
1070 >>> b = Int('b')
1071 >>> a == b
1072 a == b
1073 >>> a is None
1074 False
1075 """
1076 if other is None:
1077 return False
1078 a, b = _coerce_exprs(self, other)
1079 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
1080
1081 def __hash__(self):
1082 """ Hash code. """
1083 return AstRef.__hash__(self)
1084
1085 def __ne__(self, other):
1086 """Return a Z3 expression that represents the constraint `self != other`.
1087
1088 If `other` is `None`, then this method simply returns `True`.
1089
1090 >>> a = Int('a')
1091 >>> b = Int('b')
1092 >>> a != b
1093 a != b
1094 >>> a is not None
1095 True
1096 """
1097 if other is None:
1098 return True
1099 a, b = _coerce_exprs(self, other)
1100 _args, sz = _to_ast_array((a, b))
1101 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctxctx)
1102
1103 def params(self):
1104 return self.decl().params()
1105
1106 def decl(self):
1107 """Return the Z3 function declaration associated with a Z3 application.
1108
1109 >>> f = Function('f', IntSort(), IntSort())
1110 >>> a = Int('a')
1111 >>> t = f(a)
1112 >>> eq(t.decl(), f)
1113 True
1114 >>> (a + 1).decl()
1115 +
1116 """
1117 if z3_debug():
1118 _z3_assert(is_app(self), "Z3 application expected")
1119 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_astas_ast()), self.ctxctx)
1120
1121 def kind(self):
1122 """Return the Z3 internal kind of a function application."""
1123 if z3_debug():
1124 _z3_assert(is_app(self), "Z3 application expected")
1126
1127
1128 def num_args(self):
1129 """Return the number of arguments of a Z3 application.
1130
1131 >>> a = Int('a')
1132 >>> b = Int('b')
1133 >>> (a + b).num_args()
1134 2
1135 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1136 >>> t = f(a, b, 0)
1137 >>> t.num_args()
1138 3
1139 """
1140 if z3_debug():
1141 _z3_assert(is_app(self), "Z3 application expected")
1142 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_astas_ast()))
1143
1144 def arg(self, idx):
1145 """Return argument `idx` of the application `self`.
1146
1147 This method assumes that `self` is a function application with at least `idx+1` arguments.
1148
1149 >>> a = Int('a')
1150 >>> b = Int('b')
1151 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1152 >>> t = f(a, b, 0)
1153 >>> t.arg(0)
1154 a
1155 >>> t.arg(1)
1156 b
1157 >>> t.arg(2)
1158 0
1159 """
1160 if z3_debug():
1161 _z3_assert(is_app(self), "Z3 application expected")
1162 _z3_assert(idx < self.num_args(), "Invalid argument index")
1163 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_astas_ast(), idx), self.ctxctx)
1164
1165 def children(self):
1166 """Return a list containing the children of the given expression
1167
1168 >>> a = Int('a')
1169 >>> b = Int('b')
1170 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1171 >>> t = f(a, b, 0)
1172 >>> t.children()
1173 [a, b, 0]
1174 """
1175 if is_app(self):
1176 return [self.arg(i) for i in range(self.num_args())]
1177 else:
1178 return []
1179
1180 def update(self, *args):
1181 """Update the arguments of the expression.
1182
1183 Return a new expression with the same function declaration and updated arguments.
1184 The number of new arguments must match the current number of arguments.
1185
1186 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1187 >>> a = Int('a')
1188 >>> b = Int('b')
1189 >>> c = Int('c')
1190 >>> t = f(a, b)
1191 >>> t.update(c, c)
1192 f(c, c)
1193 """
1194 if z3_debug():
1195 _z3_assert(is_app(self), "Z3 application expected")
1196 _z3_assert(len(args) == self.num_args(), "Number of arguments does not match")
1197 _z3_assert(all([is_expr(arg) for arg in args]), "Z3 expressions expected")
1198 num = len(args)
1199 _args = (Ast * num)()
1200 for i in range(num):
1201 _args[i] = args[i].as_ast()
1202 return _to_expr_ref(Z3_update_term(self.ctx_ref(), self.as_astas_ast(), num, _args), self.ctxctx)
1203
1204 def from_string(self, s):
1205 pass
1206
1207 def serialize(self):
1208 s = Solver()
1209 f = Function('F', self.sort(), BoolSort(self.ctx))
1210 s.add(f(self))
1211 return s.sexpr()
1212
1214 """inverse function to the serialize method on ExprRef.
1215 It is made available to make it easier for users to serialize expressions back and forth between
1216 strings. Solvers can be serialized using the 'sexpr()' method.
1217 """
1218 s = Solver()
1219 s.from_string(st)
1220 if len(s.assertions()) != 1:
1221 raise Z3Exception("single assertion expected")
1222 fml = s.assertions()[0]
1223 if fml.num_args() != 1:
1224 raise Z3Exception("dummy function 'F' expected")
1225 return fml.arg(0)
1226
1227def _to_expr_ref(a, ctx):
1228 if isinstance(a, Pattern):
1229 return PatternRef(a, ctx)
1230 ctx_ref = ctx.ref()
1231 k = Z3_get_ast_kind(ctx_ref, a)
1232 if k == Z3_QUANTIFIER_AST:
1233 return QuantifierRef(a, ctx)
1234 # Check for finite set sort before checking sort kind
1235 s = Z3_get_sort(ctx_ref, a)
1236 if Z3_is_finite_set_sort(ctx_ref, s):
1237 return FiniteSetRef(a, ctx)
1238 sk = Z3_get_sort_kind(ctx_ref, s)
1239 if sk == Z3_BOOL_SORT:
1240 return BoolRef(a, ctx)
1241 if sk == Z3_INT_SORT:
1242 if k == Z3_NUMERAL_AST:
1243 return IntNumRef(a, ctx)
1244 return ArithRef(a, ctx)
1245 if sk == Z3_REAL_SORT:
1246 if k == Z3_NUMERAL_AST:
1247 return RatNumRef(a, ctx)
1248 if _is_algebraic(ctx, a):
1249 return AlgebraicNumRef(a, ctx)
1250 return ArithRef(a, ctx)
1251 if sk == Z3_COMPLEX_SORT:
1252 return ComplexRef(a, ctx)
1253 if sk == Z3_BV_SORT:
1254 if k == Z3_NUMERAL_AST:
1255 return BitVecNumRef(a, ctx)
1256 else:
1257 return BitVecRef(a, ctx)
1258 if sk == Z3_ARRAY_SORT:
1259 return ArrayRef(a, ctx)
1260 if sk == Z3_DATATYPE_SORT:
1261 return DatatypeRef(a, ctx)
1262 if sk == Z3_FLOATING_POINT_SORT:
1263 if k == Z3_APP_AST and _is_numeral(ctx, a):
1264 return FPNumRef(a, ctx)
1265 else:
1266 return FPRef(a, ctx)
1267 if sk == Z3_FINITE_FIELD_SORT:
1268 return FiniteFieldRef(a, ctx)
1269 if sk == Z3_FINITE_DOMAIN_SORT:
1270 if k == Z3_NUMERAL_AST:
1271 return FiniteDomainNumRef(a, ctx)
1272 else:
1273 return FiniteDomainRef(a, ctx)
1274 if sk == Z3_ROUNDING_MODE_SORT:
1275 return FPRMRef(a, ctx)
1276 if sk == Z3_SEQ_SORT:
1277 return SeqRef(a, ctx)
1278 if sk == Z3_CHAR_SORT:
1279 return CharRef(a, ctx)
1280 if sk == Z3_RE_SORT:
1281 return ReRef(a, ctx)
1282 return ExprRef(a, ctx)
1283
1284
1286 if is_expr(a):
1287 s1 = a.sort()
1288 if s is None:
1289 return s1
1290 if s1.eq(s):
1291 return s
1292 elif s.subsort(s1):
1293 return s1
1294 elif s1.subsort(s):
1295 return s
1296 else:
1297 if z3_debug():
1298 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1299 _z3_assert(False, "sort mismatch")
1300 else:
1301 return s
1302
1303def _check_same_sort(a, b, ctx=None):
1304 if not isinstance(a, ExprRef):
1305 return False
1306 if not isinstance(b, ExprRef):
1307 return False
1308 if ctx is None:
1309 ctx = a.ctx
1310
1311 a_sort = Z3_get_sort(ctx.ctx, a.ast)
1312 b_sort = Z3_get_sort(ctx.ctx, b.ast)
1313 return Z3_is_eq_sort(ctx.ctx, a_sort, b_sort)
1314
1315
1316def _coerce_exprs(a, b, ctx=None):
1317 if not is_expr(a) and not is_expr(b):
1318 a = _py2expr(a, ctx)
1319 b = _py2expr(b, ctx)
1320 if isinstance(a, str) and isinstance(b, SeqRef):
1321 a = StringVal(a, b.ctx)
1322 if isinstance(b, str) and isinstance(a, SeqRef):
1323 b = StringVal(b, a.ctx)
1324 if isinstance(a, float) and isinstance(b, ArithRef):
1325 a = RealVal(a, b.ctx)
1326 if isinstance(b, float) and isinstance(a, ArithRef):
1327 b = RealVal(b, a.ctx)
1328 if isinstance(a, complex) and is_expr(b):
1329 a = ComplexVal(a, ctx=b.ctx)
1330 if isinstance(b, complex) and is_expr(a):
1331 b = ComplexVal(b, ctx=a.ctx)
1332
1333 if _check_same_sort(a, b, ctx):
1334 return (a, b)
1335
1336 s = None
1337 s = _coerce_expr_merge(s, a)
1338 s = _coerce_expr_merge(s, b)
1339 a = s.cast(a)
1340 b = s.cast(b)
1341 return (a, b)
1342
1343
1344def _reduce(func, sequence, initial):
1345 result = initial
1346 for element in sequence:
1347 result = func(result, element)
1348 return result
1349
1350
1351def _coerce_expr_list(alist, ctx=None):
1352 has_expr = False
1353 for a in alist:
1354 if is_expr(a):
1355 has_expr = True
1356 break
1357 if not has_expr:
1358 alist = [_py2expr(a, ctx) for a in alist]
1359 else:
1360 ctx = ctx if ctx is not None else _ctx_from_ast_arg_list(alist)
1361 alist = [ComplexVal(a, ctx=ctx) if isinstance(a, complex) else a for a in alist]
1362 s = _reduce(_coerce_expr_merge, alist, None)
1363 return [s.cast(a) for a in alist]
1364
1365
1366def is_expr(a):
1367 """Return `True` if `a` is a Z3 expression.
1368
1369 >>> a = Int('a')
1370 >>> is_expr(a)
1371 True
1372 >>> is_expr(a + 1)
1373 True
1374 >>> is_expr(IntSort())
1375 False
1376 >>> is_expr(1)
1377 False
1378 >>> is_expr(IntVal(1))
1379 True
1380 >>> x = Int('x')
1381 >>> is_expr(ForAll(x, x >= 0))
1382 True
1383 >>> is_expr(FPVal(1.0))
1384 True
1385 """
1386 return isinstance(a, ExprRef)
1387
1388
1389def is_app(a):
1390 """Return `True` if `a` is a Z3 function application.
1391
1392 Note that, constants are function applications with 0 arguments.
1393
1394 >>> a = Int('a')
1395 >>> is_app(a)
1396 True
1397 >>> is_app(a + 1)
1398 True
1399 >>> is_app(IntSort())
1400 False
1401 >>> is_app(1)
1402 False
1403 >>> is_app(IntVal(1))
1404 True
1405 >>> x = Int('x')
1406 >>> is_app(ForAll(x, x >= 0))
1407 False
1408 """
1409 if not isinstance(a, ExprRef):
1410 return False
1411 k = _ast_kind(a.ctx, a)
1412 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1413
1414
1416 """Return `True` if `a` is Z3 constant/variable expression.
1417
1418 >>> a = Int('a')
1419 >>> is_const(a)
1420 True
1421 >>> is_const(a + 1)
1422 False
1423 >>> is_const(1)
1424 False
1425 >>> is_const(IntVal(1))
1426 True
1427 >>> x = Int('x')
1428 >>> is_const(ForAll(x, x >= 0))
1429 False
1430 """
1431 return is_app(a) and a.num_args() == 0
1432
1433
1434def is_var(a):
1435 """Return `True` if `a` is variable.
1436
1437 Z3 uses de-Bruijn indices for representing bound variables in
1438 quantifiers.
1439
1440 >>> x = Int('x')
1441 >>> is_var(x)
1442 False
1443 >>> is_const(x)
1444 True
1445 >>> f = Function('f', IntSort(), IntSort())
1446 >>> # Z3 replaces x with bound variables when ForAll is executed.
1447 >>> q = ForAll(x, f(x) == x)
1448 >>> b = q.body()
1449 >>> b
1450 f(Var(0)) == Var(0)
1451 >>> b.arg(1)
1452 Var(0)
1453 >>> is_var(b.arg(1))
1454 True
1455 """
1456 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1457
1458
1460 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1461
1462 >>> x = Int('x')
1463 >>> y = Int('y')
1464 >>> is_var(x)
1465 False
1466 >>> is_const(x)
1467 True
1468 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1469 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1470 >>> q = ForAll([x, y], f(x, y) == x + y)
1471 >>> q.body()
1472 f(Var(1), Var(0)) == Var(1) + Var(0)
1473 >>> b = q.body()
1474 >>> b.arg(0)
1475 f(Var(1), Var(0))
1476 >>> v1 = b.arg(0).arg(0)
1477 >>> v2 = b.arg(0).arg(1)
1478 >>> v1
1479 Var(1)
1480 >>> v2
1481 Var(0)
1482 >>> get_var_index(v1)
1483 1
1484 >>> get_var_index(v2)
1485 0
1486 """
1487 if z3_debug():
1488 _z3_assert(is_var(a), "Z3 bound variable expected")
1489 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1490
1491
1492def is_app_of(a, k):
1493 """Return `True` if `a` is an application of the given kind `k`.
1494
1495 >>> x = Int('x')
1496 >>> n = x + 1
1497 >>> is_app_of(n, Z3_OP_ADD)
1498 True
1499 >>> is_app_of(n, Z3_OP_MUL)
1500 False
1501 """
1502 return is_app(a) and a.kind() == k
1503
1504
1505def If(a, b, c, ctx=None):
1506 """Create a Z3 if-then-else expression.
1507
1508 >>> x = Int('x')
1509 >>> y = Int('y')
1510 >>> max = If(x > y, x, y)
1511 >>> max
1512 If(x > y, x, y)
1513 >>> simplify(max)
1514 If(x <= y, y, x)
1515 """
1516 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1517 return Cond(a, b, c, ctx)
1518 else:
1519 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1520 s = BoolSort(ctx)
1521 a = s.cast(a)
1522 b, c = _coerce_exprs(b, c, ctx)
1523 if z3_debug():
1524 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1525 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1526
1527
1528def Distinct(*args):
1529 """Create a Z3 distinct expression.
1530
1531 >>> x = Int('x')
1532 >>> y = Int('y')
1533 >>> Distinct(x, y)
1534 x != y
1535 >>> z = Int('z')
1536 >>> Distinct(x, y, z)
1537 Distinct(x, y, z)
1538 >>> simplify(Distinct(x, y, z))
1539 Distinct(x, y, z)
1540 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1541 And(Not(x == y), Not(x == z), Not(y == z))
1542 """
1543 args = _get_args(args)
1544 ctx = _ctx_from_ast_arg_list(args)
1545 if z3_debug():
1546 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1547 args = _coerce_expr_list(args, ctx)
1548 _args, sz = _to_ast_array(args)
1549 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1550
1551
1552def _mk_bin(f, a, b):
1553 args = (Ast * 2)()
1554 if z3_debug():
1555 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1556 args[0] = a.as_ast()
1557 args[1] = b.as_ast()
1558 return f(a.ctx.ref(), 2, args)
1559
1560
1561def Const(name, sort):
1562 """Create a constant of the given sort.
1563
1564 >>> Const('x', IntSort())
1565 x
1566 """
1567 if z3_debug():
1568 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1569 ctx = sort.ctx
1570 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1571
1572
1573def Consts(names, sort):
1574 """Create several constants of the given sort.
1575
1576 `names` is a string containing the names of all constants to be created.
1577 Blank spaces separate the names of different constants.
1578
1579 >>> x, y, z = Consts('x y z', IntSort())
1580 >>> x + y + z
1581 x + y + z
1582 """
1583 if isinstance(names, str):
1584 names = names.split(" ")
1585 return [Const(name, sort) for name in names]
1586
1587
1588def FreshConst(sort, prefix="c"):
1589 """Create a fresh constant of a specified sort"""
1590 if z3_debug():
1591 _z3_assert(is_sort(sort), f"Z3 sort expected, got {type(sort)}")
1592 ctx = _get_ctx(sort.ctx)
1593 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1594
1595
1596def Var(idx : int, s : SortRef) -> ExprRef:
1597 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1598 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1599 declarations.
1600
1601 >>> Var(0, IntSort())
1602 Var(0)
1603 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1604 False
1605 """
1606 if z3_debug():
1607 _z3_assert(is_sort(s), "Z3 sort expected")
1608 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1609
1610
1611def RealVar(idx: int, ctx=None) -> ExprRef:
1612 """
1613 Create a real free variable. Free variables are used to create quantified formulas.
1614 They are also used to create polynomials.
1615
1616 >>> RealVar(0)
1617 Var(0)
1618 """
1619 return Var(idx, RealSort(ctx))
1620
1621def RealVarVector(n: int, ctx= None):
1622 """
1623 Create a list of Real free variables.
1624 The variables have ids: 0, 1, ..., n-1
1625
1626 >>> x0, x1, x2, x3 = RealVarVector(4)
1627 >>> x2
1628 Var(2)
1629 """
1630 return [RealVar(i, ctx) for i in range(n)]
1631
1632
1637
1638
1640 """Boolean sort."""
1641
1642 def cast(self, val):
1643 """Try to cast `val` as a Boolean.
1644
1645 >>> x = BoolSort().cast(True)
1646 >>> x
1647 True
1648 >>> is_expr(x)
1649 True
1650 >>> is_expr(True)
1651 False
1652 >>> x.sort()
1653 Bool
1654 """
1655 if isinstance(val, bool):
1656 return BoolVal(val, self.ctxctxctx)
1657 if z3_debug():
1658 if not is_expr(val):
1659 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1660 _z3_assert(is_expr(val), msg % (val, type(val)))
1661 if not self.eq(val.sort()):
1662 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1663 return val
1664
1665 def subsort(self, other):
1666 return isinstance(other, ArithSortRef)
1667
1668 def is_int(self):
1669 return True
1670
1671 def is_bool(self):
1672 return True
1673
1674
1676 """All Boolean expressions are instances of this class."""
1677
1678 def sort(self):
1680
1681 def __add__(self, other):
1682 if isinstance(other, BoolRef):
1683 other = If(other, 1, 0)
1684 return If(self, 1, 0) + other
1685
1686 def __radd__(self, other):
1687 return self + other
1688
1689 def __rmul__(self, other):
1690 return self * other
1691
1692 def __mul__(self, other):
1693 """Create the Z3 expression `self * other`.
1694 """
1695 if isinstance(other, int) and other == 1:
1696 return If(self, 1, 0)
1697 if isinstance(other, int) and other == 0:
1698 return IntVal(0, self.ctxctxctx)
1699 if isinstance(other, BoolRef):
1700 other = If(other, 1, 0)
1701 return If(self, other, 0)
1702
1703 def __and__(self, other):
1704 return And(self, other)
1705
1706 def __or__(self, other):
1707 return Or(self, other)
1708
1709 def __xor__(self, other):
1710 return Xor(self, other)
1711
1712 def __invert__(self):
1713 return Not(self)
1714
1715 def py_value(self):
1716 if is_true(self):
1717 return True
1718 if is_false(self):
1719 return False
1720 return None
1721
1722
1723
1724
1725def is_bool(a : Any) -> bool:
1726 """Return `True` if `a` is a Z3 Boolean expression.
1727
1728 >>> p = Bool('p')
1729 >>> is_bool(p)
1730 True
1731 >>> q = Bool('q')
1732 >>> is_bool(And(p, q))
1733 True
1734 >>> x = Real('x')
1735 >>> is_bool(x)
1736 False
1737 >>> is_bool(x == 0)
1738 True
1739 """
1740 return isinstance(a, BoolRef)
1741
1742
1743def is_true(a : Any) -> bool:
1744 """Return `True` if `a` is the Z3 true expression.
1745
1746 >>> p = Bool('p')
1747 >>> is_true(p)
1748 False
1749 >>> is_true(simplify(p == p))
1750 True
1751 >>> x = Real('x')
1752 >>> is_true(x == 0)
1753 False
1754 >>> # True is a Python Boolean expression
1755 >>> is_true(True)
1756 False
1757 """
1758 return is_app_of(a, Z3_OP_TRUE)
1759
1760
1761def is_false(a : Any) -> bool:
1762 """Return `True` if `a` is the Z3 false expression.
1763
1764 >>> p = Bool('p')
1765 >>> is_false(p)
1766 False
1767 >>> is_false(False)
1768 False
1769 >>> is_false(BoolVal(False))
1770 True
1771 """
1772 return is_app_of(a, Z3_OP_FALSE)
1773
1774
1775def is_and(a : Any) -> bool:
1776 """Return `True` if `a` is a Z3 and expression.
1777
1778 >>> p, q = Bools('p q')
1779 >>> is_and(And(p, q))
1780 True
1781 >>> is_and(Or(p, q))
1782 False
1783 """
1784 return is_app_of(a, Z3_OP_AND)
1785
1786
1787def is_or(a : Any) -> bool:
1788 """Return `True` if `a` is a Z3 or expression.
1789
1790 >>> p, q = Bools('p q')
1791 >>> is_or(Or(p, q))
1792 True
1793 >>> is_or(And(p, q))
1794 False
1795 """
1796 return is_app_of(a, Z3_OP_OR)
1797
1798
1799def is_implies(a : Any) -> bool:
1800 """Return `True` if `a` is a Z3 implication expression.
1801
1802 >>> p, q = Bools('p q')
1803 >>> is_implies(Implies(p, q))
1804 True
1805 >>> is_implies(And(p, q))
1806 False
1807 """
1808 return is_app_of(a, Z3_OP_IMPLIES)
1809
1810
1811def is_not(a : Any) -> bool:
1812 """Return `True` if `a` is a Z3 not expression.
1813
1814 >>> p = Bool('p')
1815 >>> is_not(p)
1816 False
1817 >>> is_not(Not(p))
1818 True
1819 """
1820 return is_app_of(a, Z3_OP_NOT)
1821
1822
1823def is_eq(a : Any) -> bool:
1824 """Return `True` if `a` is a Z3 equality expression.
1825
1826 >>> x, y = Ints('x y')
1827 >>> is_eq(x == y)
1828 True
1829 """
1830 return is_app_of(a, Z3_OP_EQ)
1831
1832
1833def is_distinct(a : Any) -> bool:
1834 """Return `True` if `a` is a Z3 distinct expression.
1835
1836 >>> x, y, z = Ints('x y z')
1837 >>> is_distinct(x == y)
1838 False
1839 >>> is_distinct(Distinct(x, y, z))
1840 True
1841 """
1842 return is_app_of(a, Z3_OP_DISTINCT)
1843
1844
1845def BoolSort(ctx=None):
1846 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1847
1848 >>> BoolSort()
1849 Bool
1850 >>> p = Const('p', BoolSort())
1851 >>> is_bool(p)
1852 True
1853 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1854 >>> r(0, 1)
1855 r(0, 1)
1856 >>> is_bool(r(0, 1))
1857 True
1858 """
1859 ctx = _get_ctx(ctx)
1860 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1861
1862
1863def BoolVal(val, ctx=None):
1864 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1865
1866 >>> BoolVal(True)
1867 True
1868 >>> is_true(BoolVal(True))
1869 True
1870 >>> is_true(True)
1871 False
1872 >>> is_false(BoolVal(False))
1873 True
1874 """
1875 ctx = _get_ctx(ctx)
1876 if val:
1877 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1878 else:
1879 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1880
1881
1882def Bool(name, ctx=None):
1883 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1884
1885 >>> p = Bool('p')
1886 >>> q = Bool('q')
1887 >>> And(p, q)
1888 And(p, q)
1889 """
1890 ctx = _get_ctx(ctx)
1891 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1892
1893
1894def Bools(names, ctx=None):
1895 """Return a tuple of Boolean constants.
1896
1897 `names` is a single string containing all names separated by blank spaces.
1898 If `ctx=None`, then the global context is used.
1899
1900 >>> p, q, r = Bools('p q r')
1901 >>> And(p, Or(q, r))
1902 And(p, Or(q, r))
1903 """
1904 ctx = _get_ctx(ctx)
1905 if isinstance(names, str):
1906 names = names.split(" ")
1907 return [Bool(name, ctx) for name in names]
1908
1909
1910def BoolVector(prefix, sz, ctx=None):
1911 """Return a list of Boolean constants of size `sz`.
1912
1913 The constants are named using the given prefix.
1914 If `ctx=None`, then the global context is used.
1915
1916 >>> P = BoolVector('p', 3)
1917 >>> P
1918 [p__0, p__1, p__2]
1919 >>> And(P)
1920 And(p__0, p__1, p__2)
1921 """
1922 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1923
1924
1925def FreshBool(prefix="b", ctx=None):
1926 """Return a fresh Boolean constant in the given context using the given prefix.
1927
1928 If `ctx=None`, then the global context is used.
1929
1930 >>> b1 = FreshBool()
1931 >>> b2 = FreshBool()
1932 >>> eq(b1, b2)
1933 False
1934 """
1935 ctx = _get_ctx(ctx)
1936 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1937
1938
1939def Implies(a, b, ctx=None):
1940 """Create a Z3 implies expression.
1941
1942 >>> p, q = Bools('p q')
1943 >>> Implies(p, q)
1944 Implies(p, q)
1945 """
1946 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1947 s = BoolSort(ctx)
1948 a = s.cast(a)
1949 b = s.cast(b)
1950 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1951
1952
1953def Xor(a, b, ctx=None):
1954 """Create a Z3 Xor expression.
1955
1956 >>> p, q = Bools('p q')
1957 >>> Xor(p, q)
1958 Xor(p, q)
1959 >>> simplify(Xor(p, q))
1960 Not(p == q)
1961 """
1962 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1963 s = BoolSort(ctx)
1964 a = s.cast(a)
1965 b = s.cast(b)
1966 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1967
1968
1969def Not(a, ctx=None):
1970 """Create a Z3 not expression or probe.
1971
1972 >>> p = Bool('p')
1973 >>> Not(Not(p))
1974 Not(Not(p))
1975 >>> simplify(Not(Not(p)))
1976 p
1977 """
1978 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1979 if is_probe(a):
1980 # Not is also used to build probes
1981 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1982 else:
1983 s = BoolSort(ctx)
1984 a = s.cast(a)
1985 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1986
1987
1988def mk_not(a):
1989 if is_not(a):
1990 return a.arg(0)
1991 else:
1992 return Not(a)
1993
1994
1995def _has_probe(args):
1996 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1997 for arg in args:
1998 if is_probe(arg):
1999 return True
2000 return False
2001
2002
2003def And(*args):
2004 """Create a Z3 and-expression or and-probe.
2005
2006 >>> p, q, r = Bools('p q r')
2007 >>> And(p, q, r)
2008 And(p, q, r)
2009 >>> P = BoolVector('p', 5)
2010 >>> And(P)
2011 And(p__0, p__1, p__2, p__3, p__4)
2012 """
2013 last_arg = None
2014 if len(args) > 0:
2015 last_arg = args[len(args) - 1]
2016 if isinstance(last_arg, Context):
2017 ctx = args[len(args) - 1]
2018 args = args[:len(args) - 1]
2019 elif len(args) == 1 and isinstance(args[0], AstVector):
2020 ctx = args[0].ctx
2021 args = [a for a in args[0]]
2022 else:
2023 ctx = None
2024 args = _get_args(args)
2025 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2026 if z3_debug():
2027 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2028 if _has_probe(args):
2029 return _probe_and(args, ctx)
2030 else:
2031 args = _coerce_expr_list(args, ctx)
2032 _args, sz = _to_ast_array(args)
2033 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
2034
2035
2036def Or(*args):
2037 """Create a Z3 or-expression or or-probe.
2038
2039 >>> p, q, r = Bools('p q r')
2040 >>> Or(p, q, r)
2041 Or(p, q, r)
2042 >>> P = BoolVector('p', 5)
2043 >>> Or(P)
2044 Or(p__0, p__1, p__2, p__3, p__4)
2045 """
2046 last_arg = None
2047 if len(args) > 0:
2048 last_arg = args[len(args) - 1]
2049 if isinstance(last_arg, Context):
2050 ctx = args[len(args) - 1]
2051 args = args[:len(args) - 1]
2052 elif len(args) == 1 and isinstance(args[0], AstVector):
2053 ctx = args[0].ctx
2054 args = [a for a in args[0]]
2055 else:
2056 ctx = None
2057 args = _get_args(args)
2058 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2059 if z3_debug():
2060 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2061 if _has_probe(args):
2062 return _probe_or(args, ctx)
2063 else:
2064 args = _coerce_expr_list(args, ctx)
2065 _args, sz = _to_ast_array(args)
2066 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
2067
2068
2073
2074
2076 """Patterns are hints for quantifier instantiation.
2077
2078 """
2079
2080 def as_ast(self):
2082
2083 def get_id(self):
2084 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
2085
2086
2088 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2089
2090 >>> f = Function('f', IntSort(), IntSort())
2091 >>> x = Int('x')
2092 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2093 >>> q
2094 ForAll(x, f(x) == 0)
2095 >>> q.num_patterns()
2096 1
2097 >>> is_pattern(q.pattern(0))
2098 True
2099 >>> q.pattern(0)
2100 f(Var(0))
2101 """
2102 return isinstance(a, PatternRef)
2103
2104
2105def MultiPattern(*args):
2106 """Create a Z3 multi-pattern using the given expressions `*args`
2107
2108 >>> f = Function('f', IntSort(), IntSort())
2109 >>> g = Function('g', IntSort(), IntSort())
2110 >>> x = Int('x')
2111 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2112 >>> q
2113 ForAll(x, f(x) != g(x))
2114 >>> q.num_patterns()
2115 1
2116 >>> is_pattern(q.pattern(0))
2117 True
2118 >>> q.pattern(0)
2119 MultiPattern(f(Var(0)), g(Var(0)))
2120 """
2121 if z3_debug():
2122 _z3_assert(len(args) > 0, "At least one argument expected")
2123 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
2124 ctx = args[0].ctx
2125 args, sz = _to_ast_array(args)
2126 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
2127
2128
2130 if is_pattern(arg):
2131 return arg
2132 else:
2133 return MultiPattern(arg)
2134
2135
2140
2141
2143 """Universally and Existentially quantified formulas."""
2144
2145 def as_ast(self):
2146 return self.astastast
2147
2148 def get_id(self):
2149 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
2150
2151 def sort(self):
2152 """Return the Boolean sort or sort of Lambda."""
2153 if self.is_lambda():
2155 return BoolSort(self.ctxctxctxctx)
2156
2157 def is_forall(self):
2158 """Return `True` if `self` is a universal quantifier.
2159
2160 >>> f = Function('f', IntSort(), IntSort())
2161 >>> x = Int('x')
2162 >>> q = ForAll(x, f(x) == 0)
2163 >>> q.is_forall()
2164 True
2165 >>> q = Exists(x, f(x) != 0)
2166 >>> q.is_forall()
2167 False
2168 """
2170
2171 def is_exists(self):
2172 """Return `True` if `self` is an existential quantifier.
2173
2174 >>> f = Function('f', IntSort(), IntSort())
2175 >>> x = Int('x')
2176 >>> q = ForAll(x, f(x) == 0)
2177 >>> q.is_exists()
2178 False
2179 >>> q = Exists(x, f(x) != 0)
2180 >>> q.is_exists()
2181 True
2182 """
2183 return Z3_is_quantifier_exists(self.ctx_ref(), self.astastast)
2184
2185 def is_lambda(self):
2186 """Return `True` if `self` is a lambda expression.
2187
2188 >>> f = Function('f', IntSort(), IntSort())
2189 >>> x = Int('x')
2190 >>> q = Lambda(x, f(x))
2191 >>> q.is_lambda()
2192 True
2193 >>> q = Exists(x, f(x) != 0)
2194 >>> q.is_lambda()
2195 False
2196 """
2197 return Z3_is_lambda(self.ctx_ref(), self.astastast)
2198
2199 def __getitem__(self, arg):
2200 """Return the Z3 expression `self[arg]`.
2201 """
2202 if z3_debug():
2203 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2204 return _array_select(self, arg)
2205
2206 def weight(self):
2207 """Return the weight annotation of `self`.
2208
2209 >>> f = Function('f', IntSort(), IntSort())
2210 >>> x = Int('x')
2211 >>> q = ForAll(x, f(x) == 0)
2212 >>> q.weight()
2213 1
2214 >>> q = ForAll(x, f(x) == 0, weight=10)
2215 >>> q.weight()
2216 10
2217 """
2218 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.astastast))
2219
2220 def skolem_id(self):
2221 """Return the skolem id of `self`.
2222 """
2224
2225 def qid(self):
2226 """Return the quantifier id of `self`.
2227 """
2229
2230 def num_patterns(self):
2231 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2232
2233 >>> f = Function('f', IntSort(), IntSort())
2234 >>> g = Function('g', IntSort(), IntSort())
2235 >>> x = Int('x')
2236 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2237 >>> q.num_patterns()
2238 2
2239 """
2240 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.astastast))
2241
2242 def pattern(self, idx):
2243 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2244
2245 >>> f = Function('f', IntSort(), IntSort())
2246 >>> g = Function('g', IntSort(), IntSort())
2247 >>> x = Int('x')
2248 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2249 >>> q.num_patterns()
2250 2
2251 >>> q.pattern(0)
2252 f(Var(0))
2253 >>> q.pattern(1)
2254 g(Var(0))
2255 """
2256 if z3_debug():
2257 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2259
2261 """Return the number of no-patterns."""
2263
2264 def no_pattern(self, idx):
2265 """Return a no-pattern."""
2266 if z3_debug():
2267 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2269
2270 def body(self):
2271 """Return the expression being quantified.
2272
2273 >>> f = Function('f', IntSort(), IntSort())
2274 >>> x = Int('x')
2275 >>> q = ForAll(x, f(x) == 0)
2276 >>> q.body()
2277 f(Var(0)) == 0
2278 """
2280
2281 def num_vars(self):
2282 """Return the number of variables bounded by this quantifier.
2283
2284 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2285 >>> x = Int('x')
2286 >>> y = Int('y')
2287 >>> q = ForAll([x, y], f(x, y) >= x)
2288 >>> q.num_vars()
2289 2
2290 """
2291 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.astastast))
2292
2293 def var_name(self, idx):
2294 """Return a string representing a name used when displaying the quantifier.
2295
2296 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2297 >>> x = Int('x')
2298 >>> y = Int('y')
2299 >>> q = ForAll([x, y], f(x, y) >= x)
2300 >>> q.var_name(0)
2301 'x'
2302 >>> q.var_name(1)
2303 'y'
2304 """
2305 if z3_debug():
2306 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2308
2309 def var_sort(self, idx):
2310 """Return the sort of a bound variable.
2311
2312 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2313 >>> x = Int('x')
2314 >>> y = Real('y')
2315 >>> q = ForAll([x, y], f(x, y) >= x)
2316 >>> q.var_sort(0)
2317 Int
2318 >>> q.var_sort(1)
2319 Real
2320 """
2321 if z3_debug():
2322 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2324
2325 def children(self):
2326 """Return a list containing a single element self.body()
2327
2328 >>> f = Function('f', IntSort(), IntSort())
2329 >>> x = Int('x')
2330 >>> q = ForAll(x, f(x) == 0)
2331 >>> q.children()
2332 [f(Var(0)) == 0]
2333 """
2334 return [self.body()]
2335
2336
2338 """Return `True` if `a` is a Z3 quantifier.
2339
2340 >>> f = Function('f', IntSort(), IntSort())
2341 >>> x = Int('x')
2342 >>> q = ForAll(x, f(x) == 0)
2343 >>> is_quantifier(q)
2344 True
2345 >>> is_quantifier(f(x))
2346 False
2347 """
2348 return isinstance(a, QuantifierRef)
2349
2350
2351def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2352 if z3_debug():
2353 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2354 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2355 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2356 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2357 if is_app(vs):
2358 ctx = vs.ctx
2359 vs = [vs]
2360 else:
2361 ctx = vs[0].ctx
2362 if not is_expr(body):
2363 body = BoolVal(body, ctx)
2364 num_vars = len(vs)
2365 if num_vars == 0:
2366 return body
2367 _vs = (Ast * num_vars)()
2368 for i in range(num_vars):
2369 # TODO: Check if is constant
2370 _vs[i] = vs[i].as_ast()
2371 patterns = [_to_pattern(p) for p in patterns]
2372 num_pats = len(patterns)
2373 _pats = (Pattern * num_pats)()
2374 for i in range(num_pats):
2375 _pats[i] = patterns[i].ast
2376 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2377 qid = to_symbol(qid, ctx)
2378 skid = to_symbol(skid, ctx)
2379 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2380 num_vars, _vs,
2381 num_pats, _pats,
2382 num_no_pats, _no_pats,
2383 body.as_ast()), ctx)
2384
2385
2386def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2387 """Create a Z3 forall formula.
2388
2389 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2390
2391 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2392 >>> x = Int('x')
2393 >>> y = Int('y')
2394 >>> ForAll([x, y], f(x, y) >= x)
2395 ForAll([x, y], f(x, y) >= x)
2396 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2397 ForAll([x, y], f(x, y) >= x)
2398 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2399 ForAll([x, y], f(x, y) >= x)
2400 """
2401 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2402
2403
2404def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2405 """Create a Z3 exists formula.
2406
2407 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2408
2409
2410 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2411 >>> x = Int('x')
2412 >>> y = Int('y')
2413 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2414 >>> q
2415 Exists([x, y], f(x, y) >= x)
2416 >>> is_quantifier(q)
2417 True
2418 >>> r = Tactic('nnf')(q).as_expr()
2419 >>> is_quantifier(r)
2420 False
2421 """
2422 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2423
2424
2425def Lambda(vs, body):
2426 """Create a Z3 lambda expression.
2427
2428 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2429 >>> mem0 = Array('mem0', IntSort(), IntSort())
2430 >>> lo, hi, e, i = Ints('lo hi e i')
2431 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2432 >>> mem1
2433 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2434 """
2435 ctx = body.ctx
2436 if is_app(vs):
2437 vs = [vs]
2438 num_vars = len(vs)
2439 _vs = (Ast * num_vars)()
2440 for i in range(num_vars):
2441 # TODO: Check if is constant
2442 _vs[i] = vs[i].as_ast()
2443 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2444
2445
2450
2451
2453 """Real and Integer sorts."""
2454
2455 def is_real(self):
2456 """Return `True` if `self` is of the sort Real.
2457
2458 >>> x = Real('x')
2459 >>> x.is_real()
2460 True
2461 >>> (x + 1).is_real()
2462 True
2463 >>> x = Int('x')
2464 >>> x.is_real()
2465 False
2466 """
2467 return self.kind() == Z3_REAL_SORT
2468
2469 def is_int(self):
2470 """Return `True` if `self` is of the sort Integer.
2471
2472 >>> x = Int('x')
2473 >>> x.is_int()
2474 True
2475 >>> (x + 1).is_int()
2476 True
2477 >>> x = Real('x')
2478 >>> x.is_int()
2479 False
2480 """
2481 return self.kind() == Z3_INT_SORT
2482
2483 def is_bool(self):
2484 return False
2485
2486 def subsort(self, other):
2487 """Return `True` if `self` is a subsort of `other`."""
2488 return is_complex_sort(other) or (self.is_int() and is_arith_sort(other) and other.is_real())
2489
2490 def cast(self, val):
2491 """Try to cast `val` as an Integer or Real.
2492
2493 >>> IntSort().cast(10)
2494 10
2495 >>> is_int(IntSort().cast(10))
2496 True
2497 >>> is_int(10)
2498 False
2499 >>> RealSort().cast(10)
2500 10
2501 >>> is_real(RealSort().cast(10))
2502 True
2503 """
2504 if is_expr(val):
2505 if z3_debug():
2506 _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
2507 val_s = val.sort()
2508 if self.eq(val_s):
2509 return val
2510 if val_s.is_int() and self.is_real():
2511 return ToReal(val)
2512 if val_s.is_bool() and self.is_int():
2513 return If(val, 1, 0)
2514 if val_s.is_bool() and self.is_real():
2515 return ToReal(If(val, 1, 0))
2516 if z3_debug():
2517 _z3_assert(False, "Z3 Integer/Real expression expected")
2518 else:
2519 if self.is_int():
2520 return IntVal(val, self.ctxctxctx)
2521 if self.is_real():
2522 return RealVal(val, self.ctxctxctx)
2523 if z3_debug():
2524 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2525 _z3_assert(False, msg % self)
2526
2527
2528def is_arith_sort(s : Any) -> bool:
2529 """Return `True` if s is an arithmetical sort (type).
2530
2531 >>> is_arith_sort(IntSort())
2532 True
2533 >>> is_arith_sort(RealSort())
2534 True
2535 >>> is_arith_sort(BoolSort())
2536 False
2537 >>> n = Int('x') + 1
2538 >>> is_arith_sort(n.sort())
2539 True
2540 """
2541 return isinstance(s, ArithSortRef)
2542
2543
2545 """Integer, Real, and Complex expressions."""
2546
2547 def sort(self):
2548 """Return the sort (type) of the arithmetical expression `self`.
2549
2550 >>> Int('x').sort()
2551 Int
2552 >>> (Real('x') + 1).sort()
2553 Real
2554 """
2556
2557 def is_int(self):
2558 """Return `True` if `self` is an integer expression.
2559
2560 >>> x = Int('x')
2561 >>> x.is_int()
2562 True
2563 >>> (x + 1).is_int()
2564 True
2565 >>> y = Real('y')
2566 >>> (x + y).is_int()
2567 False
2568 """
2569 return self.sortsort().is_int()
2570
2571 def is_real(self):
2572 """Return `True` if `self` is an real expression.
2573
2574 >>> x = Real('x')
2575 >>> x.is_real()
2576 True
2577 >>> (x + 1).is_real()
2578 True
2579 """
2580 return self.sortsort().is_real()
2581
2582 def __add__(self, other):
2583 """Create the Z3 expression `self + other`.
2584
2585 >>> x = Int('x')
2586 >>> y = Int('y')
2587 >>> x + y
2588 x + y
2589 >>> (x + y).sort()
2590 Int
2591 """
2592 a, b = _coerce_exprs(self, other)
2593 return _to_expr_ref(_mk_bin(Z3_mk_add, a, b), self.ctxctxctx)
2594
2595 def __radd__(self, other):
2596 """Create the Z3 expression `other + self`.
2597
2598 >>> x = Int('x')
2599 >>> 10 + x
2600 10 + x
2601 """
2602 a, b = _coerce_exprs(self, other)
2603 return _to_expr_ref(_mk_bin(Z3_mk_add, b, a), self.ctxctxctx)
2604
2605 def __mul__(self, other):
2606 """Create the Z3 expression `self * other`.
2607
2608 >>> x = Real('x')
2609 >>> y = Real('y')
2610 >>> x * y
2611 x*y
2612 >>> (x * y).sort()
2613 Real
2614 """
2615 if isinstance(other, BoolRef):
2616 return If(other, self, 0)
2617 a, b = _coerce_exprs(self, other)
2618 return _to_expr_ref(_mk_bin(Z3_mk_mul, a, b), self.ctxctxctx)
2619
2620 def __rmul__(self, other):
2621 """Create the Z3 expression `other * self`.
2622
2623 >>> x = Real('x')
2624 >>> 10 * x
2625 10*x
2626 """
2627 a, b = _coerce_exprs(self, other)
2628 return _to_expr_ref(_mk_bin(Z3_mk_mul, b, a), self.ctxctxctx)
2629
2630 def __sub__(self, other):
2631 """Create the Z3 expression `self - other`.
2632
2633 >>> x = Int('x')
2634 >>> y = Int('y')
2635 >>> x - y
2636 x - y
2637 >>> (x - y).sort()
2638 Int
2639 """
2640 a, b = _coerce_exprs(self, other)
2641 return _to_expr_ref(_mk_bin(Z3_mk_sub, a, b), self.ctxctxctx)
2642
2643 def __rsub__(self, other):
2644 """Create the Z3 expression `other - self`.
2645
2646 >>> x = Int('x')
2647 >>> 10 - x
2648 10 - x
2649 """
2650 a, b = _coerce_exprs(self, other)
2651 return _to_expr_ref(_mk_bin(Z3_mk_sub, b, a), self.ctxctxctx)
2652
2653 def __pow__(self, other):
2654 """Create the Z3 expression `self**other` (** is the power operator).
2655
2656 >>> x = Real('x')
2657 >>> x**3
2658 x**3
2659 >>> (x**3).sort()
2660 Real
2661 >>> simplify(IntVal(2)**8)
2662 256
2663 """
2664 a, b = _coerce_exprs(self, other)
2665 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2666
2667 def __rpow__(self, other):
2668 """Create the Z3 expression `other**self` (** is the power operator).
2669
2670 >>> x = Real('x')
2671 >>> 2**x
2672 2**x
2673 >>> (2**x).sort()
2674 Real
2675 >>> simplify(2**IntVal(8))
2676 256
2677 """
2678 a, b = _coerce_exprs(self, other)
2679 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2680
2681 def __div__(self, other):
2682 """Create the Z3 expression `other/self`.
2683
2684 >>> x = Int('x')
2685 >>> y = Int('y')
2686 >>> x/y
2687 x/y
2688 >>> (x/y).sort()
2689 Int
2690 >>> (x/y).sexpr()
2691 '(div x y)'
2692 >>> x = Real('x')
2693 >>> y = Real('y')
2694 >>> x/y
2695 x/y
2696 >>> (x/y).sort()
2697 Real
2698 >>> (x/y).sexpr()
2699 '(/ x y)'
2700 """
2701 a, b = _coerce_exprs(self, other)
2702 return _to_expr_ref(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2703
2704 def __truediv__(self, other):
2705 """Create the Z3 expression `other/self`."""
2706 return self.__div__(other)
2707
2708 def __rdiv__(self, other):
2709 """Create the Z3 expression `other/self`.
2710
2711 >>> x = Int('x')
2712 >>> 10/x
2713 10/x
2714 >>> (10/x).sexpr()
2715 '(div 10 x)'
2716 >>> x = Real('x')
2717 >>> 10/x
2718 10/x
2719 >>> (10/x).sexpr()
2720 '(/ 10.0 x)'
2721 """
2722 a, b = _coerce_exprs(self, other)
2723 return _to_expr_ref(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2724
2725 def __rtruediv__(self, other):
2726 """Create the Z3 expression `other/self`."""
2727 return self.__rdiv__(other)
2728
2729 def __mod__(self, other):
2730 """Create the Z3 expression `other%self`.
2731
2732 >>> x = Int('x')
2733 >>> y = Int('y')
2734 >>> x % y
2735 x%y
2736 >>> simplify(IntVal(10) % IntVal(3))
2737 1
2738 """
2739 a, b = _coerce_exprs(self, other)
2740 if z3_debug():
2741 _z3_assert(a.is_int(), "Z3 integer expression expected")
2742 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2743
2744 def __rmod__(self, other):
2745 """Create the Z3 expression `other%self`.
2746
2747 >>> x = Int('x')
2748 >>> 10 % x
2749 10%x
2750 """
2751 a, b = _coerce_exprs(self, other)
2752 if z3_debug():
2753 _z3_assert(a.is_int(), "Z3 integer expression expected")
2754 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2755
2756 def __neg__(self):
2757 """Return an expression representing `-self`.
2758
2759 >>> x = Int('x')
2760 >>> -x
2761 -x
2762 >>> simplify(-(-x))
2763 x
2764 """
2765 return _to_expr_ref(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
2766
2767 def __pos__(self):
2768 """Return `self`.
2769
2770 >>> x = Int('x')
2771 >>> +x
2772 x
2773 """
2774 return self
2775
2776 def __le__(self, other):
2777 """Create the Z3 expression `other <= self`.
2778
2779 >>> x, y = Ints('x y')
2780 >>> x <= y
2781 x <= y
2782 >>> y = Real('y')
2783 >>> x <= y
2784 ToReal(x) <= y
2785 """
2786 a, b = _coerce_exprs(self, other)
2787 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2788
2789 def __lt__(self, other):
2790 """Create the Z3 expression `other < self`.
2791
2792 >>> x, y = Ints('x y')
2793 >>> x < y
2794 x < y
2795 >>> y = Real('y')
2796 >>> x < y
2797 ToReal(x) < y
2798 """
2799 a, b = _coerce_exprs(self, other)
2800 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2801
2802 def __gt__(self, other):
2803 """Create the Z3 expression `other > self`.
2804
2805 >>> x, y = Ints('x y')
2806 >>> x > y
2807 x > y
2808 >>> y = Real('y')
2809 >>> x > y
2810 ToReal(x) > y
2811 """
2812 a, b = _coerce_exprs(self, other)
2813 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2814
2815 def __ge__(self, other):
2816 """Create the Z3 expression `other >= self`.
2817
2818 >>> x, y = Ints('x y')
2819 >>> x >= y
2820 x >= y
2821 >>> y = Real('y')
2822 >>> x >= y
2823 ToReal(x) >= y
2824 """
2825 a, b = _coerce_exprs(self, other)
2826 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2827
2828 def __abs__(self):
2829 """Return an expression representing `abs(self)`.
2830
2831 >>> x = Int('x')
2832 >>> abs(x)
2833 If(x > 0, x, -x)
2834 >>> eq(abs(x), Abs(x))
2835 True
2836 """
2837 return Abs(self)
2838
2839
2841 """Return `True` if `a` is an arithmetical expression.
2842
2843 >>> x = Int('x')
2844 >>> is_arith(x)
2845 True
2846 >>> is_arith(x + 1)
2847 True
2848 >>> is_arith(1)
2849 False
2850 >>> is_arith(IntVal(1))
2851 True
2852 >>> y = Real('y')
2853 >>> is_arith(y)
2854 True
2855 >>> is_arith(y + 1)
2856 True
2857 """
2858 return isinstance(a, ArithRef)
2859
2860
2861def is_int(a) -> bool:
2862 """Return `True` if `a` is an integer expression.
2863
2864 >>> x = Int('x')
2865 >>> is_int(x + 1)
2866 True
2867 >>> is_int(1)
2868 False
2869 >>> is_int(IntVal(1))
2870 True
2871 >>> y = Real('y')
2872 >>> is_int(y)
2873 False
2874 >>> is_int(y + 1)
2875 False
2876 """
2877 return is_arith(a) and a.is_int()
2878
2879
2880def is_real(a):
2881 """Return `True` if `a` is a real expression.
2882
2883 >>> x = Int('x')
2884 >>> is_real(x + 1)
2885 False
2886 >>> y = Real('y')
2887 >>> is_real(y)
2888 True
2889 >>> is_real(y + 1)
2890 True
2891 >>> is_real(1)
2892 False
2893 >>> is_real(RealVal(1))
2894 True
2895 """
2896 return is_arith(a) and a.is_real()
2897
2898
2899def _is_numeral(ctx, a):
2900 return Z3_is_numeral_ast(ctx.ref(), a)
2901
2902
2903def _is_algebraic(ctx, a):
2904 return Z3_is_algebraic_number(ctx.ref(), a)
2905
2906
2908 """Return `True` if `a` is an integer value of sort Int.
2909
2910 >>> is_int_value(IntVal(1))
2911 True
2912 >>> is_int_value(1)
2913 False
2914 >>> is_int_value(Int('x'))
2915 False
2916 >>> n = Int('x') + 1
2917 >>> n
2918 x + 1
2919 >>> n.arg(1)
2920 1
2921 >>> is_int_value(n.arg(1))
2922 True
2923 >>> is_int_value(RealVal("1/3"))
2924 False
2925 >>> is_int_value(RealVal(1))
2926 False
2927 """
2928 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2929
2930
2932 """Return `True` if `a` is rational value of sort Real.
2933
2934 >>> is_rational_value(RealVal(1))
2935 True
2936 >>> is_rational_value(RealVal("3/5"))
2937 True
2938 >>> is_rational_value(IntVal(1))
2939 False
2940 >>> is_rational_value(1)
2941 False
2942 >>> n = Real('x') + 1
2943 >>> n.arg(1)
2944 1
2945 >>> is_rational_value(n.arg(1))
2946 True
2947 >>> is_rational_value(Real('x'))
2948 False
2949 """
2950 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2951
2952
2954 """Return `True` if `a` is an algebraic value of sort Real.
2955
2956 >>> is_algebraic_value(RealVal("3/5"))
2957 False
2958 >>> n = simplify(Sqrt(2))
2959 >>> n
2960 1.4142135623?
2961 >>> is_algebraic_value(n)
2962 True
2963 """
2964 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2965
2966
2967def is_add(a : Any) -> bool:
2968 """Return `True` if `a` is an expression of the form b + c.
2969
2970 >>> x, y = Ints('x y')
2971 >>> is_add(x + y)
2972 True
2973 >>> is_add(x - y)
2974 False
2975 """
2976 return is_app_of(a, Z3_OP_ADD)
2977
2978
2979def is_mul(a : Any) -> bool:
2980 """Return `True` if `a` is an expression of the form b * c.
2981
2982 >>> x, y = Ints('x y')
2983 >>> is_mul(x * y)
2984 True
2985 >>> is_mul(x - y)
2986 False
2987 """
2988 return is_app_of(a, Z3_OP_MUL)
2989
2990
2991def is_sub(a : Any) -> bool:
2992 """Return `True` if `a` is an expression of the form b - c.
2993
2994 >>> x, y = Ints('x y')
2995 >>> is_sub(x - y)
2996 True
2997 >>> is_sub(x + y)
2998 False
2999 """
3000 return is_app_of(a, Z3_OP_SUB)
3001
3002
3003def is_div(a : Any) -> bool:
3004 """Return `True` if `a` is an expression of the form b / c.
3005
3006 >>> x, y = Reals('x y')
3007 >>> is_div(x / y)
3008 True
3009 >>> is_div(x + y)
3010 False
3011 >>> x, y = Ints('x y')
3012 >>> is_div(x / y)
3013 False
3014 >>> is_idiv(x / y)
3015 True
3016 """
3017 return is_app_of(a, Z3_OP_DIV)
3018
3019
3020def is_idiv(a : Any) -> bool:
3021 """Return `True` if `a` is an expression of the form b div c.
3022
3023 >>> x, y = Ints('x y')
3024 >>> is_idiv(x / y)
3025 True
3026 >>> is_idiv(x + y)
3027 False
3028 """
3029 return is_app_of(a, Z3_OP_IDIV)
3030
3031
3032def is_mod(a : Any) -> bool:
3033 """Return `True` if `a` is an expression of the form b % c.
3034
3035 >>> x, y = Ints('x y')
3036 >>> is_mod(x % y)
3037 True
3038 >>> is_mod(x + y)
3039 False
3040 """
3041 return is_app_of(a, Z3_OP_MOD)
3042
3043
3044def is_le(a : Any) -> bool:
3045 """Return `True` if `a` is an expression of the form b <= c.
3046
3047 >>> x, y = Ints('x y')
3048 >>> is_le(x <= y)
3049 True
3050 >>> is_le(x < y)
3051 False
3052 """
3053 return is_app_of(a, Z3_OP_LE)
3054
3055
3056def is_lt(a : Any) -> bool:
3057 """Return `True` if `a` is an expression of the form b < c.
3058
3059 >>> x, y = Ints('x y')
3060 >>> is_lt(x < y)
3061 True
3062 >>> is_lt(x == y)
3063 False
3064 """
3065 return is_app_of(a, Z3_OP_LT)
3066
3067
3068def is_ge(a : Any) -> bool:
3069 """Return `True` if `a` is an expression of the form b >= c.
3070
3071 >>> x, y = Ints('x y')
3072 >>> is_ge(x >= y)
3073 True
3074 >>> is_ge(x == y)
3075 False
3076 """
3077 return is_app_of(a, Z3_OP_GE)
3078
3079
3080def is_gt(a : Any) -> bool:
3081 """Return `True` if `a` is an expression of the form b > c.
3082
3083 >>> x, y = Ints('x y')
3084 >>> is_gt(x > y)
3085 True
3086 >>> is_gt(x == y)
3087 False
3088 """
3089 return is_app_of(a, Z3_OP_GT)
3090
3091
3092def is_is_int(a : Any) -> bool:
3093 """Return `True` if `a` is an expression of the form IsInt(b).
3094
3095 >>> x = Real('x')
3096 >>> is_is_int(IsInt(x))
3097 True
3098 >>> is_is_int(x)
3099 False
3100 """
3101 return is_app_of(a, Z3_OP_IS_INT)
3102
3103
3104def is_to_real(a : Any) -> bool:
3105 """Return `True` if `a` is an expression of the form ToReal(b).
3106
3107 >>> x = Int('x')
3108 >>> n = ToReal(x)
3109 >>> n
3110 ToReal(x)
3111 >>> is_to_real(n)
3112 True
3113 >>> is_to_real(x)
3114 False
3115 """
3116 return is_app_of(a, Z3_OP_TO_REAL)
3117
3118
3119def is_to_int(a : Any) -> bool:
3120 """Return `True` if `a` is an expression of the form ToInt(b).
3121
3122 >>> x = Real('x')
3123 >>> n = ToInt(x)
3124 >>> n
3125 ToInt(x)
3126 >>> is_to_int(n)
3127 True
3128 >>> is_to_int(x)
3129 False
3130 """
3131 return is_app_of(a, Z3_OP_TO_INT)
3132
3133
3135 """Integer values."""
3136
3137 def as_long(self):
3138 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3139
3140 >>> v = IntVal(1)
3141 >>> v + 1
3142 1 + 1
3143 >>> v.as_long() + 1
3144 2
3145 """
3146 if z3_debug():
3147 _z3_assert(self.is_int(), "Integer value expected")
3148 return int(self.as_string())
3149
3150 def as_string(self):
3151 """Return a Z3 integer numeral as a Python string.
3152 >>> v = IntVal(100)
3153 >>> v.as_string()
3154 '100'
3155 """
3156 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3157
3159 """Return a Z3 integer numeral as a Python binary string.
3160 >>> v = IntVal(10)
3161 >>> v.as_binary_string()
3162 '1010'
3163 """
3165
3166 def py_value(self):
3167 return self.as_long()
3168
3169
3171 """Rational values."""
3172
3173 def numerator(self):
3174 """ Return the numerator of a Z3 rational numeral.
3175
3176 >>> is_rational_value(RealVal("3/5"))
3177 True
3178 >>> n = RealVal("3/5")
3179 >>> n.numerator()
3180 3
3181 >>> is_rational_value(Q(3,5))
3182 True
3183 >>> Q(3,5).numerator()
3184 3
3185 """
3187
3188 def denominator(self):
3189 """ Return the denominator of a Z3 rational numeral.
3190
3191 >>> is_rational_value(Q(3,5))
3192 True
3193 >>> n = Q(3,5)
3194 >>> n.denominator()
3195 5
3196 """
3197 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctxctx)
3198
3200 """ Return the numerator as a Python long.
3201
3202 >>> v = RealVal(10000000000)
3203 >>> v
3204 10000000000
3205 >>> v + 1
3206 10000000000 + 1
3207 >>> v.numerator_as_long() + 1 == 10000000001
3208 True
3209 """
3210 return self.numerator().as_long()
3211
3213 """ Return the denominator as a Python long.
3214
3215 >>> v = RealVal("1/3")
3216 >>> v
3217 1/3
3218 >>> v.denominator_as_long()
3219 3
3220 """
3221 return self.denominator().as_long()
3222
3223 def is_int(self):
3224 return False
3225
3226 def is_real(self):
3227 return True
3228
3229 def is_int_value(self):
3230 return self.denominator().is_int() and self.denominator_as_long() == 1
3231
3232 def as_long(self):
3233 _z3_assert(self.is_int_value(), "Expected integer fraction")
3234 return self.numerator_as_long()
3235
3236 def as_decimal(self, prec):
3237 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3238
3239 >>> v = RealVal("1/5")
3240 >>> v.as_decimal(3)
3241 '0.2'
3242 >>> v = RealVal("1/3")
3243 >>> v.as_decimal(3)
3244 '0.333?'
3245 """
3246 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3247
3248 def as_string(self):
3249 """Return a Z3 rational numeral as a Python string.
3250
3251 >>> v = Q(3,6)
3252 >>> v.as_string()
3253 '1/2'
3254 """
3255 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3256
3257 def as_fraction(self):
3258 """Return a Z3 rational as a Python Fraction object.
3259
3260 >>> v = RealVal("1/5")
3261 >>> v.as_fraction()
3262 Fraction(1, 5)
3263 """
3264 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3265
3266 def py_value(self):
3267 return Z3_get_numeral_double(self.ctx_ref(), self.as_astas_ast())
3268
3269
3271 """Algebraic irrational values."""
3272
3273 def approx(self, precision=10):
3274 """Return a Z3 rational number that approximates the algebraic number `self`.
3275 The result `r` is such that |r - self| <= 1/10^precision
3276
3277 >>> x = simplify(Sqrt(2))
3278 >>> x.approx(20)
3279 6838717160008073720548335/4835703278458516698824704
3280 >>> x.approx(5)
3281 2965821/2097152
3282 """
3284
3285 def as_decimal(self, prec):
3286 """Return a string representation of the algebraic number `self` in decimal notation
3287 using `prec` decimal places.
3288
3289 >>> x = simplify(Sqrt(2))
3290 >>> x.as_decimal(10)
3291 '1.4142135623?'
3292 >>> x.as_decimal(20)
3293 '1.41421356237309504880?'
3294 """
3295 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3296
3297 def poly(self):
3299
3300 def index(self):
3301 return Z3_algebraic_get_i(self.ctx_ref(), self.as_astas_ast())
3302
3303
3305 """The Complex sort, represented by pairs of Reals."""
3306
3307 def subsort(self, other):
3308 return False
3309
3310 def cast(self, val):
3311 if is_expr(val):
3312 _z3_assert(self.ctxctxctxctx == val.ctx, "Context mismatch")
3313 if self.eq(val.sort()):
3314 return val
3315 return ComplexVal(val, ctx=self.ctxctxctxctx)
3316
3317
3319 """A Complex expression supporting arithmetic, equality, and projections.
3320
3321 Complex numbers do not support ordering or exponentiation.
3322 """
3323
3324 def sort(self):
3326
3327 def real_part(self):
3328 return RealPart(self)
3329
3330 def imag_part(self):
3331 return ImagPart(self)
3332
3333
3335 """Return whether `s` is a Complex sort."""
3336 return isinstance(s, ComplexSortRef)
3337
3338
3340 """Return whether `a` is a Complex expression."""
3341 return isinstance(a, ComplexRef)
3342
3343
3344def ComplexSort(ctx=None):
3345 """Return the Complex sort in the given context."""
3346 ctx = _get_ctx(ctx)
3347 return ComplexSortRef(Z3_mk_complex_sort(ctx.ref()), ctx)
3348
3349
3350def Complex(name, ctx=None):
3351 """Create a named Complex constant."""
3352 ctx = _get_ctx(ctx)
3353 return ComplexRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), ComplexSort(ctx).ast), ctx)
3354
3355
3356def Complexes(names, ctx=None):
3357 """Create Complex constants from a space-separated string or list of names."""
3358 if isinstance(names, str):
3359 names = names.split(" ")
3360 return [Complex(name, ctx) for name in names]
3361
3362
3363def ComplexVal(real, imag=0, ctx=None):
3364 """Construct a Complex value or expression from Int or Real components.
3365
3366 A Python complex value may be passed as the sole component argument.
3367
3368 >>> z = ComplexVal("1/2", 2)
3369 >>> simplify(RealPart(z))
3370 1/2
3371 >>> simplify(ImagPart(z))
3372 2
3373 """
3374 if isinstance(real, complex):
3375 _z3_assert(imag == 0, "A Python complex value cannot have an additional imaginary component")
3376 real, imag = real.real, real.imag
3377 ctx = _get_ctx(ctx if ctx is not None else _ctx_from_ast_arg_list([real, imag]))
3378 sort = RealSort(ctx)
3379 real, imag = sort.cast(real), sort.cast(imag)
3380 return ComplexRef(Z3_mk_complex(ctx.ref(), real.as_ast(), imag.as_ast()), ctx)
3381
3382
3383def RealPart(value):
3384 """Return the Real-valued real component of a Complex expression."""
3385 _z3_assert(is_complex(value), "Complex expression expected")
3386 return _to_expr_ref(Z3_mk_real_part(value.ctx_ref(), value.as_ast()), value.ctx)
3387
3388
3389def ImagPart(value):
3390 """Return the Real-valued imaginary component of a Complex expression."""
3391 _z3_assert(is_complex(value), "Complex expression expected")
3392 return _to_expr_ref(Z3_mk_imag_part(value.ctx_ref(), value.as_ast()), value.ctx)
3393
3394
3395def _py2expr(a, ctx=None):
3396 if isinstance(a, bool):
3397 return BoolVal(a, ctx)
3398 if _is_int(a):
3399 return IntVal(a, ctx)
3400 if isinstance(a, float):
3401 return RealVal(a, ctx)
3402 if isinstance(a, complex):
3403 return ComplexVal(a, ctx=ctx)
3404 if isinstance(a, str):
3405 return StringVal(a, ctx)
3406 if is_expr(a):
3407 return a
3408 if z3_debug():
3409 _z3_assert(False, "Python bool, int, long or float expected")
3410
3411
3412def IntSort(ctx=None):
3413 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3414
3415 >>> IntSort()
3416 Int
3417 >>> x = Const('x', IntSort())
3418 >>> is_int(x)
3419 True
3420 >>> x.sort() == IntSort()
3421 True
3422 >>> x.sort() == BoolSort()
3423 False
3424 """
3425 ctx = _get_ctx(ctx)
3426 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3427
3428
3429def RealSort(ctx=None):
3430 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3431
3432 >>> RealSort()
3433 Real
3434 >>> x = Const('x', RealSort())
3435 >>> is_real(x)
3436 True
3437 >>> is_int(x)
3438 False
3439 >>> x.sort() == RealSort()
3440 True
3441 """
3442 ctx = _get_ctx(ctx)
3443 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3444
3445
3447 if isinstance(val, float):
3448 return str(int(val))
3449 elif isinstance(val, bool):
3450 if val:
3451 return "1"
3452 else:
3453 return "0"
3454 else:
3455 return str(val)
3456
3457
3458def IntVal(val, ctx=None):
3459 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3460
3461 >>> IntVal(1)
3462 1
3463 >>> IntVal("100")
3464 100
3465 """
3466 ctx = _get_ctx(ctx)
3467 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3468
3469
3470def RealVal(val, ctx=None):
3471 """Return a Z3 real value.
3472
3473 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3474 If `ctx=None`, then the global context is used.
3475
3476 >>> RealVal(1)
3477 1
3478 >>> RealVal(1).sort()
3479 Real
3480 >>> RealVal("3/5")
3481 3/5
3482 >>> RealVal("1.5")
3483 3/2
3484 """
3485 ctx = _get_ctx(ctx)
3486 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3487
3488
3489def RatVal(a, b, ctx=None):
3490 """Return a Z3 rational a/b.
3491
3492 If `ctx=None`, then the global context is used.
3493
3494 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3495 Z3 can reason about such expressions symbolically.
3496
3497 >>> RatVal(3,5)
3498 3/5
3499 >>> RatVal(3,5).sort()
3500 Real
3501 """
3502 if z3_debug():
3503 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3504 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3505 # Division by 0 is intentionally allowed - Z3 handles it symbolically
3506 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3507
3508
3509def Q(a, b, ctx=None):
3510 """Return a Z3 rational a/b.
3511
3512 If `ctx=None`, then the global context is used.
3513
3514 >>> Q(3,5)
3515 3/5
3516 >>> Q(3,5).sort()
3517 Real
3518 """
3519 return simplify(RatVal(a, b, ctx=ctx))
3520
3521
3522def Int(name, ctx=None):
3523 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3524
3525 >>> x = Int('x')
3526 >>> is_int(x)
3527 True
3528 >>> is_int(x + 1)
3529 True
3530 """
3531 ctx = _get_ctx(ctx)
3532 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3533
3534
3535def Ints(names, ctx=None):
3536 """Return a tuple of Integer constants.
3537
3538 >>> x, y, z = Ints('x y z')
3539 >>> Sum(x, y, z)
3540 x + y + z
3541 """
3542 ctx = _get_ctx(ctx)
3543 if isinstance(names, str):
3544 names = names.split(" ")
3545 return [Int(name, ctx) for name in names]
3546
3547
3548def IntVector(prefix, sz, ctx=None):
3549 """Return a list of integer constants of size `sz`.
3550
3551 >>> X = IntVector('x', 3)
3552 >>> X
3553 [x__0, x__1, x__2]
3554 >>> Sum(X)
3555 x__0 + x__1 + x__2
3556 """
3557 ctx = _get_ctx(ctx)
3558 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3559
3560
3561def FreshInt(prefix="x", ctx=None):
3562 """Return a fresh integer constant in the given context using the given prefix.
3563
3564 >>> x = FreshInt()
3565 >>> y = FreshInt()
3566 >>> eq(x, y)
3567 False
3568 >>> x.sort()
3569 Int
3570 """
3571 ctx = _get_ctx(ctx)
3572 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3573
3574
3575def Real(name, ctx=None):
3576 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3577
3578 >>> x = Real('x')
3579 >>> is_real(x)
3580 True
3581 >>> is_real(x + 1)
3582 True
3583 """
3584 ctx = _get_ctx(ctx)
3585 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3586
3587
3588def Reals(names, ctx=None):
3589 """Return a tuple of real constants.
3590
3591 >>> x, y, z = Reals('x y z')
3592 >>> Sum(x, y, z)
3593 x + y + z
3594 >>> Sum(x, y, z).sort()
3595 Real
3596 """
3597 ctx = _get_ctx(ctx)
3598 if isinstance(names, str):
3599 names = names.split(" ")
3600 return [Real(name, ctx) for name in names]
3601
3602
3603def RealVector(prefix, sz, ctx=None):
3604 """Return a list of real constants of size `sz`.
3605
3606 >>> X = RealVector('x', 3)
3607 >>> X
3608 [x__0, x__1, x__2]
3609 >>> Sum(X)
3610 x__0 + x__1 + x__2
3611 >>> Sum(X).sort()
3612 Real
3613 """
3614 ctx = _get_ctx(ctx)
3615 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3616
3617
3618def FreshReal(prefix="b", ctx=None):
3619 """Return a fresh real constant in the given context using the given prefix.
3620
3621 >>> x = FreshReal()
3622 >>> y = FreshReal()
3623 >>> eq(x, y)
3624 False
3625 >>> x.sort()
3626 Real
3627 """
3628 ctx = _get_ctx(ctx)
3629 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3630
3631
3632def ToReal(a):
3633 """ Return the Z3 expression ToReal(a).
3634
3635 >>> x = Int('x')
3636 >>> x.sort()
3637 Int
3638 >>> n = ToReal(x)
3639 >>> n
3640 ToReal(x)
3641 >>> n.sort()
3642 Real
3643 """
3644 ctx = a.ctx
3645 if isinstance(a, BoolRef):
3646 return If(a, RealVal(1, ctx), RealVal(0, ctx))
3647 if z3_debug():
3648 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3649 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3650
3651
3652def ToInt(a):
3653 """ Return the Z3 expression ToInt(a).
3654
3655 >>> x = Real('x')
3656 >>> x.sort()
3657 Real
3658 >>> n = ToInt(x)
3659 >>> n
3660 ToInt(x)
3661 >>> n.sort()
3662 Int
3663 """
3664 if z3_debug():
3665 _z3_assert(a.is_real(), "Z3 real expression expected.")
3666 ctx = a.ctx
3667 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3668
3669
3670def IsInt(a):
3671 """ Return the Z3 predicate IsInt(a).
3672
3673 >>> x = Real('x')
3674 >>> IsInt(x + "1/2")
3675 IsInt(x + 1/2)
3676 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3677 [x = 1/2]
3678 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3679 no solution
3680 """
3681 if z3_debug():
3682 _z3_assert(a.is_real(), "Z3 real expression expected.")
3683 ctx = a.ctx
3684 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3685
3686
3687def Sqrt(a, ctx=None):
3688 """ Return a Z3 expression which represents the square root of a.
3689
3690 >>> x = Real('x')
3691 >>> Sqrt(x)
3692 x**(1/2)
3693 """
3694 if not is_expr(a):
3695 ctx = _get_ctx(ctx)
3696 a = RealVal(a, ctx)
3697 return a ** "1/2"
3698
3699
3700def Cbrt(a, ctx=None):
3701 """ Return a Z3 expression which represents the cubic root of a.
3702
3703 >>> x = Real('x')
3704 >>> Cbrt(x)
3705 x**(1/3)
3706 """
3707 if not is_expr(a):
3708 ctx = _get_ctx(ctx)
3709 a = RealVal(a, ctx)
3710 return a ** "1/3"
3711
3712
3717
3718
3720 """Bit-vector sort."""
3721
3722 def size(self):
3723 """Return the size (number of bits) of the bit-vector sort `self`.
3724
3725 >>> b = BitVecSort(32)
3726 >>> b.size()
3727 32
3728 """
3729 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.astastast))
3730
3731 def subsort(self, other):
3732 return is_bv_sort(other) and self.size() < other.size()
3733
3734 def cast(self, val):
3735 """Try to cast `val` as a Bit-Vector.
3736
3737 >>> b = BitVecSort(32)
3738 >>> b.cast(10)
3739 10
3740 >>> b.cast(10).sexpr()
3741 '#x0000000a'
3742 """
3743 if is_expr(val):
3744 if z3_debug():
3745 _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
3746 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3747 return val
3748 else:
3749 return BitVecVal(val, self)
3750
3751
3753 """Return True if `s` is a Z3 bit-vector sort.
3754
3755 >>> is_bv_sort(BitVecSort(32))
3756 True
3757 >>> is_bv_sort(IntSort())
3758 False
3759 """
3760 return isinstance(s, BitVecSortRef)
3761
3762
3764 """Bit-vector expressions."""
3765
3766 def sort(self):
3767 """Return the sort of the bit-vector expression `self`.
3768
3769 >>> x = BitVec('x', 32)
3770 >>> x.sort()
3771 BitVec(32)
3772 >>> x.sort() == BitVecSort(32)
3773 True
3774 """
3776
3777 def size(self):
3778 """Return the number of bits of the bit-vector expression `self`.
3779
3780 >>> x = BitVec('x', 32)
3781 >>> (x + 1).size()
3782 32
3783 >>> Concat(x, x).size()
3784 64
3785 """
3786 return self.sortsort().size()
3787
3788 def __add__(self, other):
3789 """Create the Z3 expression `self + other`.
3790
3791 >>> x = BitVec('x', 32)
3792 >>> y = BitVec('y', 32)
3793 >>> x + y
3794 x + y
3795 >>> (x + y).sort()
3796 BitVec(32)
3797 """
3798 a, b = _coerce_exprs(self, other)
3799 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3800
3801 def __radd__(self, other):
3802 """Create the Z3 expression `other + self`.
3803
3804 >>> x = BitVec('x', 32)
3805 >>> 10 + x
3806 10 + x
3807 """
3808 a, b = _coerce_exprs(self, other)
3809 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3810
3811 def __mul__(self, other):
3812 """Create the Z3 expression `self * other`.
3813
3814 >>> x = BitVec('x', 32)
3815 >>> y = BitVec('y', 32)
3816 >>> x * y
3817 x*y
3818 >>> (x * y).sort()
3819 BitVec(32)
3820 """
3821 a, b = _coerce_exprs(self, other)
3822 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3823
3824 def __rmul__(self, other):
3825 """Create the Z3 expression `other * self`.
3826
3827 >>> x = BitVec('x', 32)
3828 >>> 10 * x
3829 10*x
3830 """
3831 a, b = _coerce_exprs(self, other)
3832 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3833
3834 def __sub__(self, other):
3835 """Create the Z3 expression `self - other`.
3836
3837 >>> x = BitVec('x', 32)
3838 >>> y = BitVec('y', 32)
3839 >>> x - y
3840 x - y
3841 >>> (x - y).sort()
3842 BitVec(32)
3843 """
3844 a, b = _coerce_exprs(self, other)
3845 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3846
3847 def __rsub__(self, other):
3848 """Create the Z3 expression `other - self`.
3849
3850 >>> x = BitVec('x', 32)
3851 >>> 10 - x
3852 10 - x
3853 """
3854 a, b = _coerce_exprs(self, other)
3855 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3856
3857 def __or__(self, other):
3858 """Create the Z3 expression bitwise-or `self | other`.
3859
3860 >>> x = BitVec('x', 32)
3861 >>> y = BitVec('y', 32)
3862 >>> x | y
3863 x | y
3864 >>> (x | y).sort()
3865 BitVec(32)
3866 """
3867 a, b = _coerce_exprs(self, other)
3868 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3869
3870 def __ror__(self, other):
3871 """Create the Z3 expression bitwise-or `other | self`.
3872
3873 >>> x = BitVec('x', 32)
3874 >>> 10 | x
3875 10 | x
3876 """
3877 a, b = _coerce_exprs(self, other)
3878 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3879
3880 def __and__(self, other):
3881 """Create the Z3 expression bitwise-and `self & other`.
3882
3883 >>> x = BitVec('x', 32)
3884 >>> y = BitVec('y', 32)
3885 >>> x & y
3886 x & y
3887 >>> (x & y).sort()
3888 BitVec(32)
3889 """
3890 a, b = _coerce_exprs(self, other)
3891 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3892
3893 def __rand__(self, other):
3894 """Create the Z3 expression bitwise-or `other & self`.
3895
3896 >>> x = BitVec('x', 32)
3897 >>> 10 & x
3898 10 & x
3899 """
3900 a, b = _coerce_exprs(self, other)
3901 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3902
3903 def __xor__(self, other):
3904 """Create the Z3 expression bitwise-xor `self ^ other`.
3905
3906 >>> x = BitVec('x', 32)
3907 >>> y = BitVec('y', 32)
3908 >>> x ^ y
3909 x ^ y
3910 >>> (x ^ y).sort()
3911 BitVec(32)
3912 """
3913 a, b = _coerce_exprs(self, other)
3914 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3915
3916 def __rxor__(self, other):
3917 """Create the Z3 expression bitwise-xor `other ^ self`.
3918
3919 >>> x = BitVec('x', 32)
3920 >>> 10 ^ x
3921 10 ^ x
3922 """
3923 a, b = _coerce_exprs(self, other)
3924 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3925
3926 def __pos__(self):
3927 """Return `self`.
3928
3929 >>> x = BitVec('x', 32)
3930 >>> +x
3931 x
3932 """
3933 return self
3934
3935 def __neg__(self):
3936 """Return an expression representing `-self`.
3937
3938 >>> x = BitVec('x', 32)
3939 >>> -x
3940 -x
3941 >>> simplify(-(-x))
3942 x
3943 """
3944 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
3945
3946 def __invert__(self):
3947 """Create the Z3 expression bitwise-not `~self`.
3948
3949 >>> x = BitVec('x', 32)
3950 >>> ~x
3951 ~x
3952 >>> simplify(~(~x))
3953 x
3954 """
3955 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
3956
3957 def __div__(self, other):
3958 """Create the Z3 expression (signed) division `self / other`.
3959
3960 Use the function UDiv() for unsigned division.
3961
3962 >>> x = BitVec('x', 32)
3963 >>> y = BitVec('y', 32)
3964 >>> x / y
3965 x/y
3966 >>> (x / y).sort()
3967 BitVec(32)
3968 >>> (x / y).sexpr()
3969 '(bvsdiv x y)'
3970 >>> UDiv(x, y).sexpr()
3971 '(bvudiv x y)'
3972 """
3973 a, b = _coerce_exprs(self, other)
3974 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3975
3976 def __truediv__(self, other):
3977 """Create the Z3 expression (signed) division `self / other`."""
3978 return self.__div__(other)
3979
3980 def __rdiv__(self, other):
3981 """Create the Z3 expression (signed) division `other / self`.
3982
3983 Use the function UDiv() for unsigned division.
3984
3985 >>> x = BitVec('x', 32)
3986 >>> 10 / x
3987 10/x
3988 >>> (10 / x).sexpr()
3989 '(bvsdiv #x0000000a x)'
3990 >>> UDiv(10, x).sexpr()
3991 '(bvudiv #x0000000a x)'
3992 """
3993 a, b = _coerce_exprs(self, other)
3994 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3995
3996 def __rtruediv__(self, other):
3997 """Create the Z3 expression (signed) division `other / self`."""
3998 return self.__rdiv__(other)
3999
4000 def __mod__(self, other):
4001 """Create the Z3 expression (signed) mod `self % other`.
4002
4003 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4004
4005 >>> x = BitVec('x', 32)
4006 >>> y = BitVec('y', 32)
4007 >>> x % y
4008 x%y
4009 >>> (x % y).sort()
4010 BitVec(32)
4011 >>> (x % y).sexpr()
4012 '(bvsmod x y)'
4013 >>> URem(x, y).sexpr()
4014 '(bvurem x y)'
4015 >>> SRem(x, y).sexpr()
4016 '(bvsrem x y)'
4017 """
4018 a, b = _coerce_exprs(self, other)
4019 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4020
4021 def __rmod__(self, other):
4022 """Create the Z3 expression (signed) mod `other % self`.
4023
4024 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4025
4026 >>> x = BitVec('x', 32)
4027 >>> 10 % x
4028 10%x
4029 >>> (10 % x).sexpr()
4030 '(bvsmod #x0000000a x)'
4031 >>> URem(10, x).sexpr()
4032 '(bvurem #x0000000a x)'
4033 >>> SRem(10, x).sexpr()
4034 '(bvsrem #x0000000a x)'
4035 """
4036 a, b = _coerce_exprs(self, other)
4037 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
4038
4039 def __le__(self, other):
4040 """Create the Z3 expression (signed) `other <= self`.
4041
4042 Use the function ULE() for unsigned less than or equal to.
4043
4044 >>> x, y = BitVecs('x y', 32)
4045 >>> x <= y
4046 x <= y
4047 >>> (x <= y).sexpr()
4048 '(bvsle x y)'
4049 >>> ULE(x, y).sexpr()
4050 '(bvule x y)'
4051 """
4052 a, b = _coerce_exprs(self, other)
4053 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4054
4055 def __lt__(self, other):
4056 """Create the Z3 expression (signed) `other < self`.
4057
4058 Use the function ULT() for unsigned less than.
4059
4060 >>> x, y = BitVecs('x y', 32)
4061 >>> x < y
4062 x < y
4063 >>> (x < y).sexpr()
4064 '(bvslt x y)'
4065 >>> ULT(x, y).sexpr()
4066 '(bvult x y)'
4067 """
4068 a, b = _coerce_exprs(self, other)
4069 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4070
4071 def __gt__(self, other):
4072 """Create the Z3 expression (signed) `other > self`.
4073
4074 Use the function UGT() for unsigned greater than.
4075
4076 >>> x, y = BitVecs('x y', 32)
4077 >>> x > y
4078 x > y
4079 >>> (x > y).sexpr()
4080 '(bvsgt x y)'
4081 >>> UGT(x, y).sexpr()
4082 '(bvugt x y)'
4083 """
4084 a, b = _coerce_exprs(self, other)
4085 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4086
4087 def __ge__(self, other):
4088 """Create the Z3 expression (signed) `other >= self`.
4089
4090 Use the function UGE() for unsigned greater than or equal to.
4091
4092 >>> x, y = BitVecs('x y', 32)
4093 >>> x >= y
4094 x >= y
4095 >>> (x >= y).sexpr()
4096 '(bvsge x y)'
4097 >>> UGE(x, y).sexpr()
4098 '(bvuge x y)'
4099 """
4100 a, b = _coerce_exprs(self, other)
4101 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4102
4103 def __rshift__(self, other):
4104 """Create the Z3 expression (arithmetical) right shift `self >> other`
4105
4106 Use the function LShR() for the right logical shift
4107
4108 >>> x, y = BitVecs('x y', 32)
4109 >>> x >> y
4110 x >> y
4111 >>> (x >> y).sexpr()
4112 '(bvashr x y)'
4113 >>> LShR(x, y).sexpr()
4114 '(bvlshr x y)'
4115 >>> BitVecVal(4, 3)
4116 4
4117 >>> BitVecVal(4, 3).as_signed_long()
4118 -4
4119 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4120 -2
4121 >>> simplify(BitVecVal(4, 3) >> 1)
4122 6
4123 >>> simplify(LShR(BitVecVal(4, 3), 1))
4124 2
4125 >>> simplify(BitVecVal(2, 3) >> 1)
4126 1
4127 >>> simplify(LShR(BitVecVal(2, 3), 1))
4128 1
4129 """
4130 a, b = _coerce_exprs(self, other)
4131 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4132
4133 def __lshift__(self, other):
4134 """Create the Z3 expression left shift `self << other`
4135
4136 >>> x, y = BitVecs('x y', 32)
4137 >>> x << y
4138 x << y
4139 >>> (x << y).sexpr()
4140 '(bvshl x y)'
4141 >>> simplify(BitVecVal(2, 3) << 1)
4142 4
4143 """
4144 a, b = _coerce_exprs(self, other)
4145 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4146
4147 def __rrshift__(self, other):
4148 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4149
4150 Use the function LShR() for the right logical shift
4151
4152 >>> x = BitVec('x', 32)
4153 >>> 10 >> x
4154 10 >> x
4155 >>> (10 >> x).sexpr()
4156 '(bvashr #x0000000a x)'
4157 """
4158 a, b = _coerce_exprs(self, other)
4159 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
4160
4161 def __rlshift__(self, other):
4162 """Create the Z3 expression left shift `other << self`.
4163
4164 Use the function LShR() for the right logical shift
4165
4166 >>> x = BitVec('x', 32)
4167 >>> 10 << x
4168 10 << x
4169 >>> (10 << x).sexpr()
4170 '(bvshl #x0000000a x)'
4171 """
4172 a, b = _coerce_exprs(self, other)
4173 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
4174
4175
4177 """Bit-vector values."""
4178
4179 def as_long(self):
4180 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4181
4182 >>> v = BitVecVal(0xbadc0de, 32)
4183 >>> v
4184 195936478
4185 >>> print("0x%.8x" % v.as_long())
4186 0x0badc0de
4187 """
4188 return int(self.as_string())
4189
4191 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4192 The most significant bit is assumed to be the sign.
4193
4194 >>> BitVecVal(4, 3).as_signed_long()
4195 -4
4196 >>> BitVecVal(7, 3).as_signed_long()
4197 -1
4198 >>> BitVecVal(3, 3).as_signed_long()
4199 3
4200 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4201 -1
4202 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4203 -1
4204 """
4205 sz = self.size()
4206 val = self.as_long()
4207 if val >= 2**(sz - 1):
4208 val = val - 2**sz
4209 if val < -2**(sz - 1):
4210 val = val + 2**sz
4211 return int(val)
4212
4213 def as_string(self):
4214 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
4215
4218
4219 def py_value(self):
4220 """Return the Python value of a Z3 bit-vector numeral."""
4221 return self.as_long()
4222
4223
4224
4225def is_bv(a):
4226 """Return `True` if `a` is a Z3 bit-vector expression.
4227
4228 >>> b = BitVec('b', 32)
4229 >>> is_bv(b)
4230 True
4231 >>> is_bv(b + 10)
4232 True
4233 >>> is_bv(Int('x'))
4234 False
4235 """
4236 return isinstance(a, BitVecRef)
4237
4238
4240 """Return `True` if `a` is a Z3 bit-vector numeral value.
4241
4242 >>> b = BitVec('b', 32)
4243 >>> is_bv_value(b)
4244 False
4245 >>> b = BitVecVal(10, 32)
4246 >>> b
4247 10
4248 >>> is_bv_value(b)
4249 True
4250 """
4251 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
4252
4253
4254def BV2Int(a, is_signed=False):
4255 """Return the Z3 expression BV2Int(a).
4256
4257 >>> b = BitVec('b', 3)
4258 >>> BV2Int(b).sort()
4259 Int
4260 >>> x = Int('x')
4261 >>> x > BV2Int(b)
4262 x > BV2Int(b)
4263 >>> x > BV2Int(b, is_signed=False)
4264 x > BV2Int(b)
4265 >>> x > BV2Int(b, is_signed=True)
4266 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4267 >>> solve(x > BV2Int(b), b == 1, x < 3)
4268 [x = 2, b = 1]
4269 """
4270 if z3_debug():
4271 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4272 ctx = a.ctx
4273 # investigate problem with bv2int
4274 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
4275
4276
4277def Int2BV(a, num_bits):
4278 """Return the z3 expression Int2BV(a, num_bits).
4279 It is a bit-vector of width num_bits and represents the
4280 modulo of a by 2^num_bits
4281 """
4282 ctx = a.ctx
4283 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
4284
4285
4286def BitVecSort(sz, ctx=None):
4287 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4288
4289 >>> Byte = BitVecSort(8)
4290 >>> Word = BitVecSort(16)
4291 >>> Byte
4292 BitVec(8)
4293 >>> x = Const('x', Byte)
4294 >>> eq(x, BitVec('x', 8))
4295 True
4296 """
4297 ctx = _get_ctx(ctx)
4298 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4299
4300
4301def BitVecVal(val, bv, ctx=None):
4302 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4303
4304 >>> v = BitVecVal(10, 32)
4305 >>> v
4306 10
4307 >>> print("0x%.8x" % v.as_long())
4308 0x0000000a
4309 """
4310 if is_bv_sort(bv):
4311 ctx = bv.ctx
4312 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4313 else:
4314 ctx = _get_ctx(ctx)
4315 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4316
4317
4318def BitVec(name, bv, ctx=None):
4319 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4320 If `ctx=None`, then the global context is used.
4321
4322 >>> x = BitVec('x', 16)
4323 >>> is_bv(x)
4324 True
4325 >>> x.size()
4326 16
4327 >>> x.sort()
4328 BitVec(16)
4329 >>> word = BitVecSort(16)
4330 >>> x2 = BitVec('x', word)
4331 >>> eq(x, x2)
4332 True
4333 """
4334 if isinstance(bv, BitVecSortRef):
4335 ctx = bv.ctx
4336 else:
4337 ctx = _get_ctx(ctx)
4338 bv = BitVecSort(bv, ctx)
4339 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4340
4341
4342def BitVecs(names, bv, ctx=None):
4343 """Return a tuple of bit-vector constants of size bv.
4344
4345 >>> x, y, z = BitVecs('x y z', 16)
4346 >>> x.size()
4347 16
4348 >>> x.sort()
4349 BitVec(16)
4350 >>> Sum(x, y, z)
4351 0 + x + y + z
4352 >>> Product(x, y, z)
4353 1*x*y*z
4354 >>> simplify(Product(x, y, z))
4355 x*y*z
4356 """
4357 ctx = _get_ctx(ctx)
4358 if isinstance(names, str):
4359 names = names.split(" ")
4360 return [BitVec(name, bv, ctx) for name in names]
4361
4362
4363def Concat(*args):
4364 """Create a Z3 bit-vector concatenation expression.
4365
4366 >>> v = BitVecVal(1, 4)
4367 >>> Concat(v, v+1, v)
4368 Concat(Concat(1, 1 + 1), 1)
4369 >>> simplify(Concat(v, v+1, v))
4370 289
4371 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4372 121
4373 """
4374 args = _get_args(args)
4375 sz = len(args)
4376 if z3_debug():
4377 _z3_assert(sz >= 2, "At least two arguments expected.")
4378
4379 ctx = None
4380 for a in args:
4381 if is_expr(a):
4382 ctx = a.ctx
4383 break
4384 if is_seq(args[0]) or isinstance(args[0], str):
4385 args = [_coerce_seq(s, ctx) for s in args]
4386 if z3_debug():
4387 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4388 v = (Ast * sz)()
4389 for i in range(sz):
4390 v[i] = args[i].as_ast()
4391 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4392
4393 if is_re(args[0]):
4394 if z3_debug():
4395 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4396 v = (Ast * sz)()
4397 for i in range(sz):
4398 v[i] = args[i].as_ast()
4399 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4400
4401 if z3_debug():
4402 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4403 r = args[0]
4404 for i in range(sz - 1):
4405 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4406 return r
4407
4408
4409def Extract(high, low, a):
4410 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4411
4412 Extract is overloaded to work with both bit-vectors and sequences:
4413
4414 **Bit-vector extraction**: Extract(high, low, bitvector)
4415 Extracts bits from position `high` down to position `low` (both inclusive).
4416 - high: int - the highest bit position to extract (0-indexed from right)
4417 - low: int - the lowest bit position to extract (0-indexed from right)
4418 - bitvector: BitVecRef - the bit-vector to extract from
4419 Returns a new bit-vector containing bits [high:low]
4420
4421 **Sequence extraction**: Extract(sequence, offset, length)
4422 Extracts a subsequence starting at the given offset with the specified length.
4423 The functions SubString and SubSeq are redirected to this form of Extract.
4424 - sequence: SeqRef or str - the sequence to extract from
4425 - offset: int - the starting position (0-indexed)
4426 - length: int - the number of elements to extract
4427 Returns a new sequence containing the extracted subsequence
4428
4429 >>> # Bit-vector extraction examples
4430 >>> x = BitVec('x', 8)
4431 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4432 Extract(6, 2, x)
4433 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4434 BitVec(5)
4435 >>> Extract(7, 0, x) # Extract all 8 bits
4436 Extract(7, 0, x)
4437 >>> Extract(3, 3, x) # Extract single bit at position 3
4438 Extract(3, 3, x)
4439
4440 >>> # Sequence extraction examples
4441 >>> s = StringVal("hello")
4442 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4443 str.substr("hello", 1, 3)
4444 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4445 "c"
4446 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4447 "ab"
4448 """
4449 if isinstance(high, str):
4450 high = StringVal(high)
4451 if is_seq(high):
4452 s = high
4453 offset, length = _coerce_exprs(low, a, s.ctx)
4454 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4455 if z3_debug():
4456 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4457 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4458 "First and second arguments must be non negative integers")
4459 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4460 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4461
4462
4464 if z3_debug():
4465 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4466
4467
4468def ULE(a, b):
4469 """Create the Z3 expression (unsigned) `other <= self`.
4470
4471 Use the operator <= for signed less than or equal to.
4472
4473 >>> x, y = BitVecs('x y', 32)
4474 >>> ULE(x, y)
4475 ULE(x, y)
4476 >>> (x <= y).sexpr()
4477 '(bvsle x y)'
4478 >>> ULE(x, y).sexpr()
4479 '(bvule x y)'
4480 """
4481 _check_bv_args(a, b)
4482 a, b = _coerce_exprs(a, b)
4483 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4484
4485
4486def ULT(a, b):
4487 """Create the Z3 expression (unsigned) `other < self`.
4488
4489 Use the operator < for signed less than.
4490
4491 >>> x, y = BitVecs('x y', 32)
4492 >>> ULT(x, y)
4493 ULT(x, y)
4494 >>> (x < y).sexpr()
4495 '(bvslt x y)'
4496 >>> ULT(x, y).sexpr()
4497 '(bvult x y)'
4498 """
4499 _check_bv_args(a, b)
4500 a, b = _coerce_exprs(a, b)
4501 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4502
4503
4504def UGE(a, b):
4505 """Create the Z3 expression (unsigned) `other >= self`.
4506
4507 Use the operator >= for signed greater than or equal to.
4508
4509 >>> x, y = BitVecs('x y', 32)
4510 >>> UGE(x, y)
4511 UGE(x, y)
4512 >>> (x >= y).sexpr()
4513 '(bvsge x y)'
4514 >>> UGE(x, y).sexpr()
4515 '(bvuge x y)'
4516 """
4517 _check_bv_args(a, b)
4518 a, b = _coerce_exprs(a, b)
4519 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4520
4521
4522def UGT(a, b):
4523 """Create the Z3 expression (unsigned) `other > self`.
4524
4525 Use the operator > for signed greater than.
4526
4527 >>> x, y = BitVecs('x y', 32)
4528 >>> UGT(x, y)
4529 UGT(x, y)
4530 >>> (x > y).sexpr()
4531 '(bvsgt x y)'
4532 >>> UGT(x, y).sexpr()
4533 '(bvugt x y)'
4534 """
4535 _check_bv_args(a, b)
4536 a, b = _coerce_exprs(a, b)
4537 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4538
4539
4540def UDiv(a, b):
4541 """Create the Z3 expression (unsigned) division `self / other`.
4542
4543 Use the operator / for signed division.
4544
4545 >>> x = BitVec('x', 32)
4546 >>> y = BitVec('y', 32)
4547 >>> UDiv(x, y)
4548 UDiv(x, y)
4549 >>> UDiv(x, y).sort()
4550 BitVec(32)
4551 >>> (x / y).sexpr()
4552 '(bvsdiv x y)'
4553 >>> UDiv(x, y).sexpr()
4554 '(bvudiv x y)'
4555 """
4556 _check_bv_args(a, b)
4557 a, b = _coerce_exprs(a, b)
4558 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4559
4560
4561def URem(a, b):
4562 """Create the Z3 expression (unsigned) remainder `self % other`.
4563
4564 Use the operator % for signed modulus, and SRem() for signed remainder.
4565
4566 >>> x = BitVec('x', 32)
4567 >>> y = BitVec('y', 32)
4568 >>> URem(x, y)
4569 URem(x, y)
4570 >>> URem(x, y).sort()
4571 BitVec(32)
4572 >>> (x % y).sexpr()
4573 '(bvsmod x y)'
4574 >>> URem(x, y).sexpr()
4575 '(bvurem x y)'
4576 """
4577 _check_bv_args(a, b)
4578 a, b = _coerce_exprs(a, b)
4579 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4580
4581
4582def SRem(a, b):
4583 """Create the Z3 expression signed remainder.
4584
4585 Use the operator % for signed modulus, and URem() for unsigned remainder.
4586
4587 >>> x = BitVec('x', 32)
4588 >>> y = BitVec('y', 32)
4589 >>> SRem(x, y)
4590 SRem(x, y)
4591 >>> SRem(x, y).sort()
4592 BitVec(32)
4593 >>> (x % y).sexpr()
4594 '(bvsmod x y)'
4595 >>> SRem(x, y).sexpr()
4596 '(bvsrem x y)'
4597 """
4598 _check_bv_args(a, b)
4599 a, b = _coerce_exprs(a, b)
4600 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4601
4602
4603def LShR(a, b):
4604 """Create the Z3 expression logical right shift.
4605
4606 Use the operator >> for the arithmetical right shift.
4607
4608 >>> x, y = BitVecs('x y', 32)
4609 >>> LShR(x, y)
4610 LShR(x, y)
4611 >>> (x >> y).sexpr()
4612 '(bvashr x y)'
4613 >>> LShR(x, y).sexpr()
4614 '(bvlshr x y)'
4615 >>> BitVecVal(4, 3)
4616 4
4617 >>> BitVecVal(4, 3).as_signed_long()
4618 -4
4619 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4620 -2
4621 >>> simplify(BitVecVal(4, 3) >> 1)
4622 6
4623 >>> simplify(LShR(BitVecVal(4, 3), 1))
4624 2
4625 >>> simplify(BitVecVal(2, 3) >> 1)
4626 1
4627 >>> simplify(LShR(BitVecVal(2, 3), 1))
4628 1
4629 """
4630 _check_bv_args(a, b)
4631 a, b = _coerce_exprs(a, b)
4632 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4633
4634
4635def RotateLeft(a, b):
4636 """Return an expression representing `a` rotated to the left `b` times.
4637
4638 >>> a, b = BitVecs('a b', 16)
4639 >>> RotateLeft(a, b)
4640 RotateLeft(a, b)
4641 >>> simplify(RotateLeft(a, 0))
4642 a
4643 >>> simplify(RotateLeft(a, 16))
4644 a
4645 """
4646 _check_bv_args(a, b)
4647 a, b = _coerce_exprs(a, b)
4648 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4649
4650
4651def RotateRight(a, b):
4652 """Return an expression representing `a` rotated to the right `b` times.
4653
4654 >>> a, b = BitVecs('a b', 16)
4655 >>> RotateRight(a, b)
4656 RotateRight(a, b)
4657 >>> simplify(RotateRight(a, 0))
4658 a
4659 >>> simplify(RotateRight(a, 16))
4660 a
4661 """
4662 _check_bv_args(a, b)
4663 a, b = _coerce_exprs(a, b)
4664 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4665
4666
4667def SignExt(n, a):
4668 """Return a bit-vector expression with `n` extra sign-bits.
4669
4670 >>> x = BitVec('x', 16)
4671 >>> n = SignExt(8, x)
4672 >>> n.size()
4673 24
4674 >>> n
4675 SignExt(8, x)
4676 >>> n.sort()
4677 BitVec(24)
4678 >>> v0 = BitVecVal(2, 2)
4679 >>> v0
4680 2
4681 >>> v0.size()
4682 2
4683 >>> v = simplify(SignExt(6, v0))
4684 >>> v
4685 254
4686 >>> v.size()
4687 8
4688 >>> print("%.x" % v.as_long())
4689 fe
4690 """
4691 if z3_debug():
4692 _z3_assert(_is_int(n), "First argument must be an integer")
4693 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4694 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4695
4696
4697def ZeroExt(n, a):
4698 """Return a bit-vector expression with `n` extra zero-bits.
4699
4700 >>> x = BitVec('x', 16)
4701 >>> n = ZeroExt(8, x)
4702 >>> n.size()
4703 24
4704 >>> n
4705 ZeroExt(8, x)
4706 >>> n.sort()
4707 BitVec(24)
4708 >>> v0 = BitVecVal(2, 2)
4709 >>> v0
4710 2
4711 >>> v0.size()
4712 2
4713 >>> v = simplify(ZeroExt(6, v0))
4714 >>> v
4715 2
4716 >>> v.size()
4717 8
4718 """
4719 if z3_debug():
4720 _z3_assert(_is_int(n), "First argument must be an integer")
4721 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4722 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4723
4724
4726 """Return an expression representing `n` copies of `a`.
4727
4728 >>> x = BitVec('x', 8)
4729 >>> n = RepeatBitVec(4, x)
4730 >>> n
4731 RepeatBitVec(4, x)
4732 >>> n.size()
4733 32
4734 >>> v0 = BitVecVal(10, 4)
4735 >>> print("%.x" % v0.as_long())
4736 a
4737 >>> v = simplify(RepeatBitVec(4, v0))
4738 >>> v.size()
4739 16
4740 >>> print("%.x" % v.as_long())
4741 aaaa
4742 """
4743 if z3_debug():
4744 _z3_assert(_is_int(n), "First argument must be an integer")
4745 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4746 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4747
4748
4750 """Return the reduction-and expression of `a`."""
4751 if z3_debug():
4752 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4753 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4754
4755
4756def BVRedOr(a):
4757 """Return the reduction-or expression of `a`."""
4758 if z3_debug():
4759 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4760 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4761
4762
4763def BvNand(a, b):
4764 """Return the bitwise NAND of `a` and `b`.
4765
4766 >>> x = BitVec('x', 8)
4767 >>> y = BitVec('y', 8)
4768 >>> BvNand(x, y)
4769 bvnand(x, y)
4770 """
4771 _check_bv_args(a, b)
4772 a, b = _coerce_exprs(a, b)
4773 return BitVecRef(Z3_mk_bvnand(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4774
4775
4776def BvNor(a, b):
4777 """Return the bitwise NOR of `a` and `b`.
4778
4779 >>> x = BitVec('x', 8)
4780 >>> y = BitVec('y', 8)
4781 >>> BvNor(x, y)
4782 bvnor(x, y)
4783 """
4784 _check_bv_args(a, b)
4785 a, b = _coerce_exprs(a, b)
4786 return BitVecRef(Z3_mk_bvnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4787
4788
4789def BvXnor(a, b):
4790 """Return the bitwise XNOR of `a` and `b`.
4791
4792 >>> x = BitVec('x', 8)
4793 >>> y = BitVec('y', 8)
4794 >>> BvXnor(x, y)
4795 bvxnor(x, y)
4796 """
4797 _check_bv_args(a, b)
4798 a, b = _coerce_exprs(a, b)
4799 return BitVecRef(Z3_mk_bvxnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4800
4801
4802def BVAddNoOverflow(a, b, signed):
4803 """A predicate the determines that bit-vector addition does not overflow"""
4804 _check_bv_args(a, b)
4805 a, b = _coerce_exprs(a, b)
4806 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4807
4808
4810 """A predicate the determines that signed bit-vector addition does not underflow"""
4811 _check_bv_args(a, b)
4812 a, b = _coerce_exprs(a, b)
4813 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4814
4815
4817 """A predicate the determines that bit-vector subtraction does not overflow"""
4818 _check_bv_args(a, b)
4819 a, b = _coerce_exprs(a, b)
4820 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4821
4822
4823def BVSubNoUnderflow(a, b, signed):
4824 """A predicate the determines that bit-vector subtraction does not underflow"""
4825 _check_bv_args(a, b)
4826 a, b = _coerce_exprs(a, b)
4827 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4828
4829
4831 """A predicate the determines that bit-vector signed division does not overflow"""
4832 _check_bv_args(a, b)
4833 a, b = _coerce_exprs(a, b)
4834 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4835
4836
4838 """A predicate the determines that bit-vector unary negation does not overflow"""
4839 if z3_debug():
4840 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4841 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4842
4843
4844def BVMulNoOverflow(a, b, signed):
4845 """A predicate the determines that bit-vector multiplication does not overflow"""
4846 _check_bv_args(a, b)
4847 a, b = _coerce_exprs(a, b)
4848 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4849
4850
4852 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4853 _check_bv_args(a, b)
4854 a, b = _coerce_exprs(a, b)
4855 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4856
4857
4858
4863
4865 """Array sorts."""
4866
4867 def domain(self):
4868 """Return the domain of the array sort `self`.
4869
4870 >>> A = ArraySort(IntSort(), BoolSort())
4871 >>> A.domain()
4872 Int
4873 """
4875
4876 def domain_n(self, i):
4877 """Return the domain of the array sort `self`.
4878 """
4880
4881 def range(self):
4882 """Return the range of the array sort `self`.
4883
4884 >>> A = ArraySort(IntSort(), BoolSort())
4885 >>> A.range()
4886 Bool
4887 """
4889
4890
4892 """Array expressions. """
4893
4894 def sort(self):
4895 """Return the array sort of the array expression `self`.
4896
4897 >>> a = Array('a', IntSort(), BoolSort())
4898 >>> a.sort()
4899 Array(Int, Bool)
4900 """
4902
4903 def domain(self):
4904 """Shorthand for `self.sort().domain()`.
4905
4906 >>> a = Array('a', IntSort(), BoolSort())
4907 >>> a.domain()
4908 Int
4909 """
4910 return self.sortsort().domain()
4911
4912 def domain_n(self, i):
4913 """Shorthand for self.sort().domain_n(i)`."""
4914 return self.sortsort().domain_n(i)
4915
4916 def range(self):
4917 """Shorthand for `self.sort().range()`.
4918
4919 >>> a = Array('a', IntSort(), BoolSort())
4920 >>> a.range()
4921 Bool
4922 """
4923 return self.sortsort().range()
4924
4925 def __getitem__(self, arg):
4926 """Return the Z3 expression `self[arg]`.
4927
4928 >>> a = Array('a', IntSort(), BoolSort())
4929 >>> i = Int('i')
4930 >>> a[i]
4931 a[i]
4932 >>> a[i].sexpr()
4933 '(select a i)'
4934 """
4935 return _array_select(self, arg)
4936
4937 def default(self):
4938 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
4939
4940
4941def _array_select(ar, arg):
4942 if isinstance(arg, tuple):
4943 args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))]
4944 _args, sz = _to_ast_array(args)
4945 return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4946 arg = ar.sort().domain().cast(arg)
4947 return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4948
4949
4951 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4952
4953
4954def is_array(a : Any) -> bool:
4955 """Return `True` if `a` is a Z3 array expression.
4956
4957 >>> a = Array('a', IntSort(), IntSort())
4958 >>> is_array(a)
4959 True
4960 >>> is_array(Store(a, 0, 1))
4961 True
4962 >>> is_array(a[0])
4963 False
4964 """
4965 return isinstance(a, ArrayRef)
4966
4967
4969 """Return `True` if `a` is a Z3 constant array.
4970
4971 >>> a = K(IntSort(), 10)
4972 >>> is_const_array(a)
4973 True
4974 >>> a = Array('a', IntSort(), IntSort())
4975 >>> is_const_array(a)
4976 False
4977 """
4978 return is_app_of(a, Z3_OP_CONST_ARRAY)
4979
4980
4981def is_K(a):
4982 """Return `True` if `a` is a Z3 constant array.
4983
4984 >>> a = K(IntSort(), 10)
4985 >>> is_K(a)
4986 True
4987 >>> a = Array('a', IntSort(), IntSort())
4988 >>> is_K(a)
4989 False
4990 """
4991 return is_app_of(a, Z3_OP_CONST_ARRAY)
4992
4993
4994def is_map(a):
4995 """Return `True` if `a` is a Z3 map array expression.
4996
4997 >>> f = Function('f', IntSort(), IntSort())
4998 >>> b = Array('b', IntSort(), IntSort())
4999 >>> a = Map(f, b)
5000 >>> a
5001 Map(f, b)
5002 >>> is_map(a)
5003 True
5004 >>> is_map(b)
5005 False
5006 """
5007 return is_app_of(a, Z3_OP_ARRAY_MAP)
5008
5009
5011 """Return `True` if `a` is a Z3 default array expression.
5012 >>> d = Default(K(IntSort(), 10))
5013 >>> is_default(d)
5014 True
5015 """
5016 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
5017
5018
5020 """Return the function declaration associated with a Z3 map array expression.
5021
5022 >>> f = Function('f', IntSort(), IntSort())
5023 >>> b = Array('b', IntSort(), IntSort())
5024 >>> a = Map(f, b)
5025 >>> eq(f, get_map_func(a))
5026 True
5027 >>> get_map_func(a)
5028 f
5029 >>> get_map_func(a)(0)
5030 f(0)
5031 """
5032 if z3_debug():
5033 _z3_assert(is_map(a), "Z3 array map expression expected.")
5034 return FuncDeclRef(
5036 a.ctx_ref(),
5037 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
5038 ),
5039 ctx=a.ctx,
5040 )
5041
5042
5043def ArraySort(*sig):
5044 """Return the Z3 array sort with the given domain and range sorts.
5045
5046 >>> A = ArraySort(IntSort(), BoolSort())
5047 >>> A
5048 Array(Int, Bool)
5049 >>> A.domain()
5050 Int
5051 >>> A.range()
5052 Bool
5053 >>> AA = ArraySort(IntSort(), A)
5054 >>> AA
5055 Array(Int, Array(Int, Bool))
5056 >>> ArraySort(IntSort(), BoolSort(), RealSort())
5057 Array(Int, Bool, Real)
5058 """
5059 sig = _get_args(sig)
5060 if z3_debug():
5061 _z3_assert(len(sig) > 1, "At least two arguments expected")
5062 arity = len(sig) - 1
5063 r = sig[arity]
5064 d = sig[0]
5065 if z3_debug():
5066 for s in sig:
5067 _z3_assert(is_sort(s), "Z3 sort expected")
5068 _z3_assert(s.ctx == r.ctx, "Context mismatch")
5069 ctx = d.ctx
5070 if len(sig) == 2:
5071 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
5072 dom = (Sort * arity)()
5073 for i in range(arity):
5074 dom[i] = sig[i].ast
5075 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
5076
5077
5078def Array(name, *sorts):
5079 """Return an array constant named `name` with the given domain and range sorts.
5080
5081 >>> a = Array('a', IntSort(), IntSort())
5082 >>> a.sort()
5083 Array(Int, Int)
5084 >>> a[0]
5085 a[0]
5086 """
5087 s = ArraySort(sorts)
5088 ctx = s.ctx
5089 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
5090
5091
5092def Update(a, *args):
5093 """Return a Z3 store array expression.
5094
5095 >>> a = Array('a', IntSort(), IntSort())
5096 >>> i, v = Ints('i v')
5097 >>> s = Update(a, i, v)
5098 >>> s.sort()
5099 Array(Int, Int)
5100 >>> prove(s[i] == v)
5101 proved
5102 >>> j = Int('j')
5103 >>> prove(Implies(i != j, s[j] == a[j]))
5104 proved
5105 """
5106 if z3_debug():
5107 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5108 args = _get_args(args)
5109 ctx = a.ctx
5110 if len(args) <= 1:
5111 raise Z3Exception("array update requires index and value arguments")
5112 if len(args) == 2:
5113 i = args[0]
5114 v = args[1]
5115 i = a.sort().domain().cast(i)
5116 v = a.sort().range().cast(v)
5117 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
5118 v = a.sort().range().cast(args[-1])
5119 idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
5120 _args, sz = _to_ast_array(idxs)
5121 return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
5122
5123
5124def Default(a):
5125 """ Return a default value for array expression.
5126 >>> b = K(IntSort(), 1)
5127 >>> prove(Default(b) == 1)
5128 proved
5129 """
5130 if z3_debug():
5131 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5132 return a.default()
5133
5134
5135def Store(a, *args):
5136 """Return a Z3 store array expression.
5137
5138 >>> a = Array('a', IntSort(), IntSort())
5139 >>> i, v = Ints('i v')
5140 >>> s = Store(a, i, v)
5141 >>> s.sort()
5142 Array(Int, Int)
5143 >>> prove(s[i] == v)
5144 proved
5145 >>> j = Int('j')
5146 >>> prove(Implies(i != j, s[j] == a[j]))
5147 proved
5148 """
5149 return Update(a, args)
5150
5151
5152def Select(a, *args):
5153 """Return a Z3 select array expression.
5154
5155 >>> a = Array('a', IntSort(), IntSort())
5156 >>> i = Int('i')
5157 >>> Select(a, i)
5158 a[i]
5159 >>> eq(Select(a, i), a[i])
5160 True
5161 """
5162 args = _get_args(args)
5163 if z3_debug():
5164 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5165 return a[args]
5166
5167
5168def Map(f, *args):
5169 """Return a Z3 map array expression.
5170
5171 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5172 >>> a1 = Array('a1', IntSort(), IntSort())
5173 >>> a2 = Array('a2', IntSort(), IntSort())
5174 >>> b = Map(f, a1, a2)
5175 >>> b
5176 Map(f, a1, a2)
5177 >>> prove(b[0] == f(a1[0], a2[0]))
5178 proved
5179 """
5180 args = _get_args(args)
5181 if z3_debug():
5182 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
5183 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
5184 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
5185 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
5186 _args, sz = _to_ast_array(args)
5187 ctx = f.ctx
5188 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
5189
5190
5191def K(dom, v):
5192 """Return a Z3 constant array expression.
5193
5194 >>> a = K(IntSort(), 10)
5195 >>> a
5196 K(Int, 10)
5197 >>> a.sort()
5198 Array(Int, Int)
5199 >>> i = Int('i')
5200 >>> a[i]
5201 K(Int, 10)[i]
5202 >>> simplify(a[i])
5203 10
5204 """
5205 if z3_debug():
5206 _z3_assert(is_sort(dom), "Z3 sort expected")
5207 ctx = dom.ctx
5208 if not is_expr(v):
5209 v = _py2expr(v, ctx)
5210 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
5211
5212
5213def Ext(a, b):
5214 """Return extensionality index for one-dimensional arrays.
5215 >> a, b = Consts('a b', SetSort(IntSort()))
5216 >> Ext(a, b)
5217 Ext(a, b)
5218 """
5219 ctx = a.ctx
5220 if z3_debug():
5221 _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
5222 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5223
5224
5225def AsArray(f):
5226 """Return a Z3 as-array expression for the given function declaration.
5227
5228 >>> f = Function('f', IntSort(), IntSort())
5229 >>> a = AsArray(f)
5230 >>> a.sort()
5231 Array(Int, Int)
5232 >>> is_as_array(a)
5233 True
5234 >>> get_as_array_func(a) == f
5235 True
5236 """
5237 if z3_debug():
5238 _z3_assert(isinstance(f, FuncDeclRef), "function declaration expected")
5239 ctx = f.ctx
5240 return ArrayRef(Z3_mk_as_array(ctx.ref(), f.ast), ctx)
5241
5242
5244 """Return `True` if `a` is a Z3 array select application.
5245
5246 >>> a = Array('a', IntSort(), IntSort())
5247 >>> is_select(a)
5248 False
5249 >>> i = Int('i')
5250 >>> is_select(a[i])
5251 True
5252 """
5253 return is_app_of(a, Z3_OP_SELECT)
5254
5255
5257 """Return `True` if `a` is a Z3 array store application.
5258
5259 >>> a = Array('a', IntSort(), IntSort())
5260 >>> is_store(a)
5261 False
5262 >>> is_store(Store(a, 0, 1))
5263 True
5264 """
5265 return is_app_of(a, Z3_OP_STORE)
5266
5267
5272
5273
5274def SetSort(s):
5275 """ Create a set sort over element sort s"""
5276 return ArraySort(s, BoolSort())
5277
5278
5280 """Create the empty set
5281 >>> EmptySet(IntSort())
5282 K(Int, False)
5283 """
5284 ctx = s.ctx
5285 if is_finite_set_sort(s):
5286 return FiniteSetEmpty(s)
5287 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
5288
5289
5290def FullSet(s):
5291 """Create the full set
5292 >>> FullSet(IntSort())
5293 K(Int, True)
5294 """
5295 ctx = s.ctx
5296 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
5297
5298
5299def SetUnion(*args):
5300 """ Take the union of sets
5301 >>> a = Const('a', SetSort(IntSort()))
5302 >>> b = Const('b', SetSort(IntSort()))
5303 >>> SetUnion(a, b)
5304 union(a, b)
5305 """
5306 args = _get_args(args)
5307 if len(args) > 0 and is_finite_set(args[0]):
5308 from functools import reduce
5309 return reduce(FiniteSetUnion, args)
5310 ctx = _ctx_from_ast_arg_list(args)
5311 _args, sz = _to_ast_array(args)
5312 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
5313
5314
5315def SetIntersect(*args):
5316 """ Take the union of sets
5317 >>> a = Const('a', SetSort(IntSort()))
5318 >>> b = Const('b', SetSort(IntSort()))
5319 >>> SetIntersect(a, b)
5320 intersection(a, b)
5321 """
5322 args = _get_args(args)
5323 ctx = _ctx_from_ast_arg_list(args)
5324 if len(args) > 0 and is_finite_set(args[0]):
5325 from functools import reduce
5326 return reduce(FiniteSetIntersect, args)
5327 _args, sz = _to_ast_array(args)
5328 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
5329
5330
5331def SetAdd(s, e):
5332 """ Add element e to set s
5333 >>> a = Const('a', SetSort(IntSort()))
5334 >>> SetAdd(a, 1)
5335 Store(a, 1, True)
5336 """
5337 ctx = _ctx_from_ast_arg_list([s, e])
5338 e = _py2expr(e, ctx)
5339 if is_finite_set(s):
5340 return FiniteSetSingleton(e) | s
5341 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5342
5343
5344def SetDel(s, e):
5345 """ Remove element e to set s
5346 >>> a = Const('a', SetSort(IntSort()))
5347 >>> SetDel(a, 1)
5348 Store(a, 1, False)
5349 """
5350 ctx = _ctx_from_ast_arg_list([s, e])
5351 e = _py2expr(e, ctx)
5352 if is_finite_set(s):
5353 return s - FiniteSetSingleton(e)
5354 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5355
5356
5358 """ The complement of set s
5359 >>> a = Const('a', SetSort(IntSort()))
5360 >>> SetComplement(a)
5361 complement(a)
5362 """
5363 ctx = s.ctx
5364 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
5365
5366
5368 """ The set difference of a and b
5369 >>> a = Const('a', SetSort(IntSort()))
5370 >>> b = Const('b', SetSort(IntSort()))
5371 >>> SetDifference(a, b)
5372 setminus(a, b)
5373 """
5374 ctx = _ctx_from_ast_arg_list([a, b])
5375 if is_finite_set(a):
5376 return FiniteSetDifference(a, b)
5377 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5378
5379
5380def IsMember(e, s):
5381 """ Check if e is a member of set s
5382 >>> a = Const('a', SetSort(IntSort()))
5383 >>> IsMember(1, a)
5384 a[1]
5385 """
5386 ctx = _ctx_from_ast_arg_list([s, e])
5387 e = _py2expr(e, ctx)
5388 if is_finite_set(s):
5389 return FiniteSetIsMember(e, s)
5390 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5391
5392
5393def IsSubset(a, b):
5394 """ Check if a is a subset of b
5395 >>> a = Const('a', SetSort(IntSort()))
5396 >>> b = Const('b', SetSort(IntSort()))
5397 >>> IsSubset(a, b)
5398 subset(a, b)
5399 """
5400 ctx = _ctx_from_ast_arg_list([a, b])
5401 if is_finite_set(a):
5402 return FiniteSetIsSubset(a, b)
5403 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5404
5405
5406
5411
5412
5414 """Finite set sort."""
5415
5416 def element_sort(self):
5417 """Return the element sort of this finite set sort."""
5419
5420 def cast(self, val):
5421 """Try to cast val as a finite set expression."""
5422 if is_expr(val):
5423 if self.eq(val.sort()):
5424 return val
5425 else:
5426 _z3_assert(False, "Cannot cast to finite set sort")
5427 if isinstance(val, set):
5428 elem_sort = self.element_sort()
5429 result = FiniteSetEmpty(self)
5430 for e in val:
5431 result = FiniteSetUnion(result, Singleton(_py2expr(e, self.ctxctxctx, elem_sort)))
5432 return result
5433 _z3_assert(False, "Cannot cast to finite set sort")
5434
5435 def subsort(self, other):
5436 return False
5437
5438 def is_int(self):
5439 return False
5440
5441 def is_bool(self):
5442 return False
5443
5444 def is_datatype(self):
5445 return False
5446
5447 def is_array(self):
5448 return False
5449
5450 def is_bv(self):
5451 return False
5452
5453
5455 """Return True if a is a Z3 finite set expression.
5456 >>> s = FiniteSetSort(IntSort())
5457 >>> is_finite_set(FiniteSetEmpty(s))
5458 True
5459 >>> is_finite_set(IntVal(1))
5460 False
5461 """
5462 return isinstance(a, FiniteSetRef)
5463
5464
5466 """Return True if s is a Z3 finite set sort.
5467 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5468 True
5469 >>> is_finite_set_sort(IntSort())
5470 False
5471 """
5472 return isinstance(s, FiniteSetSortRef)
5473
5474
5476 """Finite set expression."""
5477
5478 def sort(self):
5480
5481 def __or__(self, other):
5482 """Return the union of self and other."""
5483 return FiniteSetUnion(self, other)
5484
5485 def __and__(self, other):
5486 """Return the intersection of self and other."""
5487 return FiniteSetIntersect(self, other)
5488
5489 def __sub__(self, other):
5490 """Return the set difference of self and other."""
5491 return FiniteSetDifference(self, other)
5492
5493
5494def FiniteSetSort(elem_sort):
5495 """Create a finite set sort over element sort elem_sort.
5496 >>> s = FiniteSetSort(IntSort())
5497 >>> s
5498 FiniteSet(Int)
5499 """
5500 return FiniteSetSortRef(Z3_mk_finite_set_sort(elem_sort.ctx_ref(), elem_sort.ast), elem_sort.ctx)
5501
5502
5503def FiniteSetEmpty(set_sort):
5504 """Create an empty finite set of the given sort.
5505 >>> s = FiniteSetSort(IntSort())
5506 >>> FiniteSetEmpty(s)
5507 set.empty
5508 """
5509 ctx = set_sort.ctx
5510 return FiniteSetRef(Z3_mk_finite_set_empty(ctx.ref(), set_sort.ast), ctx)
5511
5512
5513def Singleton(elem):
5514 """Create a singleton finite set containing elem.
5515 >>> Singleton(IntVal(1))
5516 set.singleton(1)
5517 """
5518 ctx = elem.ctx
5519 return FiniteSetRef(Z3_mk_finite_set_singleton(ctx.ref(), elem.as_ast()), ctx)
5520
5521
5522def FiniteSetUnion(s1, s2):
5523 """Create the union of two finite sets.
5524 >>> a = Const('a', FiniteSetSort(IntSort()))
5525 >>> b = Const('b', FiniteSetSort(IntSort()))
5526 >>> FiniteSetUnion(a, b)
5527 set.union(a, b)
5528 """
5529 ctx = _ctx_from_ast_arg_list([s1, s2])
5530 return FiniteSetRef(Z3_mk_finite_set_union(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5531
5532
5534 """Create the intersection of two finite sets.
5535 >>> a = Const('a', FiniteSetSort(IntSort()))
5536 >>> b = Const('b', FiniteSetSort(IntSort()))
5537 >>> FiniteSetIntersect(a, b)
5538 set.intersect(a, b)
5539 """
5540 ctx = _ctx_from_ast_arg_list([s1, s2])
5541 return FiniteSetRef(Z3_mk_finite_set_intersect(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5542
5543
5545 """Create the set difference of two finite sets.
5546 >>> a = Const('a', FiniteSetSort(IntSort()))
5547 >>> b = Const('b', FiniteSetSort(IntSort()))
5548 >>> FiniteSetDifference(a, b)
5549 set.difference(a, b)
5550 """
5551 ctx = _ctx_from_ast_arg_list([s1, s2])
5552 return FiniteSetRef(Z3_mk_finite_set_difference(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5553
5554
5555def FiniteSetMember(elem, set):
5556 """Check if elem is a member of the finite set.
5557 >>> a = Const('a', FiniteSetSort(IntSort()))
5558 >>> FiniteSetMember(IntVal(1), a)
5559 set.in(1, a)
5560 """
5561 ctx = _ctx_from_ast_arg_list([elem, set])
5562 return BoolRef(Z3_mk_finite_set_member(ctx.ref(), elem.as_ast(), set.as_ast()), ctx)
5563
5564def In(elem, set):
5565 return FiniteSetMember(elem, set)
5566
5568 """Get the size (cardinality) of a finite set.
5569 >>> a = Const('a', FiniteSetSort(IntSort()))
5570 >>> FiniteSetSize(a)
5571 set.size(a)
5572 """
5573 ctx = set.ctx
5574 return ArithRef(Z3_mk_finite_set_size(ctx.ref(), set.as_ast()), ctx)
5575
5576
5578 """Check if s1 is a subset of s2.
5579 >>> a = Const('a', FiniteSetSort(IntSort()))
5580 >>> b = Const('b', FiniteSetSort(IntSort()))
5581 >>> FiniteSetSubset(a, b)
5582 set.subset(a, b)
5583 """
5584 ctx = _ctx_from_ast_arg_list([s1, s2])
5585 return BoolRef(Z3_mk_finite_set_subset(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5586
5587
5588def FiniteSetMap(f, set):
5589 """Apply function f to all elements of the finite set.
5590 >>> f = Array('f', IntSort(), IntSort())
5591 >>> a = Const('a', FiniteSetSort(IntSort()))
5592 >>> FiniteSetMap(f, a)
5593 set.map(f, a)
5594 """
5595 if isinstance(f, FuncDeclRef):
5596 f = AsArray(f)
5597 ctx = _ctx_from_ast_arg_list([f, set])
5598 return FiniteSetRef(Z3_mk_finite_set_map(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5599
5600
5602 """Filter a finite set using predicate f.
5603 >>> f = Array('f', IntSort(), BoolSort())
5604 >>> a = Const('a', FiniteSetSort(IntSort()))
5605 >>> FiniteSetFilter(f, a)
5606 set.filter(f, a)
5607 """
5608 if isinstance(f, FuncDeclRef):
5609 f = AsArray(f)
5610 ctx = _ctx_from_ast_arg_list([f, set])
5611 return FiniteSetRef(Z3_mk_finite_set_filter(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5612
5613
5614def FiniteSetRange(low, high):
5615 """Create a finite set of integers in the range [low, high).
5616 >>> FiniteSetRange(IntVal(0), IntVal(5))
5617 set.range(0, 5)
5618 """
5619 ctx = _ctx_from_ast_arg_list([low, high])
5620 return FiniteSetRef(Z3_mk_finite_set_range(ctx.ref(), low.as_ast(), high.as_ast()), ctx)
5621
5622
5623
5628
5630 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5631 if not isinstance(acc, tuple):
5632 return False
5633 if len(acc) != 2:
5634 return False
5635 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5636
5637
5639 """Helper class for declaring Z3 datatypes.
5640
5641 >>> List = Datatype('List')
5642 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5643 >>> List.declare('nil')
5644 >>> List = List.create()
5645 >>> # List is now a Z3 declaration
5646 >>> List.nil
5647 nil
5648 >>> List.cons(10, List.nil)
5649 cons(10, nil)
5650 >>> List.cons(10, List.nil).sort()
5651 List
5652 >>> cons = List.cons
5653 >>> nil = List.nil
5654 >>> car = List.car
5655 >>> cdr = List.cdr
5656 >>> n = cons(1, cons(0, nil))
5657 >>> n
5658 cons(1, cons(0, nil))
5659 >>> simplify(cdr(n))
5660 cons(0, nil)
5661 >>> simplify(car(n))
5662 1
5663 """
5664
5665 def __init__(self, name, ctx=None):
5666 self.ctx = _get_ctx(ctx)
5667 self.name = name
5669
5670 def __deepcopy__(self, memo={}):
5671 r = Datatype(self.name, self.ctx)
5672 r.constructors = copy.deepcopy(self.constructors)
5673 return r
5674
5675 def declare_core(self, name, rec_name, *args):
5676 if z3_debug():
5677 _z3_assert(isinstance(name, str), "String expected")
5678 _z3_assert(isinstance(rec_name, str), "String expected")
5679 _z3_assert(
5680 all([_valid_accessor(a) for a in args]),
5681 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5682 )
5683 self.constructors.append((name, rec_name, args))
5684
5685 def declare(self, name, *args):
5686 """Declare constructor named `name` with the given accessors `args`.
5687 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5688 or a reference to the datatypes being declared.
5689
5690 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5691 declares the constructor named `cons` that builds a new List using an integer and a List.
5692 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5693 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5694 we use the method create() to create the actual datatype in Z3.
5695
5696 >>> List = Datatype('List')
5697 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5698 >>> List.declare('nil')
5699 >>> List = List.create()
5700 """
5701 if z3_debug():
5702 _z3_assert(isinstance(name, str), "String expected")
5703 _z3_assert(name != "", "Constructor name cannot be empty")
5704 return self.declare_core(name, "is-" + name, *args)
5705
5706 def __repr__(self):
5707 return "Datatype(%s, %s)" % (self.name, self.constructors)
5708
5709 def create(self):
5710 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5711
5712 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5713
5714 >>> List = Datatype('List')
5715 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5716 >>> List.declare('nil')
5717 >>> List = List.create()
5718 >>> List.nil
5719 nil
5720 >>> List.cons(10, List.nil)
5721 cons(10, nil)
5722 """
5723 return CreateDatatypes([self])[0]
5724
5725 def create_polymorphic(self, type_params):
5726 """Create a polymorphic Z3 datatype with explicit type variables.
5727
5728 `type_params` is a list of type variables created with `DeclareTypeVar`.
5729 Constructor field sorts may reference these type variables.
5730 Self-recursive fields may reference this datatype directly.
5731
5732 >>> A = DeclareTypeVar('A')
5733 >>> Pair = Datatype('Pair')
5734 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5735 >>> Pair = Pair.create_polymorphic([A])
5736 """
5737 return CreatePolymorphicDatatype(self, type_params)
5738
5739
5741 """Auxiliary object used to create Z3 datatypes."""
5742
5743 def __init__(self, c, ctx):
5744 self.c = c
5745 self.ctx = ctx
5746
5747 def __del__(self):
5748 if self.ctx.ref() is not None and Z3_del_constructor is not None:
5749 Z3_del_constructor(self.ctx.ref(), self.c)
5750
5751
5753 """Auxiliary object used to create Z3 datatypes."""
5754
5755 def __init__(self, c, ctx):
5756 self.c = c
5757 self.ctx = ctx
5758
5759 def __del__(self):
5760 if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5761 Z3_del_constructor_list(self.ctx.ref(), self.c)
5762
5763
5765 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5766
5767 In the following example we define a Tree-List using two mutually recursive datatypes.
5768
5769 >>> TreeList = Datatype('TreeList')
5770 >>> Tree = Datatype('Tree')
5771 >>> # Tree has two constructors: leaf and node
5772 >>> Tree.declare('leaf', ('val', IntSort()))
5773 >>> # a node contains a list of trees
5774 >>> Tree.declare('node', ('children', TreeList))
5775 >>> TreeList.declare('nil')
5776 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5777 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5778 >>> Tree.val(Tree.leaf(10))
5779 val(leaf(10))
5780 >>> simplify(Tree.val(Tree.leaf(10)))
5781 10
5782 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5783 >>> n1
5784 node(cons(leaf(10), cons(leaf(20), nil)))
5785 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5786 >>> simplify(n2 == n1)
5787 False
5788 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5789 True
5790 """
5791 ds = _get_args(ds)
5792 if z3_debug():
5793 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5794 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5795 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5796 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5797 ctx = ds[0].ctx
5798 num = len(ds)
5799 names = (Symbol * num)()
5800 out = (Sort * num)()
5801 clists = (ConstructorList * num)()
5802 to_delete = []
5803 for i in range(num):
5804 d = ds[i]
5805 names[i] = to_symbol(d.name, ctx)
5806 num_cs = len(d.constructors)
5807 cs = (Constructor * num_cs)()
5808 for j in range(num_cs):
5809 c = d.constructors[j]
5810 cname = to_symbol(c[0], ctx)
5811 rname = to_symbol(c[1], ctx)
5812 fs = c[2]
5813 num_fs = len(fs)
5814 fnames = (Symbol * num_fs)()
5815 sorts = (Sort * num_fs)()
5816 refs = (ctypes.c_uint * num_fs)()
5817 for k in range(num_fs):
5818 fname = fs[k][0]
5819 ftype = fs[k][1]
5820 fnames[k] = to_symbol(fname, ctx)
5821 if isinstance(ftype, Datatype):
5822 if z3_debug():
5823 _z3_assert(
5824 ds.count(ftype) == 1,
5825 "One and only one occurrence of each datatype is expected",
5826 )
5827 sorts[k] = None
5828 refs[k] = ds.index(ftype)
5829 else:
5830 if z3_debug():
5831 _z3_assert(is_sort(ftype), "Z3 sort expected")
5832 sorts[k] = ftype.ast
5833 refs[k] = 0
5834 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5835 to_delete.append(ScopedConstructor(cs[j], ctx))
5836 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5837 to_delete.append(ScopedConstructorList(clists[i], ctx))
5838 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5839 result = []
5840 # Create a field for every constructor, recognizer and accessor
5841 for i in range(num):
5842 dref = DatatypeSortRef(out[i], ctx)
5843 num_cs = dref.num_constructors()
5844 for j in range(num_cs):
5845 cref = dref.constructor(j)
5846 cref_name = cref.name()
5847 cref_arity = cref.arity()
5848 if cref.arity() == 0:
5849 cref = cref()
5850 setattr(dref, cref_name, cref)
5851 rref = dref.recognizer(j)
5852 setattr(dref, "is_" + cref_name, rref)
5853 for k in range(cref_arity):
5854 aref = dref.accessor(j, k)
5855 setattr(dref, aref.name(), aref)
5856 result.append(dref)
5857 return tuple(result)
5858
5859
5860def CreatePolymorphicDatatype(d, type_params):
5861 """Create a single polymorphic Z3 datatype with explicit type parameters.
5862
5863 `d` is a `Datatype` helper object whose constructors have been declared.
5864 `type_params` is a list of type variables created with `DeclareTypeVar`.
5865 Constructor field sorts may reference these type variables, and self-recursive
5866 fields may reference `d` directly.
5867
5868 >>> A = DeclareTypeVar('A')
5869 >>> Pair = Datatype('Pair')
5870 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5871 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5872 """
5873 if z3_debug():
5874 _z3_assert(isinstance(d, Datatype), "Datatype expected")
5875 _z3_assert(d.constructors != [], "Non-empty Datatype expected")
5876 ctx = d.ctx
5877 name = to_symbol(d.name, ctx)
5878 num_params = len(type_params)
5879 params_arr = (Sort * num_params)()
5880 for i, p in enumerate(type_params):
5881 if z3_debug():
5882 _z3_assert(is_sort(p), "Z3 sort expected for type parameter")
5883 params_arr[i] = p.ast
5884 num_cs = len(d.constructors)
5885 cs = (Constructor * num_cs)()
5886 to_delete = []
5887 for j in range(num_cs):
5888 c = d.constructors[j]
5889 cname = to_symbol(c[0], ctx)
5890 rname = to_symbol(c[1], ctx)
5891 fs = c[2]
5892 num_fs = len(fs)
5893 fnames = (Symbol * num_fs)()
5894 sorts = (Sort * num_fs)()
5895 refs = (ctypes.c_uint * num_fs)()
5896 for k in range(num_fs):
5897 fname = fs[k][0]
5898 ftype = fs[k][1]
5899 fnames[k] = to_symbol(fname, ctx)
5900 if isinstance(ftype, Datatype):
5901 if z3_debug():
5902 _z3_assert(ftype is d, "Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5903 sorts[k] = None
5904 refs[k] = 0
5905 else:
5906 if z3_debug():
5907 _z3_assert(is_sort(ftype), "Z3 sort expected")
5908 sorts[k] = ftype.ast
5909 refs[k] = 0
5910 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5911 to_delete.append(ScopedConstructor(cs[j], ctx))
5912 out = Z3_mk_polymorphic_datatype(ctx.ref(), name, num_params, params_arr, num_cs, cs)
5913 dref = DatatypeSortRef(out, ctx)
5914 num_cs_actual = dref.num_constructors()
5915 for j in range(num_cs_actual):
5916 cref = dref.constructor(j)
5917 cref_name = cref.name()
5918 cref_arity = cref.arity()
5919 if cref_arity == 0:
5920 cref = cref()
5921 setattr(dref, cref_name, cref)
5922 rref = dref.recognizer(j)
5923 setattr(dref, "is_" + cref_name, rref)
5924 for k in range(cref_arity):
5925 aref = dref.accessor(j, k)
5926 setattr(dref, aref.name(), aref)
5927 return dref
5928
5929
5931 """Datatype sorts."""
5932
5934 """Return the number of constructors in the given Z3 datatype.
5935
5936 >>> List = Datatype('List')
5937 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5938 >>> List.declare('nil')
5939 >>> List = List.create()
5940 >>> # List is now a Z3 declaration
5941 >>> List.num_constructors()
5942 2
5943 """
5945
5946 def constructor(self, idx):
5947 """Return a constructor of the datatype `self`.
5948
5949 >>> List = Datatype('List')
5950 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5951 >>> List.declare('nil')
5952 >>> List = List.create()
5953 >>> # List is now a Z3 declaration
5954 >>> List.num_constructors()
5955 2
5956 >>> List.constructor(0)
5957 cons
5958 >>> List.constructor(1)
5959 nil
5960 """
5961 if z3_debug():
5962 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5964
5965 def recognizer(self, idx):
5966 """In Z3, each constructor has an associated recognizer predicate.
5967
5968 If the constructor is named `name`, then the recognizer `is_name`.
5969
5970 >>> List = Datatype('List')
5971 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5972 >>> List.declare('nil')
5973 >>> List = List.create()
5974 >>> # List is now a Z3 declaration
5975 >>> List.num_constructors()
5976 2
5977 >>> List.recognizer(0)
5978 is(cons)
5979 >>> List.recognizer(1)
5980 is(nil)
5981 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5982 False
5983 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5984 True
5985 >>> l = Const('l', List)
5986 >>> simplify(List.is_cons(l))
5987 is(cons, l)
5988 """
5989 if z3_debug():
5990 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5992
5993 def accessor(self, i, j):
5994 """In Z3, each constructor has 0 or more accessor.
5995 The number of accessors is equal to the arity of the constructor.
5996
5997 >>> List = Datatype('List')
5998 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5999 >>> List.declare('nil')
6000 >>> List = List.create()
6001 >>> List.num_constructors()
6002 2
6003 >>> List.constructor(0)
6004 cons
6005 >>> num_accs = List.constructor(0).arity()
6006 >>> num_accs
6007 2
6008 >>> List.accessor(0, 0)
6009 car
6010 >>> List.accessor(0, 1)
6011 cdr
6012 >>> List.constructor(1)
6013 nil
6014 >>> num_accs = List.constructor(1).arity()
6015 >>> num_accs
6016 0
6017 """
6018 if z3_debug():
6019 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
6020 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
6021 return FuncDeclRef(
6023 ctx=self.ctxctxctx,
6024 )
6025
6026
6028 """Datatype expressions."""
6029
6030 def sort(self):
6031 """Return the datatype sort of the datatype expression `self`."""
6033
6034 def update_field(self, field_accessor, new_value):
6035 """Return a new datatype expression with the specified field updated.
6036
6037 Args:
6038 field_accessor: The accessor function declaration for the field to update
6039 new_value: The new value for the field
6040
6041 Returns:
6042 A new datatype expression with the field updated, other fields unchanged
6043
6044 Example:
6045 >>> Person = Datatype('Person')
6046 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
6047 >>> Person = Person.create()
6048 >>> person_age = Person.accessor(0, 1) # age accessor
6049 >>> p = Const('p', Person)
6050 >>> p2 = p.update_field(person_age, IntVal(30))
6051 """
6052 if z3_debug():
6053 _z3_assert(is_func_decl(field_accessor), "Z3 function declaration expected")
6054 _z3_assert(is_expr(new_value), "Z3 expression expected")
6055 return _to_expr_ref(
6056 Z3_datatype_update_field(self.ctx_ref(), field_accessor.ast, self.as_astas_ast(), new_value.as_ast()),
6057 self.ctxctxctx
6058 )
6059
6060def DatatypeSort(name, params=None, ctx=None):
6061 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
6062
6063 Args:
6064 name: name of the datatype sort
6065 params: optional list/tuple of sort parameters for parametric datatypes
6066 ctx: Z3 context (optional)
6067
6068 Example:
6069 >>> # Non-parametric datatype
6070 >>> TreeRef = DatatypeSort('Tree')
6071 >>> # Parametric datatype with one parameter
6072 >>> ListIntRef = DatatypeSort('List', [IntSort()])
6073 >>> # Parametric datatype with multiple parameters
6074 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
6075 """
6076 ctx = _get_ctx(ctx)
6077 if params is None or len(params) == 0:
6078 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), 0, (Sort * 0)()), ctx)
6079 else:
6080 _params = (Sort * len(params))()
6081 for i in range(len(params)):
6082 _params[i] = params[i].ast
6083 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), len(params), _params), ctx)
6084
6085def TupleSort(name, sorts, ctx=None):
6086 """Create a named tuple sort base on a set of underlying sorts
6087 Example:
6088 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
6089 """
6090 tuple = Datatype(name, ctx)
6091 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
6092 tuple.declare(name, *projects)
6093 tuple = tuple.create()
6094 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
6095
6096
6097def DisjointSum(name, sorts, ctx=None):
6098 """Create a named tagged union sort base on a set of underlying sorts
6099 Example:
6100 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
6101 """
6102 sum = Datatype(name, ctx)
6103 for i in range(len(sorts)):
6104 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
6105 sum = sum.create()
6106 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
6107
6108
6109def EnumSort(name, values, ctx=None):
6110 """Return a new enumeration sort named `name` containing the given values.
6111
6112 The result is a pair (sort, list of constants).
6113 Example:
6114 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6115 """
6116 if z3_debug():
6117 _z3_assert(isinstance(name, str), "Name must be a string")
6118 _z3_assert(all([isinstance(v, str) for v in values]), "Enumeration sort values must be strings")
6119 _z3_assert(len(values) > 0, "At least one value expected")
6120 ctx = _get_ctx(ctx)
6121 num = len(values)
6122 _val_names = (Symbol * num)()
6123 for i in range(num):
6124 _val_names[i] = to_symbol(values[i], ctx)
6125 _values = (FuncDecl * num)()
6126 _testers = (FuncDecl * num)()
6127 name = to_symbol(name, ctx)
6128 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
6129 V = []
6130 for i in range(num):
6131 V.append(FuncDeclRef(_values[i], ctx))
6132 V = [a() for a in V]
6133 return S, V
6134
6135
6140
6141
6143 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6144
6145 Consider using the function `args2params` to create instances of this object.
6146 """
6147
6148 def __init__(self, ctx=None, params=None):
6149 self.ctx = _get_ctx(ctx)
6150 if params is None:
6151 self.params = Z3_mk_params(self.ctx.ref())
6152 else:
6153 self.params = params
6154 Z3_params_inc_ref(self.ctx.ref(), self.params)
6155
6156 def __deepcopy__(self, memo={}):
6157 return ParamsRef(self.ctx, self.params)
6158
6159 def __del__(self):
6160 if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
6161 Z3_params_dec_ref(self.ctx.ref(), self.params)
6162
6163 def set(self, name, val):
6164 """Set parameter name with value val."""
6165 if z3_debug():
6166 _z3_assert(isinstance(name, str), "parameter name must be a string")
6167 name_sym = to_symbol(name, self.ctx)
6168 if isinstance(val, bool):
6169 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
6170 elif _is_int(val):
6171 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
6172 elif isinstance(val, float):
6173 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
6174 elif isinstance(val, str):
6175 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
6176 else:
6177 if z3_debug():
6178 _z3_assert(False, "invalid parameter value")
6179
6180 def __repr__(self):
6181 return Z3_params_to_string(self.ctx.ref(), self.params)
6182
6183 def validate(self, ds):
6184 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
6185 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
6186
6187
6188def args2params(arguments, keywords, ctx=None):
6189 """Convert python arguments into a Z3_params object.
6190 A ':' is added to the keywords, and '_' is replaced with '-'
6191
6192 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6193 (params model true relevancy 2 elim_and true)
6194 """
6195 if z3_debug():
6196 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
6197 prev = None
6198 r = ParamsRef(ctx)
6199 for a in arguments:
6200 if prev is None:
6201 prev = a
6202 else:
6203 r.set(prev, a)
6204 prev = None
6205 for k in keywords:
6206 v = keywords[k]
6207 r.set(k, v)
6208 return r
6209
6210
6212 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6213 """
6214
6215 def __init__(self, descr, ctx=None):
6216 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
6217 self.ctx = _get_ctx(ctx)
6218 self.descr = descr
6219 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
6220
6221 def __deepcopy__(self, memo={}):
6222 return ParamsDescrsRef(self.descr, self.ctx)
6223
6224 def __del__(self):
6225 if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
6226 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
6227
6228 def size(self):
6229 """Return the size of in the parameter description `self`.
6230 """
6231 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
6232
6233 def __len__(self):
6234 """Return the size of in the parameter description `self`.
6235 """
6236 return self.size()
6237
6238 def get_name(self, i):
6239 """Return the i-th parameter name in the parameter description `self`.
6240 """
6241 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
6242
6243 def get_kind(self, n):
6244 """Return the kind of the parameter named `n`.
6245 """
6246 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6247
6248 def get_documentation(self, n):
6249 """Return the documentation string of the parameter named `n`.
6250 """
6251 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6252
6253 def __getitem__(self, arg):
6254 if _is_int(arg):
6255 return self.get_name(arg)
6256 else:
6257 return self.get_kind(arg)
6258
6259 def __repr__(self):
6260 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
6261
6262
6267
6268
6270 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6271
6272 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6273 A goal has a solution if one of its subgoals has a solution.
6274 A goal is unsatisfiable if all subgoals are unsatisfiable.
6275 """
6276
6277 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6278 if z3_debug():
6279 _z3_assert(goal is None or ctx is not None,
6280 "If goal is different from None, then ctx must be also different from None")
6281 self.ctx = _get_ctx(ctx)
6282 self.goal = goal
6283 if self.goal is None:
6284 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
6285 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
6286
6287 def __del__(self):
6288 if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
6289 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
6290
6291 def depth(self):
6292 """Return the depth of the goal `self`.
6293 The depth corresponds to the number of tactics applied to `self`.
6294
6295 >>> x, y = Ints('x y')
6296 >>> g = Goal()
6297 >>> g.add(x == 0, y >= x + 1)
6298 >>> g.depth()
6299 0
6300 >>> r = Then('simplify', 'solve-eqs')(g)
6301 >>> # r has 1 subgoal
6302 >>> len(r)
6303 1
6304 >>> r[0].depth()
6305 2
6306 """
6307 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
6308
6309 def inconsistent(self):
6310 """Return `True` if `self` contains the `False` constraints.
6311
6312 >>> x, y = Ints('x y')
6313 >>> g = Goal()
6314 >>> g.inconsistent()
6315 False
6316 >>> g.add(x == 0, x == 1)
6317 >>> g
6318 [x == 0, x == 1]
6319 >>> g.inconsistent()
6320 False
6321 >>> g2 = Tactic('propagate-values')(g)[0]
6322 >>> g2.inconsistent()
6323 True
6324 """
6325 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
6326
6327 def prec(self):
6328 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6329
6330 >>> g = Goal()
6331 >>> g.prec() == Z3_GOAL_PRECISE
6332 True
6333 >>> x, y = Ints('x y')
6334 >>> g.add(x == y + 1)
6335 >>> g.prec() == Z3_GOAL_PRECISE
6336 True
6337 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6338 >>> g2 = t(g)[0]
6339 >>> g2
6340 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6341 >>> g2.prec() == Z3_GOAL_PRECISE
6342 False
6343 >>> g2.prec() == Z3_GOAL_UNDER
6344 True
6345 """
6346 return Z3_goal_precision(self.ctx.ref(), self.goal)
6347
6348 def precision(self):
6349 """Alias for `prec()`.
6350
6351 >>> g = Goal()
6352 >>> g.precision() == Z3_GOAL_PRECISE
6353 True
6354 """
6355 return self.prec()
6356
6357 def size(self):
6358 """Return the number of constraints in the goal `self`.
6359
6360 >>> g = Goal()
6361 >>> g.size()
6362 0
6363 >>> x, y = Ints('x y')
6364 >>> g.add(x == 0, y > x)
6365 >>> g.size()
6366 2
6367 """
6368 return int(Z3_goal_size(self.ctx.ref(), self.goal))
6369
6370 def __len__(self):
6371 """Return the number of constraints in the goal `self`.
6372
6373 >>> g = Goal()
6374 >>> len(g)
6375 0
6376 >>> x, y = Ints('x y')
6377 >>> g.add(x == 0, y > x)
6378 >>> len(g)
6379 2
6380 """
6381 return self.size()
6382
6383 def get(self, i):
6384 """Return a constraint in the goal `self`.
6385
6386 >>> g = Goal()
6387 >>> x, y = Ints('x y')
6388 >>> g.add(x == 0, y > x)
6389 >>> g.get(0)
6390 x == 0
6391 >>> g.get(1)
6392 y > x
6393 """
6394 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
6395
6396 def __getitem__(self, arg):
6397 """Return a constraint in the goal `self`.
6398
6399 >>> g = Goal()
6400 >>> x, y = Ints('x y')
6401 >>> g.add(x == 0, y > x)
6402 >>> g[0]
6403 x == 0
6404 >>> g[1]
6405 y > x
6406 """
6407 if arg < 0:
6408 arg += len(self)
6409 if arg < 0 or arg >= len(self):
6410 raise IndexError
6411 return self.get(arg)
6412
6413 def assert_exprs(self, *args):
6414 """Assert constraints into the goal.
6415
6416 >>> x = Int('x')
6417 >>> g = Goal()
6418 >>> g.assert_exprs(x > 0, x < 2)
6419 >>> g
6420 [x > 0, x < 2]
6421 """
6422 args = _get_args(args)
6423 s = BoolSort(self.ctx)
6424 for arg in args:
6425 arg = s.cast(arg)
6426 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
6427
6428 def append(self, *args):
6429 """Add constraints.
6430
6431 >>> x = Int('x')
6432 >>> g = Goal()
6433 >>> g.append(x > 0, x < 2)
6434 >>> g
6435 [x > 0, x < 2]
6436 """
6437 self.assert_exprs(*args)
6438
6439 def insert(self, *args):
6440 """Add constraints.
6441
6442 >>> x = Int('x')
6443 >>> g = Goal()
6444 >>> g.insert(x > 0, x < 2)
6445 >>> g
6446 [x > 0, x < 2]
6447 """
6448 self.assert_exprs(*args)
6449
6450 def add(self, *args):
6451 """Add constraints.
6452
6453 >>> x = Int('x')
6454 >>> g = Goal()
6455 >>> g.add(x > 0, x < 2)
6456 >>> g
6457 [x > 0, x < 2]
6458 """
6459 self.assert_exprs(*args)
6460
6461 def convert_model(self, model):
6462 """Retrieve model from a satisfiable goal
6463 >>> a, b = Ints('a b')
6464 >>> g = Goal()
6465 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6466 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6467 >>> r = t(g)
6468 >>> r[0]
6469 [Or(b == 0, b == 1), Not(0 <= b)]
6470 >>> r[1]
6471 [Or(b == 0, b == 1), Not(1 <= b)]
6472 >>> # Remark: the subgoal r[0] is unsatisfiable
6473 >>> # Creating a solver for solving the second subgoal
6474 >>> s = Solver()
6475 >>> s.add(r[1])
6476 >>> s.check()
6477 sat
6478 >>> s.model()
6479 [b = 0]
6480 >>> # Model s.model() does not assign a value to `a`
6481 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6482 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6483 >>> r[1].convert_model(s.model())
6484 [b = 0, a = 1]
6485 """
6486 if z3_debug():
6487 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
6488 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
6489
6490 def __repr__(self):
6491 return obj_to_string(self)
6492
6493 def sexpr(self):
6494 """Return a textual representation of the s-expression representing the goal."""
6495 return Z3_goal_to_string(self.ctx.ref(), self.goal)
6496
6497 def dimacs(self, include_names=True):
6498 """Return a textual representation of the goal in DIMACS format."""
6499 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
6500
6501 def translate(self, target):
6502 """Copy goal `self` to context `target`.
6503
6504 >>> x = Int('x')
6505 >>> g = Goal()
6506 >>> g.add(x > 10)
6507 >>> g
6508 [x > 10]
6509 >>> c2 = Context()
6510 >>> g2 = g.translate(c2)
6511 >>> g2
6512 [x > 10]
6513 >>> g.ctx == main_ctx()
6514 True
6515 >>> g2.ctx == c2
6516 True
6517 >>> g2.ctx == main_ctx()
6518 False
6519 """
6520 if z3_debug():
6521 _z3_assert(isinstance(target, Context), "target must be a context")
6522 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
6523
6524 def __copy__(self):
6525 return self.translate(self.ctx)
6526
6527 def __deepcopy__(self, memo={}):
6528 return self.translate(self.ctx)
6529
6530 def simplify(self, *arguments, **keywords):
6531 """Return a new simplified goal.
6532
6533 This method is essentially invoking the simplify tactic.
6534
6535 >>> g = Goal()
6536 >>> x = Int('x')
6537 >>> g.add(x + 1 >= 2)
6538 >>> g
6539 [x + 1 >= 2]
6540 >>> g2 = g.simplify()
6541 >>> g2
6542 [x >= 1]
6543 >>> # g was not modified
6544 >>> g
6545 [x + 1 >= 2]
6546 """
6547 t = Tactic("simplify")
6548 return t.apply(self, *arguments, **keywords)[0]
6549
6550 def as_expr(self):
6551 """Return goal `self` as a single Z3 expression.
6552
6553 >>> x = Int('x')
6554 >>> g = Goal()
6555 >>> g.as_expr()
6556 True
6557 >>> g.add(x > 1)
6558 >>> g.as_expr()
6559 x > 1
6560 >>> g.add(x < 10)
6561 >>> g.as_expr()
6562 And(x > 1, x < 10)
6563 """
6564 sz = len(self)
6565 if sz == 0:
6566 return BoolVal(True, self.ctx)
6567 elif sz == 1:
6568 return self.get(0)
6569 else:
6570 return And([self.get(i) for i in range(len(self))], self.ctx)
6571
6572
6577
6578
6580 """A collection (vector) of ASTs."""
6581
6582 def __init__(self, v=None, ctx=None):
6583 self.vector = None
6584 if v is None:
6585 self.ctx = _get_ctx(ctx)
6586 self.vector = Z3_mk_ast_vector(self.ctx.ref())
6587 else:
6588 self.vector = v
6589 assert ctx is not None
6590 self.ctx = ctx
6591 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
6592
6593 def __del__(self):
6594 if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
6595 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
6596
6597 def __len__(self):
6598 """Return the size of the vector `self`.
6599
6600 >>> A = AstVector()
6601 >>> len(A)
6602 0
6603 >>> A.push(Int('x'))
6604 >>> A.push(Int('x'))
6605 >>> len(A)
6606 2
6607 """
6608 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
6609
6610 def __getitem__(self, i):
6611 """Return the AST at position `i`.
6612
6613 >>> A = AstVector()
6614 >>> A.push(Int('x') + 1)
6615 >>> A.push(Int('y'))
6616 >>> A[0]
6617 x + 1
6618 >>> A[1]
6619 y
6620 """
6621
6622 if isinstance(i, int):
6623 if i < 0:
6624 i += self.__len__()
6625
6626 if i >= self.__len__():
6627 raise IndexError
6628 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
6629
6630 elif isinstance(i, slice):
6631 result = []
6632 for ii in range(*i.indices(self.__len__())):
6633 result.append(_to_ast_ref(
6634 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
6635 self.ctx,
6636 ))
6637 return result
6638
6639 def __setitem__(self, i, v):
6640 """Update AST at position `i`.
6641
6642 >>> A = AstVector()
6643 >>> A.push(Int('x') + 1)
6644 >>> A.push(Int('y'))
6645 >>> A[0]
6646 x + 1
6647 >>> A[0] = Int('x')
6648 >>> A[0]
6649 x
6650 """
6651 if i < 0:
6652 i += self.__len__()
6653 if i < 0 or i >= self.__len__():
6654 raise IndexError
6655 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
6656
6657 def push(self, v):
6658 """Add `v` in the end of the vector.
6659
6660 >>> A = AstVector()
6661 >>> len(A)
6662 0
6663 >>> A.push(Int('x'))
6664 >>> len(A)
6665 1
6666 """
6667 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
6668
6669 def resize(self, sz):
6670 """Resize the vector to `sz` elements.
6671
6672 >>> A = AstVector()
6673 >>> A.resize(10)
6674 >>> len(A)
6675 10
6676 >>> for i in range(10): A[i] = Int('x')
6677 >>> A[5]
6678 x
6679 """
6680 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
6681
6682 def __contains__(self, item):
6683 """Return `True` if the vector contains `item`.
6684
6685 >>> x = Int('x')
6686 >>> A = AstVector()
6687 >>> x in A
6688 False
6689 >>> A.push(x)
6690 >>> x in A
6691 True
6692 >>> (x+1) in A
6693 False
6694 >>> A.push(x+1)
6695 >>> (x+1) in A
6696 True
6697 >>> A
6698 [x, x + 1]
6699 """
6700 for elem in self:
6701 if elem.eq(item):
6702 return True
6703 return False
6704
6705 def translate(self, other_ctx):
6706 """Copy vector `self` to context `other_ctx`.
6707
6708 >>> x = Int('x')
6709 >>> A = AstVector()
6710 >>> A.push(x)
6711 >>> c2 = Context()
6712 >>> B = A.translate(c2)
6713 >>> B
6714 [x]
6715 """
6716 return AstVector(
6717 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
6718 ctx=other_ctx,
6719 )
6720
6721 def __copy__(self):
6722 return self.translate(self.ctx)
6723
6724 def __deepcopy__(self, memo={}):
6725 return self.translate(self.ctx)
6726
6727 def __repr__(self):
6728 return obj_to_string(self)
6729
6730 def sexpr(self):
6731 """Return a textual representation of the s-expression representing the vector."""
6732 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
6733
6734
6739
6740
6742 """A mapping from ASTs to ASTs."""
6743
6744 def __init__(self, m=None, ctx=None):
6745 self.map = None
6746 if m is None:
6747 self.ctx = _get_ctx(ctx)
6748 self.map = Z3_mk_ast_map(self.ctx.ref())
6749 else:
6750 self.map = m
6751 assert ctx is not None
6752 self.ctx = ctx
6753 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6754
6755 def __deepcopy__(self, memo={}):
6756 return AstMap(self.map, self.ctx)
6757
6758 def __del__(self):
6759 if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6760 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6761
6762 def __len__(self):
6763 """Return the size of the map.
6764
6765 >>> M = AstMap()
6766 >>> len(M)
6767 0
6768 >>> x = Int('x')
6769 >>> M[x] = IntVal(1)
6770 >>> len(M)
6771 1
6772 """
6773 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6774
6775 def __contains__(self, key):
6776 """Return `True` if the map contains key `key`.
6777
6778 >>> M = AstMap()
6779 >>> x = Int('x')
6780 >>> M[x] = x + 1
6781 >>> x in M
6782 True
6783 >>> x+1 in M
6784 False
6785 """
6786 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6787
6788 def __getitem__(self, key):
6789 """Retrieve the value associated with key `key`.
6790
6791 >>> M = AstMap()
6792 >>> x = Int('x')
6793 >>> M[x] = x + 1
6794 >>> M[x]
6795 x + 1
6796 """
6797 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6798
6799 def __setitem__(self, k, v):
6800 """Add/Update key `k` with value `v`.
6801
6802 >>> M = AstMap()
6803 >>> x = Int('x')
6804 >>> M[x] = x + 1
6805 >>> len(M)
6806 1
6807 >>> M[x]
6808 x + 1
6809 >>> M[x] = IntVal(1)
6810 >>> M[x]
6811 1
6812 """
6813 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6814
6815 def __repr__(self):
6816 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6817
6818 def erase(self, k):
6819 """Remove the entry associated with key `k`.
6820
6821 >>> M = AstMap()
6822 >>> x = Int('x')
6823 >>> M[x] = x + 1
6824 >>> len(M)
6825 1
6826 >>> M.erase(x)
6827 >>> len(M)
6828 0
6829 """
6830 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6831
6832 def reset(self):
6833 """Remove all entries from the map.
6834
6835 >>> M = AstMap()
6836 >>> x = Int('x')
6837 >>> M[x] = x + 1
6838 >>> M[x+x] = IntVal(1)
6839 >>> len(M)
6840 2
6841 >>> M.reset()
6842 >>> len(M)
6843 0
6844 """
6845 Z3_ast_map_reset(self.ctx.ref(), self.map)
6846
6847 def keys(self):
6848 """Return an AstVector containing all keys in the map.
6849
6850 >>> M = AstMap()
6851 >>> x = Int('x')
6852 >>> M[x] = x + 1
6853 >>> M[x+x] = IntVal(1)
6854 >>> M.keys()
6855 [x + x, x]
6856 """
6857 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6858
6859
6864
6865
6867 """Store the value of the interpretation of a function in a particular point."""
6868
6869 def __init__(self, entry, ctx):
6870 self.entry = entry
6871 self.ctx = ctx
6872 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6873
6874 def __deepcopy__(self, memo={}):
6875 return FuncEntry(self.entry, self.ctx)
6876
6877 def __del__(self):
6878 if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6879 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6880
6881 def num_args(self):
6882 """Return the number of arguments in the given entry.
6883
6884 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6885 >>> s = Solver()
6886 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6887 >>> s.check()
6888 sat
6889 >>> m = s.model()
6890 >>> f_i = m[f]
6891 >>> f_i.num_entries()
6892 1
6893 >>> e = f_i.entry(0)
6894 >>> e.num_args()
6895 2
6896 """
6897 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6898
6899 def arg_value(self, idx):
6900 """Return the value of argument `idx`.
6901
6902 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6903 >>> s = Solver()
6904 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6905 >>> s.check()
6906 sat
6907 >>> m = s.model()
6908 >>> f_i = m[f]
6909 >>> f_i.num_entries()
6910 1
6911 >>> e = f_i.entry(0)
6912 >>> e
6913 [1, 2, 20]
6914 >>> e.num_args()
6915 2
6916 >>> e.arg_value(0)
6917 1
6918 >>> e.arg_value(1)
6919 2
6920 >>> try:
6921 ... e.arg_value(2)
6922 ... except IndexError:
6923 ... print("index error")
6924 index error
6925 """
6926 if idx >= self.num_args():
6927 raise IndexError
6928 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6929
6930 def value(self):
6931 """Return the value of the function at point `self`.
6932
6933 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6934 >>> s = Solver()
6935 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6936 >>> s.check()
6937 sat
6938 >>> m = s.model()
6939 >>> f_i = m[f]
6940 >>> f_i.num_entries()
6941 1
6942 >>> e = f_i.entry(0)
6943 >>> e
6944 [1, 2, 20]
6945 >>> e.num_args()
6946 2
6947 >>> e.value()
6948 20
6949 """
6950 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6951
6952 def as_list(self):
6953 """Return entry `self` as a Python list.
6954 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6955 >>> s = Solver()
6956 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6957 >>> s.check()
6958 sat
6959 >>> m = s.model()
6960 >>> f_i = m[f]
6961 >>> f_i.num_entries()
6962 1
6963 >>> e = f_i.entry(0)
6964 >>> e.as_list()
6965 [1, 2, 20]
6966 """
6967 args = [self.arg_value(i) for i in range(self.num_args())]
6968 args.append(self.value())
6969 return args
6970
6971 def __repr__(self):
6972 return repr(self.as_list())
6973
6974
6976 """Stores the interpretation of a function in a Z3 model."""
6977
6978 def __init__(self, f, ctx):
6979 self.f = f
6980 self.ctx = ctx
6981 if self.f is not None:
6982 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6983
6984 def __del__(self):
6985 if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6986 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6987
6988 def else_value(self):
6989 """
6990 Return the `else` value for a function interpretation.
6991 Return None if Z3 did not specify the `else` value for
6992 this object.
6993
6994 >>> f = Function('f', IntSort(), IntSort())
6995 >>> s = Solver()
6996 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6997 >>> s.check()
6998 sat
6999 >>> m = s.model()
7000 >>> m[f]
7001 [2 -> 0, else -> 1]
7002 >>> m[f].else_value()
7003 1
7004 """
7005 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
7006 if r:
7007 return _to_expr_ref(r, self.ctx)
7008 else:
7009 return None
7010
7011 def num_entries(self):
7012 """Return the number of entries/points in the function interpretation `self`.
7013
7014 >>> f = Function('f', IntSort(), IntSort())
7015 >>> s = Solver()
7016 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7017 >>> s.check()
7018 sat
7019 >>> m = s.model()
7020 >>> m[f]
7021 [2 -> 0, else -> 1]
7022 >>> m[f].num_entries()
7023 1
7024 """
7025 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
7026
7027 def arity(self):
7028 """Return the number of arguments for each entry in the function interpretation `self`.
7029
7030 >>> f = Function('f', IntSort(), IntSort())
7031 >>> s = Solver()
7032 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7033 >>> s.check()
7034 sat
7035 >>> m = s.model()
7036 >>> m[f].arity()
7037 1
7038 """
7039 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
7040
7041 def entry(self, idx):
7042 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
7043
7044 >>> f = Function('f', IntSort(), IntSort())
7045 >>> s = Solver()
7046 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7047 >>> s.check()
7048 sat
7049 >>> m = s.model()
7050 >>> m[f]
7051 [2 -> 0, else -> 1]
7052 >>> m[f].num_entries()
7053 1
7054 >>> m[f].entry(0)
7055 [2, 0]
7056 """
7057 if idx >= self.num_entries():
7058 raise IndexError
7059 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
7060
7061 def translate(self, other_ctx):
7062 """Copy model 'self' to context 'other_ctx'.
7063 """
7064 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
7065
7066 def __copy__(self):
7067 return self.translate(self.ctx)
7068
7069 def __deepcopy__(self, memo={}):
7070 return self.translate(self.ctx)
7071
7072 def as_list(self):
7073 """Return the function interpretation as a Python list.
7074 >>> f = Function('f', IntSort(), IntSort())
7075 >>> s = Solver()
7076 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7077 >>> s.check()
7078 sat
7079 >>> m = s.model()
7080 >>> m[f]
7081 [2 -> 0, else -> 1]
7082 >>> m[f].as_list()
7083 [[2, 0], 1]
7084 """
7085 r = [self.entry(i).as_list() for i in range(self.num_entries())]
7086 r.append(self.else_value())
7087 return r
7088
7089 def __repr__(self):
7090 return obj_to_string(self)
7091
7092
7094 """Model/Solution of a satisfiability problem (aka system of constraints)."""
7095
7096 def __init__(self, m, ctx):
7097 assert ctx is not None
7098 self.model = m
7099 self.ctx = ctx
7100 Z3_model_inc_ref(self.ctx.ref(), self.model)
7101
7102 def __del__(self):
7103 if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
7104 Z3_model_dec_ref(self.ctx.ref(), self.model)
7105
7106 def __repr__(self):
7107 return obj_to_string(self)
7108
7109 def sexpr(self):
7110 """Return a textual representation of the s-expression representing the model."""
7111 return Z3_model_to_string(self.ctx.ref(), self.model)
7112
7113 def eval(self, t, model_completion=False):
7114 """Evaluate the expression `t` in the model `self`.
7115 If `model_completion` is enabled, then a default interpretation is automatically added
7116 for symbols that do not have an interpretation in the model `self`.
7117
7118 >>> x = Int('x')
7119 >>> s = Solver()
7120 >>> s.add(x > 0, x < 2)
7121 >>> s.check()
7122 sat
7123 >>> m = s.model()
7124 >>> m.eval(x + 1)
7125 2
7126 >>> m.eval(x == 1)
7127 True
7128 >>> y = Int('y')
7129 >>> m.eval(y + x)
7130 1 + y
7131 >>> m.eval(y)
7132 y
7133 >>> m.eval(y, model_completion=True)
7134 0
7135 >>> # Now, m contains an interpretation for y
7136 >>> m.eval(y + x)
7137 1
7138 """
7139 r = (Ast * 1)()
7140 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
7141 return _to_expr_ref(r[0], self.ctx)
7142 raise Z3Exception("failed to evaluate expression in the model")
7143
7144 def evaluate(self, t, model_completion=False):
7145 """Alias for `eval`.
7146
7147 >>> x = Int('x')
7148 >>> s = Solver()
7149 >>> s.add(x > 0, x < 2)
7150 >>> s.check()
7151 sat
7152 >>> m = s.model()
7153 >>> m.evaluate(x + 1)
7154 2
7155 >>> m.evaluate(x == 1)
7156 True
7157 >>> y = Int('y')
7158 >>> m.evaluate(y + x)
7159 1 + y
7160 >>> m.evaluate(y)
7161 y
7162 >>> m.evaluate(y, model_completion=True)
7163 0
7164 >>> # Now, m contains an interpretation for y
7165 >>> m.evaluate(y + x)
7166 1
7167 """
7168 return self.eval(t, model_completion)
7169
7170 def __len__(self):
7171 """Return the number of constant and function declarations in the model `self`.
7172
7173 >>> f = Function('f', IntSort(), IntSort())
7174 >>> x = Int('x')
7175 >>> s = Solver()
7176 >>> s.add(x > 0, f(x) != x)
7177 >>> s.check()
7178 sat
7179 >>> m = s.model()
7180 >>> len(m)
7181 2
7182 """
7183 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
7184 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
7185 return num_consts + num_funcs
7186
7187 def get_interp(self, decl):
7188 """Return the interpretation for a given declaration or constant.
7189
7190 >>> f = Function('f', IntSort(), IntSort())
7191 >>> x = Int('x')
7192 >>> s = Solver()
7193 >>> s.add(x > 0, x < 2, f(x) == 0)
7194 >>> s.check()
7195 sat
7196 >>> m = s.model()
7197 >>> m[x]
7198 1
7199 >>> m[f]
7200 [else -> 0]
7201 """
7202 if z3_debug():
7203 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
7204 if is_const(decl):
7205 decl = decl.decl()
7206 try:
7207 if decl.arity() == 0:
7208 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
7209 if _r.value is None:
7210 return None
7211 r = _to_expr_ref(_r, self.ctx)
7212 if is_as_array(r):
7213 fi = self.get_interp(get_as_array_func(r))
7214 if fi is None:
7215 return fi
7216 e = fi.else_value()
7217 if e is None:
7218 return fi
7219 if fi.arity() != 1:
7220 return fi
7221 srt = decl.range()
7222 dom = srt.domain()
7223 e = K(dom, e)
7224 i = 0
7225 sz = fi.num_entries()
7226 n = fi.arity()
7227 while i < sz:
7228 fe = fi.entry(i)
7229 e = Store(e, fe.arg_value(0), fe.value())
7230 i += 1
7231 return e
7232 else:
7233 return r
7234 else:
7235 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
7236 except Z3Exception:
7237 return None
7238
7239 def num_sorts(self):
7240 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7241
7242 >>> A = DeclareSort('A')
7243 >>> a, b = Consts('a b', A)
7244 >>> s = Solver()
7245 >>> s.add(a != b)
7246 >>> s.check()
7247 sat
7248 >>> m = s.model()
7249 >>> m.num_sorts()
7250 1
7251 """
7252 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
7253
7254 def get_sort(self, idx):
7255 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7256
7257 >>> A = DeclareSort('A')
7258 >>> B = DeclareSort('B')
7259 >>> a1, a2 = Consts('a1 a2', A)
7260 >>> b1, b2 = Consts('b1 b2', B)
7261 >>> s = Solver()
7262 >>> s.add(a1 != a2, b1 != b2)
7263 >>> s.check()
7264 sat
7265 >>> m = s.model()
7266 >>> m.num_sorts()
7267 2
7268 >>> m.get_sort(0)
7269 A
7270 >>> m.get_sort(1)
7271 B
7272 """
7273 if idx >= self.num_sorts():
7274 raise IndexError
7275 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
7276
7277 def sorts(self):
7278 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7279
7280 >>> A = DeclareSort('A')
7281 >>> B = DeclareSort('B')
7282 >>> a1, a2 = Consts('a1 a2', A)
7283 >>> b1, b2 = Consts('b1 b2', B)
7284 >>> s = Solver()
7285 >>> s.add(a1 != a2, b1 != b2)
7286 >>> s.check()
7287 sat
7288 >>> m = s.model()
7289 >>> m.sorts()
7290 [A, B]
7291 """
7292 return [self.get_sort(i) for i in range(self.num_sorts())]
7293
7294 def get_universe(self, s):
7295 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7296
7297 >>> A = DeclareSort('A')
7298 >>> a, b = Consts('a b', A)
7299 >>> s = Solver()
7300 >>> s.add(a != b)
7301 >>> s.check()
7302 sat
7303 >>> m = s.model()
7304 >>> m.get_universe(A)
7305 [A!val!0, A!val!1]
7306 """
7307 if z3_debug():
7308 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
7309 try:
7310 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
7311 except Z3Exception:
7312 return None
7313
7314 def __getitem__(self, idx):
7315 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7316 If `idx` is a declaration, then the actual interpretation is returned.
7317
7318 The elements can be retrieved using position or the actual declaration.
7319
7320 >>> f = Function('f', IntSort(), IntSort())
7321 >>> x = Int('x')
7322 >>> s = Solver()
7323 >>> s.add(x > 0, x < 2, f(x) == 0)
7324 >>> s.check()
7325 sat
7326 >>> m = s.model()
7327 >>> len(m)
7328 2
7329 >>> m[0]
7330 x
7331 >>> m[1]
7332 f
7333 >>> m[x]
7334 1
7335 >>> m[f]
7336 [else -> 0]
7337 >>> for d in m: print("%s -> %s" % (d, m[d]))
7338 x -> 1
7339 f -> [else -> 0]
7340 """
7341 if _is_int(idx):
7342 if idx < 0:
7343 idx += len(self)
7344 if idx < 0 or idx >= len(self):
7345 raise IndexError
7346 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
7347 if (idx < num_consts):
7348 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
7349 else:
7350 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
7351 if isinstance(idx, FuncDeclRef):
7352 return self.get_interp(idx)
7353 if is_const(idx):
7354 return self.get_interp(idx.decl())
7355 if isinstance(idx, SortRef):
7356 return self.get_universe(idx)
7357 if z3_debug():
7358 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7359 return None
7360
7361 def decls(self):
7362 """Return a list with all symbols that have an interpretation in the model `self`.
7363 >>> f = Function('f', IntSort(), IntSort())
7364 >>> x = Int('x')
7365 >>> s = Solver()
7366 >>> s.add(x > 0, x < 2, f(x) == 0)
7367 >>> s.check()
7368 sat
7369 >>> m = s.model()
7370 >>> m.decls()
7371 [x, f]
7372 """
7373 r = []
7374 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
7375 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
7376 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
7377 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
7378 return r
7379
7380 def update_value(self, x, value):
7381 """Update the interpretation of a constant"""
7382 if is_expr(x):
7383 x = x.decl()
7384 if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
7385 fi1 = value.f
7386 fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
7387 fi2 = FuncInterp(fi2, x.ctx)
7388 for i in range(value.num_entries()):
7389 e = value.entry(i)
7390 n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
7391 v = AstVector()
7392 for j in range(n):
7393 v.push(e.arg_value(j))
7394 val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
7395 Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
7396 return
7397 if not is_func_decl(x) or x.arity() != 0:
7398 raise Z3Exception("Expecting 0-ary function or constant expression")
7399 value = _py2expr(value)
7400 Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
7401
7402 def translate(self, target):
7403 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7404 """
7405 if z3_debug():
7406 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7407 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
7408 return ModelRef(model, target)
7409
7410 def project(self, vars, fml):
7411 """Perform model-based projection on fml with respect to vars.
7412 Assume that the model satisfies fml. Then compute a projection fml_p, such
7413 that vars do not occur free in fml_p, fml_p is true in the model and
7414 fml_p => exists vars . fml
7415 """
7416 ctx = self.ctx.ref()
7417 _vars = (Ast * len(vars))()
7418 for i in range(len(vars)):
7419 _vars[i] = vars[i].as_ast()
7420 return _to_expr_ref(Z3_qe_model_project(ctx, self.model, len(vars), _vars, fml.ast), self.ctx)
7421
7422 def project_with_witness(self, vars, fml):
7423 """Perform model-based projection, but also include realizer terms for the projected variables"""
7424 ctx = self.ctx.ref()
7425 _vars = (Ast * len(vars))()
7426 for i in range(len(vars)):
7427 _vars[i] = vars[i].as_ast()
7428 defs = AstMap()
7429 result = Z3_qe_model_project_with_witness(ctx, self.model, len(vars), _vars, fml.ast, defs.map)
7430 result = _to_expr_ref(result, self.ctx)
7431 return result, defs
7432
7433
7434 def __copy__(self):
7435 return self.translate(self.ctx)
7436
7437 def __deepcopy__(self, memo={}):
7438 return self.translate(self.ctx)
7439
7440
7441def Model(ctx=None, eval = {}):
7442 ctx = _get_ctx(ctx)
7443 mdl = ModelRef(Z3_mk_model(ctx.ref()), ctx)
7444 for k, v in eval.items():
7445 mdl.update_value(k, v)
7446 return mdl
7447
7448
7450 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7451 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7452
7453
7455 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7456 if z3_debug():
7457 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
7458 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
7459
7460
7465
7466
7468 """Statistics for `Solver.check()`."""
7469
7470 def __init__(self, stats, ctx):
7471 self.stats = stats
7472 self.ctx = ctx
7473 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
7474
7475 def __deepcopy__(self, memo={}):
7476 return Statistics(self.stats, self.ctx)
7477
7478 def __del__(self):
7479 if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
7480 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
7481
7482 def __repr__(self):
7483 if in_html_mode():
7484 out = io.StringIO()
7485 even = True
7486 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
7487 for k, v in self:
7488 if even:
7489 out.write(u('<tr style="background-color:#CFCFCF">'))
7490 even = False
7491 else:
7492 out.write(u("<tr>"))
7493 even = True
7494 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
7495 out.write(u("</table>"))
7496 return out.getvalue()
7497 else:
7498 return Z3_stats_to_string(self.ctx.ref(), self.stats)
7499
7500 def __len__(self):
7501 """Return the number of statistical counters.
7502
7503 >>> x = Int('x')
7504 >>> s = Then('simplify', 'nlsat').solver()
7505 >>> s.add(x > 0)
7506 >>> s.check()
7507 sat
7508 >>> st = s.statistics()
7509 >>> len(st) > 0
7510 True
7511 """
7512 return int(Z3_stats_size(self.ctx.ref(), self.stats))
7513
7514 def __getitem__(self, idx):
7515 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7516
7517 >>> x = Int('x')
7518 >>> s = Then('simplify', 'nlsat').solver()
7519 >>> s.add(x > 0)
7520 >>> s.check()
7521 sat
7522 >>> st = s.statistics()
7523 >>> len(st) > 0
7524 True
7525 >>> st[0]
7526 ('nlsat propagations', 2)
7527 >>> st[1]
7528 ('nlsat restarts', 1)
7529 """
7530 if idx >= len(self):
7531 raise IndexError
7532 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7533 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7534 else:
7535 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7536 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
7537
7538 def keys(self):
7539 """Return the list of statistical counters.
7540
7541 >>> x = Int('x')
7542 >>> s = Then('simplify', 'nlsat').solver()
7543 >>> s.add(x > 0)
7544 >>> s.check()
7545 sat
7546 >>> st = s.statistics()
7547 """
7548 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
7549
7550 def get_key_value(self, key):
7551 """Return the value of a particular statistical counter.
7552
7553 >>> x = Int('x')
7554 >>> s = Then('simplify', 'nlsat').solver()
7555 >>> s.add(x > 0)
7556 >>> s.check()
7557 sat
7558 >>> st = s.statistics()
7559 >>> st.get_key_value('nlsat propagations')
7560 2
7561 """
7562 for idx in range(len(self)):
7563 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
7564 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7565 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7566 else:
7567 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7568 raise Z3Exception("unknown key")
7569
7570 def __getattr__(self, name):
7571 """Access the value of statistical using attributes.
7572
7573 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7574 we should use '_' (e.g., 'nlsat_propagations').
7575
7576 >>> x = Int('x')
7577 >>> s = Then('simplify', 'nlsat').solver()
7578 >>> s.add(x > 0)
7579 >>> s.check()
7580 sat
7581 >>> st = s.statistics()
7582 >>> st.nlsat_propagations
7583 2
7584 >>> st.nlsat_stages
7585 2
7586 """
7587 key = name.replace("_", " ")
7588 try:
7589 return self.get_key_value(key)
7590 except Z3Exception:
7591 raise AttributeError
7592
7593
7598
7599
7601 """Represents the result of a satisfiability check: sat, unsat, unknown.
7602
7603 >>> s = Solver()
7604 >>> s.check()
7605 sat
7606 >>> r = s.check()
7607 >>> isinstance(r, CheckSatResult)
7608 True
7609 """
7610
7611 def __init__(self, r):
7612 self.r = r
7613
7614 def __deepcopy__(self, memo={}):
7615 return CheckSatResult(self.r)
7616
7617 def __eq__(self, other):
7618 return isinstance(other, CheckSatResult) and self.r == other.r
7619
7620 def __ne__(self, other):
7621 return not self.__eq__(other)
7622
7623 def __repr__(self):
7624 if in_html_mode():
7625 if self.r == Z3_L_TRUE:
7626 return "<b>sat</b>"
7627 elif self.r == Z3_L_FALSE:
7628 return "<b>unsat</b>"
7629 else:
7630 return "<b>unknown</b>"
7631 else:
7632 if self.r == Z3_L_TRUE:
7633 return "sat"
7634 elif self.r == Z3_L_FALSE:
7635 return "unsat"
7636 else:
7637 return "unknown"
7638
7639 def _repr_html_(self):
7640 in_html = in_html_mode()
7641 set_html_mode(True)
7642 res = repr(self)
7643 set_html_mode(in_html)
7644 return res
7645
7646
7647sat = CheckSatResult(Z3_L_TRUE)
7648unsat = CheckSatResult(Z3_L_FALSE)
7649unknown = CheckSatResult(Z3_L_UNDEF)
7650
7651
7653 """
7654 Solver API provides methods for implementing the main SMT 2.0 commands:
7655 push, pop, check, get-model, etc.
7656 """
7657
7658 def __init__(self, solver=None, ctx=None, logFile=None):
7659 assert solver is None or ctx is not None
7660 self.ctx = _get_ctx(ctx)
7661 self.backtrack_level = 4000000000
7662 self.solver = None
7663 if solver is None:
7664 self.solver = Z3_mk_solver(self.ctx.ref())
7665 else:
7666 self.solver = solver
7667 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
7668 if logFile is not None:
7669 self.set("smtlib2_log", logFile)
7670
7671 def __del__(self):
7672 if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
7673 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
7674
7675 def __enter__(self):
7676 self.push()
7677 return self
7678
7679 def __exit__(self, *exc_info):
7680 self.pop()
7681
7682 def set(self, *args, **keys):
7683 """Set a configuration option.
7684 The method `help()` return a string containing all available options.
7685
7686 >>> s = Solver()
7687 >>> # The option MBQI can be set using three different approaches.
7688 >>> s.set(mbqi=True)
7689 >>> s.set('MBQI', True)
7690 >>> s.set(':mbqi', True)
7691 """
7692 p = args2params(args, keys, self.ctx)
7693 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
7694
7695 def push(self):
7696 """Create a backtracking point.
7697
7698 >>> x = Int('x')
7699 >>> s = Solver()
7700 >>> s.add(x > 0)
7701 >>> s
7702 [x > 0]
7703 >>> s.push()
7704 >>> s.add(x < 1)
7705 >>> s
7706 [x > 0, x < 1]
7707 >>> s.check()
7708 unsat
7709 >>> s.pop()
7710 >>> s.check()
7711 sat
7712 >>> s
7713 [x > 0]
7714 """
7715 Z3_solver_push(self.ctx.ref(), self.solver)
7716
7717 def pop(self, num=1):
7718 """Backtrack \\c num backtracking points.
7719
7720 >>> x = Int('x')
7721 >>> s = Solver()
7722 >>> s.add(x > 0)
7723 >>> s
7724 [x > 0]
7725 >>> s.push()
7726 >>> s.add(x < 1)
7727 >>> s
7728 [x > 0, x < 1]
7729 >>> s.check()
7730 unsat
7731 >>> s.pop()
7732 >>> s.check()
7733 sat
7734 >>> s
7735 [x > 0]
7736 """
7737 Z3_solver_pop(self.ctx.ref(), self.solver, num)
7738
7739 def num_scopes(self):
7740 """Return the current number of backtracking points.
7741
7742 >>> s = Solver()
7743 >>> s.num_scopes()
7744 0
7745 >>> s.push()
7746 >>> s.num_scopes()
7747 1
7748 >>> s.push()
7749 >>> s.num_scopes()
7750 2
7751 >>> s.pop()
7752 >>> s.num_scopes()
7753 1
7754 """
7755 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
7756
7757 def reset(self):
7758 """Remove all asserted constraints and backtracking points created using `push()`.
7759
7760 >>> x = Int('x')
7761 >>> s = Solver()
7762 >>> s.add(x > 0)
7763 >>> s
7764 [x > 0]
7765 >>> s.reset()
7766 >>> s
7767 []
7768 """
7769 Z3_solver_reset(self.ctx.ref(), self.solver)
7770
7771 def assert_exprs(self, *args):
7772 """Assert constraints into the solver.
7773
7774 >>> x = Int('x')
7775 >>> s = Solver()
7776 >>> s.assert_exprs(x > 0, x < 2)
7777 >>> s
7778 [x > 0, x < 2]
7779 """
7780 args = _get_args(args)
7781 s = BoolSort(self.ctx)
7782 for arg in args:
7783 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7784 for f in arg:
7785 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7786 else:
7787 arg = s.cast(arg)
7788 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7789
7790 def add(self, *args):
7791 """Assert constraints into the solver.
7792
7793 >>> x = Int('x')
7794 >>> s = Solver()
7795 >>> s.add(x > 0, x < 2)
7796 >>> s
7797 [x > 0, x < 2]
7798 """
7799 self.assert_exprs(*args)
7800
7801 def __iadd__(self, fml):
7802 self.add(fml)
7803 return self
7804
7805 def append(self, *args):
7806 """Assert constraints into the solver.
7807
7808 >>> x = Int('x')
7809 >>> s = Solver()
7810 >>> s.append(x > 0, x < 2)
7811 >>> s
7812 [x > 0, x < 2]
7813 """
7814 self.assert_exprs(*args)
7815
7816 def insert(self, *args):
7817 """Assert constraints into the solver.
7818
7819 >>> x = Int('x')
7820 >>> s = Solver()
7821 >>> s.insert(x > 0, x < 2)
7822 >>> s
7823 [x > 0, x < 2]
7824 """
7825 self.assert_exprs(*args)
7826
7827 def assert_and_track(self, a, p):
7828 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7829
7830 If `p` is a string, it will be automatically converted into a Boolean constant.
7831
7832 >>> x = Int('x')
7833 >>> p3 = Bool('p3')
7834 >>> s = Solver()
7835 >>> s.set(unsat_core=True)
7836 >>> s.assert_and_track(x > 0, 'p1')
7837 >>> s.assert_and_track(x != 1, 'p2')
7838 >>> s.assert_and_track(x < 0, p3)
7839 >>> print(s.check())
7840 unsat
7841 >>> c = s.unsat_core()
7842 >>> len(c)
7843 2
7844 >>> Bool('p1') in c
7845 True
7846 >>> Bool('p2') in c
7847 False
7848 >>> p3 in c
7849 True
7850 """
7851 if isinstance(p, str):
7852 p = Bool(p, self.ctx)
7853 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7854 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7855 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7856
7857 def check(self, *assumptions):
7858 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7859
7860 >>> x = Int('x')
7861 >>> s = Solver()
7862 >>> s.check()
7863 sat
7864 >>> s.add(x > 0, x < 2)
7865 >>> s.check()
7866 sat
7867 >>> s.model().eval(x)
7868 1
7869 >>> s.add(x < 1)
7870 >>> s.check()
7871 unsat
7872 >>> s.reset()
7873 >>> s.add(2**x == 4)
7874 >>> s.check()
7875 sat
7876 """
7877 s = BoolSort(self.ctx)
7878 assumptions = _get_args(assumptions)
7879 num = len(assumptions)
7880 _assumptions = (Ast * num)()
7881 for i in range(num):
7882 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7883 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7884 return CheckSatResult(r)
7885
7886 def model(self):
7887 """Return a model for the last `check()`.
7888
7889 This function raises an exception if
7890 a model is not available (e.g., last `check()` returned unsat).
7891
7892 >>> s = Solver()
7893 >>> a = Int('a')
7894 >>> s.add(a + 2 == 0)
7895 >>> s.check()
7896 sat
7897 >>> s.model()
7898 [a = -2]
7899 """
7900 try:
7901 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7902 except Z3Exception:
7903 raise Z3Exception("model is not available")
7904
7905 def import_model_converter(self, other):
7906 """Import model converter from other into the current solver"""
7907 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7908
7909 def interrupt(self):
7910 """Interrupt the execution of the solver object.
7911 Remarks: This ensures that the interrupt applies only
7912 to the given solver object and it applies only if it is running.
7913 """
7914 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7915
7916 def unsat_core(self):
7917 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7918
7919 These are the assumptions Z3 used in the unsatisfiability proof.
7920 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7921 They may be also used to "retract" assumptions. Note that, assumptions are not really
7922 "soft constraints", but they can be used to implement them.
7923
7924 >>> p1, p2, p3 = Bools('p1 p2 p3')
7925 >>> x, y = Ints('x y')
7926 >>> s = Solver()
7927 >>> s.add(Implies(p1, x > 0))
7928 >>> s.add(Implies(p2, y > x))
7929 >>> s.add(Implies(p2, y < 1))
7930 >>> s.add(Implies(p3, y > -3))
7931 >>> s.check(p1, p2, p3)
7932 unsat
7933 >>> core = s.unsat_core()
7934 >>> len(core)
7935 2
7936 >>> p1 in core
7937 True
7938 >>> p2 in core
7939 True
7940 >>> p3 in core
7941 False
7942 >>> # "Retracting" p2
7943 >>> s.check(p1, p3)
7944 sat
7945 """
7946 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7947
7948 def consequences(self, assumptions, variables):
7949 """Determine fixed values for the variables based on the solver state and assumptions.
7950 >>> s = Solver()
7951 >>> a, b, c, d = Bools('a b c d')
7952 >>> s.add(Implies(a,b), Implies(b, c))
7953 >>> s.consequences([a],[b,c,d])
7954 (sat, [Implies(a, b), Implies(a, c)])
7955 >>> s.consequences([Not(c),d],[a,b,c,d])
7956 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7957 """
7958 if isinstance(assumptions, list):
7959 _asms = AstVector(None, self.ctx)
7960 for a in assumptions:
7961 _asms.push(a)
7962 assumptions = _asms
7963 if isinstance(variables, list):
7964 _vars = AstVector(None, self.ctx)
7965 for a in variables:
7966 _vars.push(a)
7967 variables = _vars
7968 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7969 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7970 consequences = AstVector(None, self.ctx)
7971 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7972 variables.vector, consequences.vector)
7973 sz = len(consequences)
7974 consequences = [consequences[i] for i in range(sz)]
7975 return CheckSatResult(r), consequences
7976
7977 def from_file(self, filename):
7978 """Parse assertions from a file"""
7979 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7980
7981 def from_string(self, s):
7982 """Parse assertions from a string"""
7983 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7984
7985 def cube(self, vars=None):
7986 """Get set of cubes
7987 The method takes an optional set of variables that restrict which
7988 variables may be used as a starting point for cubing.
7989 If vars is not None, then the first case split is based on a variable in
7990 this set.
7991 """
7992 self.cube_vs = AstVector(None, self.ctx)
7993 if vars is not None:
7994 for v in vars:
7995 self.cube_vs.push(v)
7996 while True:
7997 lvl = self.backtrack_level
7998 self.backtrack_level = 4000000000
7999 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
8000 if (len(r) == 1 and is_false(r[0])):
8001 return
8002 yield r
8003 if (len(r) == 0):
8004 return
8005
8006 def cube_vars(self):
8007 """Access the set of variables that were touched by the most recently generated cube.
8008 This set of variables can be used as a starting point for additional cubes.
8009 The idea is that variables that appear in clauses that are reduced by the most recent
8010 cube are likely more useful to cube on."""
8011 return self.cube_vs
8012
8013 def congruence_root(self, t):
8014 """Retrieve congruence closure root of the term t relative to the current search state
8015 The function primarily works for SimpleSolver. Terms and variables that are
8016 eliminated during pre-processing are not visible to the congruence closure.
8017 """
8018 t = _py2expr(t, self.ctx)
8019 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
8020
8021 def congruence_next(self, t):
8022 """Retrieve congruence closure sibling of the term t relative to the current search state
8023 The function primarily works for SimpleSolver. Terms and variables that are
8024 eliminated during pre-processing are not visible to the congruence closure.
8025 """
8026 t = _py2expr(t, self.ctx)
8027 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
8028
8029 def congruence_explain(self, a, b):
8030 """Explain congruence of a and b relative to the current search state"""
8031 a = _py2expr(a, self.ctx)
8032 b = _py2expr(b, self.ctx)
8033 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
8034
8035
8036 def solve_for(self, ts):
8037 """Retrieve a solution for t relative to linear equations maintained in the current state."""
8038 vars = AstVector(ctx=self.ctx);
8039 terms = AstVector(ctx=self.ctx);
8040 guards = AstVector(ctx=self.ctx);
8041 for t in ts:
8042 t = _py2expr(t, self.ctx)
8043 vars.push(t)
8044 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
8045 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
8046
8047
8048 def proof(self):
8049 """Return a proof for the last `check()`. Proof construction must be enabled."""
8050 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
8051
8052 def assertions(self):
8053 """Return an AST vector containing all added constraints.
8054
8055 >>> s = Solver()
8056 >>> s.assertions()
8057 []
8058 >>> a = Int('a')
8059 >>> s.add(a > 0)
8060 >>> s.add(a < 10)
8061 >>> s.assertions()
8062 [a > 0, a < 10]
8063 """
8064 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
8065
8066 def units(self):
8067 """Return an AST vector containing all currently inferred units.
8068 """
8069 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
8070
8071 def non_units(self):
8072 """Return an AST vector containing all atomic formulas in solver state that are not units.
8073 """
8074 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
8075
8076 def trail_levels(self):
8077 """Return trail and decision levels of the solver state after a check() call.
8078 """
8079 trail = self.trail()
8080 levels = (ctypes.c_uint * len(trail))()
8081 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
8082 return trail, levels
8083
8084 def set_initial_value(self, var, value):
8085 """initialize the solver's state by setting the initial value of var to value
8086 """
8087 s = var.sort()
8088 value = s.cast(value)
8089 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
8090
8091 def trail(self):
8092 """Return trail of the solver state after a check() call.
8093 """
8094 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
8095
8096 def statistics(self):
8097 """Return statistics for the last `check()`.
8098
8099 >>> s = SimpleSolver()
8100 >>> x = Int('x')
8101 >>> s.add(x > 0)
8102 >>> s.check()
8103 sat
8104 >>> st = s.statistics()
8105 >>> st.get_key_value('final checks')
8106 1
8107 >>> len(st) > 0
8108 True
8109 >>> st[0] != 0
8110 True
8111 """
8112 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8113
8114 def reason_unknown(self):
8115 """Return a string describing why the last `check()` returned `unknown`.
8116
8117 >>> x = Int('x')
8118 >>> s = SimpleSolver()
8119 >>> s.add(x == 2**x)
8120 >>> s.check()
8121 unknown
8122 >>> s.reason_unknown()
8123 '(incomplete (theory arithmetic))'
8124 """
8125 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8126
8127 def help(self):
8128 """Display a string describing all available options."""
8129 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8130
8131 def param_descrs(self):
8132 """Return the parameter description set."""
8133 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8134
8135 def __repr__(self):
8136 """Return a formatted string with all added constraints."""
8137 return obj_to_string(self)
8138
8139 def translate(self, target):
8140 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8141
8142 >>> c1 = Context()
8143 >>> c2 = Context()
8144 >>> s1 = Solver(ctx=c1)
8145 >>> s2 = s1.translate(c2)
8146 """
8147 if z3_debug():
8148 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8149 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8150 return Solver(solver, target)
8151
8152 def __copy__(self):
8153 return self.translate(self.ctx)
8154
8155 def __deepcopy__(self, memo={}):
8156 return self.translate(self.ctx)
8157
8158 def sexpr(self):
8159 """Return a formatted string (in Lisp-like format) with all added constraints.
8160 """
8161 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8162
8163 def dimacs(self, include_names=True):
8164 """Return a textual representation of the solver in DIMACS format."""
8165 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8166
8167 def to_smt2(self):
8168 """return SMTLIB2 formatted benchmark for solver's assertions"""
8169 es = self.assertions()
8170 sz = len(es)
8171 sz1 = sz
8172 if sz1 > 0:
8173 sz1 -= 1
8174 v = (Ast * sz1)()
8175 for i in range(sz1):
8176 v[i] = es[i].as_ast()
8177 if sz > 0:
8178 e = es[sz1].as_ast()
8179 else:
8180 e = BoolVal(True, self.ctx).as_ast()
8181 return Z3_benchmark_to_smtlib_string(
8182 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8183 )
8184
8185 def solutions(self, t):
8186 """Returns an iterator over solutions that satisfy the constraints.
8187
8188 The parameter `t` is an expression whose values should be returned.
8189
8190 >>> s = Solver()
8191 >>> x, y, z = Ints("x y z")
8192 >>> s.add(x * x == 4)
8193 >>> print(list(s.solutions(x)))
8194 [-2, 2]
8195 >>> s.reset()
8196 >>> s.add(x >= 0, x < 10)
8197 >>> print(list(s.solutions(x)))
8198 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8199 >>> s.reset()
8200 >>> s.add(x >= 0, y < 10, y == 2*x)
8201 >>> print(list(s.solutions([x, y])))
8202 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8203 """
8204 s = Solver()
8205 s.add(self.assertions())
8206 t = _get_args(t)
8207 if isinstance(t, (list, tuple)):
8208 while s.check() == sat:
8209 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8210 yield result
8211 s.add(Or(t_ != result_ for t_, result_ in zip(t, result)))
8212 else:
8213 while s.check() == sat:
8214 result = s.model().eval(t, model_completion=True)
8215 yield result
8216 s.add(t != result)
8217
8218
8219def SolverFor(logic, ctx=None, logFile=None):
8220 """Create a solver customized for the given logic.
8221
8222 The parameter `logic` is a string. It should be contains
8223 the name of a SMT-LIB logic.
8224 See http://www.smtlib.org/ for the name of all available logics.
8225
8226 >>> s = SolverFor("QF_LIA")
8227 >>> x = Int('x')
8228 >>> s.add(x > 0)
8229 >>> s.add(x < 2)
8230 >>> s.check()
8231 sat
8232 >>> s.model()
8233 [x = 1]
8234 """
8235 ctx = _get_ctx(ctx)
8236 logic = to_symbol(logic)
8237 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8238
8239
8240def SimpleSolver(ctx=None, logFile=None):
8241 """Return a simple general purpose solver with limited amount of preprocessing.
8242
8243 >>> s = SimpleSolver()
8244 >>> x = Int('x')
8245 >>> s.add(x > 0)
8246 >>> s.check()
8247 sat
8248 """
8249 ctx = _get_ctx(ctx)
8250 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8251
8252#########################################
8253#
8254# Fixedpoint
8255#
8256#########################################
8257
8258
8259class Fixedpoint(Z3PPObject):
8260 """Fixedpoint API provides methods for solving with recursive predicates"""
8261
8262 def __init__(self, fixedpoint=None, ctx=None):
8263 assert fixedpoint is None or ctx is not None
8264 self.ctx = _get_ctx(ctx)
8265 self.fixedpoint = None
8266 if fixedpoint is None:
8267 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8268 else:
8269 self.fixedpoint = fixedpoint
8270 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8271 self.vars = []
8272
8273 def __deepcopy__(self, memo={}):
8274 return FixedPoint(self.fixedpoint, self.ctx)
8275
8276 def __del__(self):
8277 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8278 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8279
8280 def set(self, *args, **keys):
8281 """Set a configuration option. The method `help()` return a string containing all available options.
8282 """
8283 p = args2params(args, keys, self.ctx)
8284 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8285
8286 def help(self):
8287 """Display a string describing all available options."""
8288 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8289
8290 def param_descrs(self):
8291 """Return the parameter description set."""
8292 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8293
8294 def assert_exprs(self, *args):
8295 """Assert constraints as background axioms for the fixedpoint solver."""
8296 args = _get_args(args)
8297 s = BoolSort(self.ctx)
8298 for arg in args:
8299 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8300 for f in arg:
8301 f = self.abstract(f)
8302 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8303 else:
8304 arg = s.cast(arg)
8305 arg = self.abstract(arg)
8306 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8307
8308 def add(self, *args):
8309 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8310 self.assert_exprs(*args)
8311
8312 def __iadd__(self, fml):
8313 self.add(fml)
8314 return self
8315
8316 def append(self, *args):
8317 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8318 self.assert_exprs(*args)
8319
8320 def insert(self, *args):
8321 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8322 self.assert_exprs(*args)
8323
8324 def add_rule(self, head, body=None, name=None):
8325 """Assert rules defining recursive predicates to the fixedpoint solver.
8326 >>> a = Bool('a')
8327 >>> b = Bool('b')
8328 >>> s = Fixedpoint()
8329 >>> s.register_relation(a.decl())
8330 >>> s.register_relation(b.decl())
8331 >>> s.fact(a)
8332 >>> s.rule(b, a)
8333 >>> s.query(b)
8334 sat
8335 """
8336 if name is None:
8337 name = ""
8338 name = to_symbol(name, self.ctx)
8339 if body is None:
8340 head = self.abstract(head)
8341 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8342 else:
8343 body = _get_args(body)
8344 f = self.abstract(Implies(And(body, self.ctx), head))
8345 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8346
8347 def rule(self, head, body=None, name=None):
8348 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8349 self.add_rule(head, body, name)
8350
8351 def fact(self, head, name=None):
8352 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8353 self.add_rule(head, None, name)
8354
8355 def query(self, *query):
8356 """Query the fixedpoint engine whether formula is derivable.
8357 You can also pass an tuple or list of recursive predicates.
8358 """
8359 query = _get_args(query)
8360 sz = len(query)
8361 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8362 _decls = (FuncDecl * sz)()
8363 i = 0
8364 for q in query:
8365 _decls[i] = q.ast
8366 i = i + 1
8367 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8368 else:
8369 if sz == 1:
8370 query = query[0]
8371 else:
8372 query = And(query, self.ctx)
8373 query = self.abstract(query, False)
8374 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8375 return CheckSatResult(r)
8376
8377 def query_from_lvl(self, lvl, *query):
8378 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8379 """
8380 query = _get_args(query)
8381 sz = len(query)
8382 if sz >= 1 and isinstance(query[0], FuncDecl):
8383 _z3_assert(False, "unsupported")
8384 else:
8385 if sz == 1:
8386 query = query[0]
8387 else:
8388 query = And(query)
8389 query = self.abstract(query, False)
8390 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8391 return CheckSatResult(r)
8392
8393 def update_rule(self, head, body, name):
8394 """update rule"""
8395 if name is None:
8396 name = ""
8397 name = to_symbol(name, self.ctx)
8398 body = _get_args(body)
8399 f = self.abstract(Implies(And(body, self.ctx), head))
8400 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8401
8402 def get_answer(self):
8403 """Retrieve answer from last query call."""
8404 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8405 return _to_expr_ref(r, self.ctx)
8406
8407 def get_ground_sat_answer(self):
8408 """Retrieve a ground cex from last query call."""
8409 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8410 return _to_expr_ref(r, self.ctx)
8411
8412 def get_rules_along_trace(self):
8413 """retrieve rules along the counterexample trace"""
8414 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8415
8416 def get_rule_names_along_trace(self):
8417 """retrieve rule names along the counterexample trace"""
8418 # this is a hack as I don't know how to return a list of symbols from C++;
8419 # obtain names as a single string separated by semicolons
8420 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8421 # split into individual names
8422 return names.split(";")
8423
8424 def get_num_levels(self, predicate):
8425 """Retrieve number of levels used for predicate in PDR engine"""
8426 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8427
8428 def get_cover_delta(self, level, predicate):
8429 """Retrieve properties known about predicate for the level'th unfolding.
8430 -1 is treated as the limit (infinity)
8431 """
8432 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8433 return _to_expr_ref(r, self.ctx)
8434
8435 def add_cover(self, level, predicate, property):
8436 """Add property to predicate for the level'th unfolding.
8437 -1 is treated as infinity (infinity)
8438 """
8439 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8440
8441 def register_relation(self, *relations):
8442 """Register relation as recursive"""
8443 relations = _get_args(relations)
8444 for f in relations:
8445 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8446
8447 def set_predicate_representation(self, f, *representations):
8448 """Control how relation is represented"""
8449 representations = _get_args(representations)
8450 representations = [to_symbol(s) for s in representations]
8451 sz = len(representations)
8452 args = (Symbol * sz)()
8453 for i in range(sz):
8454 args[i] = representations[i]
8455 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8456
8457 def parse_string(self, s):
8458 """Parse rules and queries from a string"""
8459 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8460
8461 def parse_file(self, f):
8462 """Parse rules and queries from a file"""
8463 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8464
8465 def get_rules(self):
8466 """retrieve rules that have been added to fixedpoint context"""
8467 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8468
8469 def get_assertions(self):
8470 """retrieve assertions that have been added to fixedpoint context"""
8471 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8472
8473 def __repr__(self):
8474 """Return a formatted string with all added rules and constraints."""
8475 return self.sexpr()
8476
8477 def sexpr(self):
8478 """Return a formatted string (in Lisp-like format) with all added constraints.
8479 We say the string is in s-expression format.
8480 """
8481 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8482
8483 def to_string(self, queries):
8484 """Return a formatted string (in Lisp-like format) with all added constraints.
8485 We say the string is in s-expression format.
8486 Include also queries.
8487 """
8488 args, len = _to_ast_array(queries)
8489 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8490
8491 def statistics(self):
8492 """Return statistics for the last `query()`.
8493 """
8494 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8495
8496 def reason_unknown(self):
8497 """Return a string describing why the last `query()` returned `unknown`.
8498 """
8499 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8500
8501 def declare_var(self, *vars):
8502 """Add variable or several variables.
8503 The added variable or variables will be bound in the rules
8504 and queries
8505 """
8506 vars = _get_args(vars)
8507 for v in vars:
8508 self.vars += [v]
8509
8510 def abstract(self, fml, is_forall=True):
8511 if self.vars == []:
8512 return fml
8513 if is_forall:
8514 return ForAll(self.vars, fml)
8515 else:
8516 return Exists(self.vars, fml)
8517
8518
8519#########################################
8520#
8521# Finite domains
8522#
8523#########################################
8524
8525class FiniteDomainSortRef(SortRef):
8526 """Finite domain sort."""
8527
8528 def size(self):
8529 """Return the size of the finite domain sort"""
8530 r = (ctypes.c_ulonglong * 1)()
8531 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8532 return r[0]
8533 else:
8534 raise Z3Exception("Failed to retrieve finite domain sort size")
8535
8536
8537def FiniteDomainSort(name, sz, ctx=None):
8538 """Create a named finite domain sort of a given size sz"""
8539 if not isinstance(name, Symbol):
8540 name = to_symbol(name)
8541 ctx = _get_ctx(ctx)
8542 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8543
8544
8545def is_finite_domain_sort(s):
8546 """Return True if `s` is a Z3 finite-domain sort.
8547
8548 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8549 True
8550 >>> is_finite_domain_sort(IntSort())
8551 False
8552 """
8553 return isinstance(s, FiniteDomainSortRef)
8554
8555
8556class FiniteDomainRef(ExprRef):
8557 """Finite-domain expressions."""
8558
8559 def sort(self):
8560 """Return the sort of the finite-domain expression `self`."""
8561 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8562
8563 def as_string(self):
8564 """Return a Z3 floating point expression as a Python string."""
8565 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8566
8567
8568def is_finite_domain(a):
8569 """Return `True` if `a` is a Z3 finite-domain expression.
8570
8571 >>> s = FiniteDomainSort('S', 100)
8572 >>> b = Const('b', s)
8573 >>> is_finite_domain(b)
8574 True
8575 >>> is_finite_domain(Int('x'))
8576 False
8577 """
8578 return isinstance(a, FiniteDomainRef)
8579
8580
8581class FiniteDomainNumRef(FiniteDomainRef):
8582 """Integer values."""
8583
8584 def as_long(self):
8585 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8586
8587 >>> s = FiniteDomainSort('S', 100)
8588 >>> v = FiniteDomainVal(3, s)
8589 >>> v
8590 3
8591 >>> v.as_long() + 1
8592 4
8593 """
8594 return int(self.as_string())
8595
8596 def as_string(self):
8597 """Return a Z3 finite-domain numeral as a Python string.
8598
8599 >>> s = FiniteDomainSort('S', 100)
8600 >>> v = FiniteDomainVal(42, s)
8601 >>> v.as_string()
8602 '42'
8603 """
8604 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8605
8606
8607def FiniteDomainVal(val, sort, ctx=None):
8608 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8609
8610 >>> s = FiniteDomainSort('S', 256)
8611 >>> FiniteDomainVal(255, s)
8612 255
8613 >>> FiniteDomainVal('100', s)
8614 100
8615 """
8616 if z3_debug():
8617 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8618 ctx = sort.ctx
8619 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8620
8621
8622def is_finite_domain_value(a):
8623 """Return `True` if `a` is a Z3 finite-domain value.
8624
8625 >>> s = FiniteDomainSort('S', 100)
8626 >>> b = Const('b', s)
8627 >>> is_finite_domain_value(b)
8628 False
8629 >>> b = FiniteDomainVal(10, s)
8630 >>> b
8631 10
8632 >>> is_finite_domain_value(b)
8633 True
8634 """
8635 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8636
8637
8638#########################################
8639#
8640# Optimize
8641#
8642#########################################
8643
8644class OptimizeObjective:
8645 def __init__(self, opt, value, is_max):
8646 self._opt = opt
8647 self._value = value
8648 self._is_max = is_max
8649
8650 def lower(self):
8651 opt = self._opt
8652 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8653
8654 def upper(self):
8655 opt = self._opt
8656 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8657
8658 def lower_values(self):
8659 opt = self._opt
8660 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8661
8662 def upper_values(self):
8663 opt = self._opt
8664 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8665
8666 def value(self):
8667 if self._is_max:
8668 return self.upper()
8669 else:
8670 return self.lower()
8671
8672 def __str__(self):
8673 return "%s:%s" % (self._value, self._is_max)
8674
8675
8676_on_models = {}
8677
8678
8679def _global_on_model(ctx):
8680 (fn, mdl) = _on_models[ctx]
8681 fn(mdl)
8682
8683
8684_on_model_eh = on_model_eh_type(_global_on_model)
8685
8686
8687class Optimize(Z3PPObject):
8688 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8689
8690 def __init__(self, optimize=None, ctx=None):
8691 self.ctx = _get_ctx(ctx)
8692 if optimize is None:
8693 self.optimize = Z3_mk_optimize(self.ctx.ref())
8694 else:
8695 self.optimize = optimize
8696 self._on_models_id = None
8697 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8698
8699 def __copy__(self):
8700 return self.translate(self.ctx)
8701
8702 def __deepcopy__(self, memo={}):
8703 return self.translate(self.ctx)
8704
8705 def __del__(self):
8706 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8707 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8708 if self._on_models_id is not None:
8709 del _on_models[self._on_models_id]
8710
8711 def __enter__(self):
8712 self.push()
8713 return self
8714
8715 def __exit__(self, *exc_info):
8716 self.pop()
8717
8718 def set(self, *args, **keys):
8719 """Set a configuration option.
8720 The method `help()` return a string containing all available options.
8721 """
8722 p = args2params(args, keys, self.ctx)
8723 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8724
8725 def help(self):
8726 """Display a string describing all available options."""
8727 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8728
8729 def param_descrs(self):
8730 """Return the parameter description set."""
8731 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8732
8733 def assert_exprs(self, *args):
8734 """Assert constraints as background axioms for the optimize solver."""
8735 args = _get_args(args)
8736 s = BoolSort(self.ctx)
8737 for arg in args:
8738 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8739 for f in arg:
8740 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8741 else:
8742 arg = s.cast(arg)
8743 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8744
8745 def add(self, *args):
8746 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8747 self.assert_exprs(*args)
8748
8749 def __iadd__(self, fml):
8750 self.add(fml)
8751 return self
8752
8753 def assert_and_track(self, a, p):
8754 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8755
8756 If `p` is a string, it will be automatically converted into a Boolean constant.
8757
8758 >>> x = Int('x')
8759 >>> p3 = Bool('p3')
8760 >>> s = Optimize()
8761 >>> s.assert_and_track(x > 0, 'p1')
8762 >>> s.assert_and_track(x != 1, 'p2')
8763 >>> s.assert_and_track(x < 0, p3)
8764 >>> print(s.check())
8765 unsat
8766 >>> c = s.unsat_core()
8767 >>> len(c)
8768 2
8769 >>> Bool('p1') in c
8770 True
8771 >>> Bool('p2') in c
8772 False
8773 >>> p3 in c
8774 True
8775 """
8776 if isinstance(p, str):
8777 p = Bool(p, self.ctx)
8778 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8779 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8780 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8781
8782 def add_soft(self, arg, weight="1", id=None):
8783 """Add soft constraint with optional weight and optional identifier.
8784 If no weight is supplied, then the penalty for violating the soft constraint
8785 is 1.
8786 Soft constraints are grouped by identifiers. Soft constraints that are
8787 added without identifiers are grouped by default.
8788 """
8789 if _is_int(weight):
8790 weight = "%d" % weight
8791 elif isinstance(weight, float):
8792 weight = "%f" % weight
8793 if not isinstance(weight, str):
8794 raise Z3Exception("weight should be a string or an integer")
8795 if id is None:
8796 id = ""
8797 id = to_symbol(id, self.ctx)
8798
8799 def asoft(a):
8800 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8801 return OptimizeObjective(self, v, False)
8802 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8803 return [asoft(a) for a in arg]
8804 return asoft(arg)
8805
8806 def set_initial_value(self, var, value):
8807 """initialize the solver's state by setting the initial value of var to value
8808 """
8809 s = var.sort()
8810 value = s.cast(value)
8811 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8812
8813 def maximize(self, arg):
8814 """Add objective function to maximize."""
8815 return OptimizeObjective(
8816 self,
8817 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8818 is_max=True,
8819 )
8820
8821 def minimize(self, arg):
8822 """Add objective function to minimize."""
8823 return OptimizeObjective(
8824 self,
8825 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8826 is_max=False,
8827 )
8828
8829 def push(self):
8830 """create a backtracking point for added rules, facts and assertions"""
8831 Z3_optimize_push(self.ctx.ref(), self.optimize)
8832
8833 def pop(self):
8834 """restore to previously created backtracking point"""
8835 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8836
8837 def check(self, *assumptions):
8838 """Check consistency and produce optimal values."""
8839 assumptions = _get_args(assumptions)
8840 num = len(assumptions)
8841 _assumptions = (Ast * num)()
8842 for i in range(num):
8843 _assumptions[i] = assumptions[i].as_ast()
8844 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8845
8846 def reason_unknown(self):
8847 """Return a string that describes why the last `check()` returned `unknown`."""
8848 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8849
8850 def model(self):
8851 """Return a model for the last check()."""
8852 try:
8853 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8854 except Z3Exception:
8855 raise Z3Exception("model is not available")
8856
8857 def unsat_core(self):
8858 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8859
8860 def lower(self, obj):
8861 if not isinstance(obj, OptimizeObjective):
8862 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8863 return obj.lower()
8864
8865 def upper(self, obj):
8866 if not isinstance(obj, OptimizeObjective):
8867 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8868 return obj.upper()
8869
8870 def lower_values(self, obj):
8871 if not isinstance(obj, OptimizeObjective):
8872 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8873 return obj.lower_values()
8874
8875 def upper_values(self, obj):
8876 if not isinstance(obj, OptimizeObjective):
8877 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8878 return obj.upper_values()
8879
8880 def from_file(self, filename):
8881 """Parse assertions and objectives from a file"""
8882 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8883
8884 def from_string(self, s):
8885 """Parse assertions and objectives from a string"""
8886 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8887
8888 def assertions(self):
8889 """Return an AST vector containing all added constraints."""
8890 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8891
8892 def objectives(self):
8893 """returns set of objective functions"""
8894 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8895
8896 def __repr__(self):
8897 """Return a formatted string with all added rules and constraints."""
8898 return self.sexpr()
8899
8900 def sexpr(self):
8901 """Return a formatted string (in Lisp-like format) with all added constraints.
8902 We say the string is in s-expression format.
8903 """
8904 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8905
8906 def statistics(self):
8907 """Return statistics for the last check`.
8908 """
8909 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8910
8911 def translate(self, target):
8912 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8913
8914 >>> c1 = Context()
8915 >>> c2 = Context()
8916 >>> o1 = Optimize(ctx=c1)
8917 >>> o2 = o1.translate(c2)
8918 """
8919 if z3_debug():
8920 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8921 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8922 return Optimize(opt, target)
8923
8924 def set_on_model(self, on_model):
8925 """Register a callback that is invoked with every incremental improvement to
8926 objective values. The callback takes a model as argument.
8927 The life-time of the model is limited to the callback so the
8928 model has to be (deep) copied if it is to be used after the callback
8929 """
8930 id = len(_on_models) + 41
8931 mdl = Model(self.ctx)
8932 _on_models[id] = (on_model, mdl)
8933 self._on_models_id = id
8934 Z3_optimize_register_model_eh(
8935 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8936 )
8937
8938
8939#########################################
8940#
8941# ApplyResult
8942#
8943#########################################
8944class ApplyResult(Z3PPObject):
8945 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8946 It also contains model and proof converters.
8947 """
8948
8949 def __init__(self, result, ctx):
8950 self.result = result
8951 self.ctx = ctx
8952 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8953
8954 def __deepcopy__(self, memo={}):
8955 return ApplyResult(self.result, self.ctx)
8956
8957 def __del__(self):
8958 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8959 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8960
8961 def __len__(self):
8962 """Return the number of subgoals in `self`.
8963
8964 >>> a, b = Ints('a b')
8965 >>> g = Goal()
8966 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8967 >>> t = Tactic('split-clause')
8968 >>> r = t(g)
8969 >>> len(r)
8970 2
8971 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8972 >>> len(t(g))
8973 4
8974 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8975 >>> len(t(g))
8976 1
8977 """
8978 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8979
8980 def __getitem__(self, idx):
8981 """Return one of the subgoals stored in ApplyResult object `self`.
8982
8983 >>> a, b = Ints('a b')
8984 >>> g = Goal()
8985 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8986 >>> t = Tactic('split-clause')
8987 >>> r = t(g)
8988 >>> r[0]
8989 [a == 0, Or(b == 0, b == 1), a > b]
8990 >>> r[1]
8991 [a == 1, Or(b == 0, b == 1), a > b]
8992 """
8993 if idx < 0:
8994 idx += len(self)
8995 if idx < 0 or idx >= len(self):
8996 raise IndexError
8997 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8998
8999 def __repr__(self):
9000 return obj_to_string(self)
9001
9002 def sexpr(self):
9003 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
9004 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
9005
9006 def as_expr(self):
9007 """Return a Z3 expression consisting of all subgoals.
9008
9009 >>> x = Int('x')
9010 >>> g = Goal()
9011 >>> g.add(x > 1)
9012 >>> g.add(Or(x == 2, x == 3))
9013 >>> r = Tactic('simplify')(g)
9014 >>> r
9015 [[Not(x <= 1), Or(x == 2, x == 3)]]
9016 >>> r.as_expr()
9017 And(Not(x <= 1), Or(x == 2, x == 3))
9018 >>> r = Tactic('split-clause')(g)
9019 >>> r
9020 [[x > 1, x == 2], [x > 1, x == 3]]
9021 >>> r.as_expr()
9022 Or(And(x > 1, x == 2), And(x > 1, x == 3))
9023 """
9024 sz = len(self)
9025 if sz == 0:
9026 return BoolVal(False, self.ctx)
9027 elif sz == 1:
9028 return self[0].as_expr()
9029 else:
9030 return Or([self[i].as_expr() for i in range(len(self))])
9031
9032#########################################
9033#
9034# Simplifiers
9035#
9036#########################################
9037
9038def num_simplifiers(ctx=None):
9039 """Return the number of simplifiers supported by the given context."""
9040 return Z3_get_num_simplifiers(_get_ctx(ctx).ref())
9041
9042
9043def simplifier_name(i, ctx=None):
9044 """Return the name of the i-th simplifier supported by the given context."""
9045 return Z3_get_simplifier_name(_get_ctx(ctx).ref(), i)
9046
9047
9048def simplifier_description(name, ctx=None):
9049 """Return the description of the simplifier identified by name."""
9050 return Z3_simplifier_get_descr(_get_ctx(ctx).ref(), name)
9051
9052
9053class Simplifier:
9054 """Simplifiers act as pre-processing utilities for solvers.
9055 Build a custom simplifier and add it to a solver"""
9056
9057 def __init__(self, simplifier, ctx=None):
9058 self.ctx = _get_ctx(ctx)
9059 self.simplifier = None
9060 if isinstance(simplifier, SimplifierObj):
9061 self.simplifier = simplifier
9062 elif isinstance(simplifier, list):
9063 simps = [Simplifier(s, ctx) for s in simplifier]
9064 self.simplifier = simps[0].simplifier
9065 for i in range(1, len(simps)):
9066 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
9067 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9068 return
9069 else:
9070 if z3_debug():
9071 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
9072 try:
9073 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
9074 except Z3Exception:
9075 raise Z3Exception("unknown simplifier '%s'" % simplifier)
9076 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9077
9078 def __deepcopy__(self, memo={}):
9079 return Simplifier(self.simplifier, self.ctx)
9080
9081 def __del__(self):
9082 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
9083 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
9084
9085 def using_params(self, *args, **keys):
9086 """Return a simplifier that uses the given configuration options"""
9087 p = args2params(args, keys, self.ctx)
9088 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
9089
9090 def add(self, solver):
9091 """Return a solver that applies the simplification pre-processing specified by the simplifier"""
9092 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
9093
9094 def help(self):
9095 """Display a string containing a description of the available options for the `self` simplifier."""
9096 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
9097
9098 def param_descrs(self):
9099 """Return the parameter description set."""
9100 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
9101
9102
9103#########################################
9104#
9105# Tactics
9106#
9107#########################################
9108
9109
9110class Tactic:
9111 """Tactics transform, solver and/or simplify sets of constraints (Goal).
9112 A Tactic can be converted into a Solver using the method solver().
9113
9114 Several combinators are available for creating new tactics using the built-in ones:
9115 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
9116 """
9117
9118 def __init__(self, tactic, ctx=None):
9119 self.ctx = _get_ctx(ctx)
9120 self.tactic = None
9121 if isinstance(tactic, TacticObj):
9122 self.tactic = tactic
9123 else:
9124 if z3_debug():
9125 _z3_assert(isinstance(tactic, str), "tactic name expected")
9126 try:
9127 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9128 except Z3Exception:
9129 raise Z3Exception("unknown tactic '%s'" % tactic)
9130 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9131
9132 def __deepcopy__(self, memo={}):
9133 return Tactic(self.tactic, self.ctx)
9134
9135 def __del__(self):
9136 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9137 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9138
9139 def solver(self, logFile=None):
9140 """Create a solver using the tactic `self`.
9141
9142 The solver supports the methods `push()` and `pop()`, but it
9143 will always solve each `check()` from scratch.
9144
9145 >>> t = Then('simplify', 'nlsat')
9146 >>> s = t.solver()
9147 >>> x = Real('x')
9148 >>> s.add(x**2 == 2, x > 0)
9149 >>> s.check()
9150 sat
9151 >>> s.model()
9152 [x = 1.4142135623?]
9153 """
9154 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9155
9156 def apply(self, goal, *arguments, **keywords):
9157 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9158
9159 >>> x, y = Ints('x y')
9160 >>> t = Tactic('solve-eqs')
9161 >>> t.apply(And(x == 0, y >= x + 1))
9162 [[y >= 1]]
9163 """
9164 if z3_debug():
9165 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9166 goal = _to_goal(goal)
9167 if len(arguments) > 0 or len(keywords) > 0:
9168 p = args2params(arguments, keywords, self.ctx)
9169 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9170 else:
9171 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9172
9173 def __call__(self, goal, *arguments, **keywords):
9174 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9175
9176 >>> x, y = Ints('x y')
9177 >>> t = Tactic('solve-eqs')
9178 >>> t(And(x == 0, y >= x + 1))
9179 [[y >= 1]]
9180 """
9181 return self.apply(goal, *arguments, **keywords)
9182
9183 def help(self):
9184 """Display a string containing a description of the available options for the `self` tactic."""
9185 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9186
9187 def param_descrs(self):
9188 """Return the parameter description set."""
9189 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9190
9191
9192def _to_goal(a):
9193 if isinstance(a, BoolRef):
9194 goal = Goal(ctx=a.ctx)
9195 goal.add(a)
9196 return goal
9197 else:
9198 return a
9199
9200
9201def _to_tactic(t, ctx=None):
9202 if isinstance(t, Tactic):
9203 return t
9204 else:
9205 return Tactic(t, ctx)
9206
9207
9208def _and_then(t1, t2, ctx=None):
9209 t1 = _to_tactic(t1, ctx)
9210 t2 = _to_tactic(t2, ctx)
9211 if z3_debug():
9212 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9213 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9214
9215
9216def _or_else(t1, t2, ctx=None):
9217 t1 = _to_tactic(t1, ctx)
9218 t2 = _to_tactic(t2, ctx)
9219 if z3_debug():
9220 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9221 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9222
9223
9224def AndThen(*ts, **ks):
9225 """Return a tactic that applies the tactics in `*ts` in sequence.
9226
9227 >>> x, y = Ints('x y')
9228 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9229 >>> t(And(x == 0, y > x + 1))
9230 [[Not(y <= 1)]]
9231 >>> t(And(x == 0, y > x + 1)).as_expr()
9232 Not(y <= 1)
9233 """
9234 if z3_debug():
9235 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9236 ctx = ks.get("ctx", None)
9237 num = len(ts)
9238 r = ts[0]
9239 for i in range(num - 1):
9240 r = _and_then(r, ts[i + 1], ctx)
9241 return r
9242
9243
9244def Then(*ts, **ks):
9245 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9246
9247 >>> x, y = Ints('x y')
9248 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9249 >>> t(And(x == 0, y > x + 1))
9250 [[Not(y <= 1)]]
9251 >>> t(And(x == 0, y > x + 1)).as_expr()
9252 Not(y <= 1)
9253 """
9254 return AndThen(*ts, **ks)
9255
9256
9257def OrElse(*ts, **ks):
9258 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9259
9260 >>> x = Int('x')
9261 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9262 >>> # Tactic split-clause fails if there is no clause in the given goal.
9263 >>> t(x == 0)
9264 [[x == 0]]
9265 >>> t(Or(x == 0, x == 1))
9266 [[x == 0], [x == 1]]
9267 """
9268 if z3_debug():
9269 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9270 ctx = ks.get("ctx", None)
9271 num = len(ts)
9272 r = ts[0]
9273 for i in range(num - 1):
9274 r = _or_else(r, ts[i + 1], ctx)
9275 return r
9276
9277
9278def ParOr(*ts, **ks):
9279 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9280
9281 >>> x = Int('x')
9282 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9283 >>> t(x + 1 == 2)
9284 [[x == 1]]
9285 """
9286 if z3_debug():
9287 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9288 ctx = _get_ctx(ks.get("ctx", None))
9289 ts = [_to_tactic(t, ctx) for t in ts]
9290 sz = len(ts)
9291 _args = (TacticObj * sz)()
9292 for i in range(sz):
9293 _args[i] = ts[i].tactic
9294 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9295
9296
9297def ParThen(t1, t2, ctx=None):
9298 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9299 The subgoals are processed in parallel.
9300
9301 >>> x, y = Ints('x y')
9302 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9303 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9304 [[x == 1, y == 2], [x == 2, y == 3]]
9305 """
9306 t1 = _to_tactic(t1, ctx)
9307 t2 = _to_tactic(t2, ctx)
9308 if z3_debug():
9309 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9310 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9311
9312
9313def ParAndThen(t1, t2, ctx=None):
9314 """Alias for ParThen(t1, t2, ctx)."""
9315 return ParThen(t1, t2, ctx)
9316
9317
9318def With(t, *args, **keys):
9319 """Return a tactic that applies tactic `t` using the given configuration options.
9320
9321 >>> x, y = Ints('x y')
9322 >>> t = With(Tactic('simplify'), som=True)
9323 >>> t((x + 1)*(y + 2) == 0)
9324 [[2*x + y + x*y == -2]]
9325 """
9326 ctx = keys.pop("ctx", None)
9327 t = _to_tactic(t, ctx)
9328 p = args2params(args, keys, t.ctx)
9329 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9330
9331
9332def WithParams(t, p):
9333 """Return a tactic that applies tactic `t` using the given configuration options.
9334
9335 >>> x, y = Ints('x y')
9336 >>> p = ParamsRef()
9337 >>> p.set("som", True)
9338 >>> t = WithParams(Tactic('simplify'), p)
9339 >>> t((x + 1)*(y + 2) == 0)
9340 [[2*x + y + x*y == -2]]
9341 """
9342 t = _to_tactic(t, None)
9343 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9344
9345
9346def Repeat(t, max=4294967295, ctx=None):
9347 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9348 or the maximum number of iterations `max` is reached.
9349
9350 >>> x, y = Ints('x y')
9351 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9352 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9353 >>> r = t(c)
9354 >>> for subgoal in r: print(subgoal)
9355 [x == 0, y == 0, x > y]
9356 [x == 0, y == 1, x > y]
9357 [x == 1, y == 0, x > y]
9358 [x == 1, y == 1, x > y]
9359 >>> t = Then(t, Tactic('propagate-values'))
9360 >>> t(c)
9361 [[x == 1, y == 0]]
9362 """
9363 t = _to_tactic(t, ctx)
9364 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9365
9366
9367def TryFor(t, ms, ctx=None):
9368 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9369
9370 If `t` does not terminate in `ms` milliseconds, then it fails.
9371 """
9372 t = _to_tactic(t, ctx)
9373 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9374
9375
9376def tactics(ctx=None):
9377 """Return a list of all available tactics in Z3.
9378
9379 >>> l = tactics()
9380 >>> l.count('simplify') == 1
9381 True
9382 """
9383 ctx = _get_ctx(ctx)
9384 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9385
9386
9387def tactic_description(name, ctx=None):
9388 """Return a short description for the tactic named `name`.
9389
9390 >>> d = tactic_description('simplify')
9391 """
9392 ctx = _get_ctx(ctx)
9393 return Z3_tactic_get_descr(ctx.ref(), name)
9394
9395
9396def describe_tactics():
9397 """Display a (tabular) description of all available tactics in Z3."""
9398 if in_html_mode():
9399 even = True
9400 print('<table border="1" cellpadding="2" cellspacing="0">')
9401 for t in tactics():
9402 if even:
9403 print('<tr style="background-color:#CFCFCF">')
9404 even = False
9405 else:
9406 print("<tr>")
9407 even = True
9408 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9409 print("</table>")
9410 else:
9411 for t in tactics():
9412 print("%s : %s" % (t, tactic_description(t)))
9413
9414
9415class Probe:
9416 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9417 to decide which solver and/or preprocessing step will be used.
9418 """
9419
9420 def __init__(self, probe, ctx=None):
9421 self.ctx = _get_ctx(ctx)
9422 self.probe = None
9423 if isinstance(probe, ProbeObj):
9424 self.probe = probe
9425 elif isinstance(probe, float):
9426 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9427 elif _is_int(probe):
9428 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9429 elif isinstance(probe, bool):
9430 if probe:
9431 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9432 else:
9433 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9434 else:
9435 if z3_debug():
9436 _z3_assert(isinstance(probe, str), "probe name expected")
9437 try:
9438 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9439 except Z3Exception:
9440 raise Z3Exception("unknown probe '%s'" % probe)
9441 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9442
9443 def __deepcopy__(self, memo={}):
9444 return Probe(self.probe, self.ctx)
9445
9446 def __del__(self):
9447 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9448 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9449
9450 def __lt__(self, other):
9451 """Return a probe that evaluates to "true" when the value returned by `self`
9452 is less than the value returned by `other`.
9453
9454 >>> p = Probe('size') < 10
9455 >>> x = Int('x')
9456 >>> g = Goal()
9457 >>> g.add(x > 0)
9458 >>> g.add(x < 10)
9459 >>> p(g)
9460 1.0
9461 """
9462 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9463
9464 def __gt__(self, other):
9465 """Return a probe that evaluates to "true" when the value returned by `self`
9466 is greater than the value returned by `other`.
9467
9468 >>> p = Probe('size') > 10
9469 >>> x = Int('x')
9470 >>> g = Goal()
9471 >>> g.add(x > 0)
9472 >>> g.add(x < 10)
9473 >>> p(g)
9474 0.0
9475 """
9476 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9477
9478 def __le__(self, other):
9479 """Return a probe that evaluates to "true" when the value returned by `self`
9480 is less than or equal to the value returned by `other`.
9481
9482 >>> p = Probe('size') <= 2
9483 >>> x = Int('x')
9484 >>> g = Goal()
9485 >>> g.add(x > 0)
9486 >>> g.add(x < 10)
9487 >>> p(g)
9488 1.0
9489 """
9490 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9491
9492 def __ge__(self, other):
9493 """Return a probe that evaluates to "true" when the value returned by `self`
9494 is greater than or equal to the value returned by `other`.
9495
9496 >>> p = Probe('size') >= 2
9497 >>> x = Int('x')
9498 >>> g = Goal()
9499 >>> g.add(x > 0)
9500 >>> g.add(x < 10)
9501 >>> p(g)
9502 1.0
9503 """
9504 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9505
9506 def __eq__(self, other):
9507 """Return a probe that evaluates to "true" when the value returned by `self`
9508 is equal to the value returned by `other`.
9509
9510 >>> p = Probe('size') == 2
9511 >>> x = Int('x')
9512 >>> g = Goal()
9513 >>> g.add(x > 0)
9514 >>> g.add(x < 10)
9515 >>> p(g)
9516 1.0
9517 """
9518 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9519
9520 def __ne__(self, other):
9521 """Return a probe that evaluates to "true" when the value returned by `self`
9522 is not equal to the value returned by `other`.
9523
9524 >>> p = Probe('size') != 2
9525 >>> x = Int('x')
9526 >>> g = Goal()
9527 >>> g.add(x > 0)
9528 >>> g.add(x < 10)
9529 >>> p(g)
9530 0.0
9531 """
9532 p = self.__eq__(other)
9533 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9534
9535 def __call__(self, goal):
9536 """Evaluate the probe `self` in the given goal.
9537
9538 >>> p = Probe('size')
9539 >>> x = Int('x')
9540 >>> g = Goal()
9541 >>> g.add(x > 0)
9542 >>> g.add(x < 10)
9543 >>> p(g)
9544 2.0
9545 >>> g.add(x < 20)
9546 >>> p(g)
9547 3.0
9548 >>> p = Probe('num-consts')
9549 >>> p(g)
9550 1.0
9551 >>> p = Probe('is-propositional')
9552 >>> p(g)
9553 0.0
9554 >>> p = Probe('is-qflia')
9555 >>> p(g)
9556 1.0
9557 """
9558 if z3_debug():
9559 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9560 goal = _to_goal(goal)
9561 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9562
9563
9564def is_probe(p):
9565 """Return `True` if `p` is a Z3 probe.
9566
9567 >>> is_probe(Int('x'))
9568 False
9569 >>> is_probe(Probe('memory'))
9570 True
9571 """
9572 return isinstance(p, Probe)
9573
9574
9575def _to_probe(p, ctx=None):
9576 if is_probe(p):
9577 return p
9578 else:
9579 return Probe(p, ctx)
9580
9581
9582def probes(ctx=None):
9583 """Return a list of all available probes in Z3.
9584
9585 >>> l = probes()
9586 >>> l.count('memory') == 1
9587 True
9588 """
9589 ctx = _get_ctx(ctx)
9590 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9591
9592
9593def probe_description(name, ctx=None):
9594 """Return a short description for the probe named `name`.
9595
9596 >>> d = probe_description('memory')
9597 """
9598 ctx = _get_ctx(ctx)
9599 return Z3_probe_get_descr(ctx.ref(), name)
9600
9601
9602def describe_probes():
9603 """Display a (tabular) description of all available probes in Z3."""
9604 if in_html_mode():
9605 even = True
9606 print('<table border="1" cellpadding="2" cellspacing="0">')
9607 for p in probes():
9608 if even:
9609 print('<tr style="background-color:#CFCFCF">')
9610 even = False
9611 else:
9612 print("<tr>")
9613 even = True
9614 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9615 print("</table>")
9616 else:
9617 for p in probes():
9618 print("%s : %s" % (p, probe_description(p)))
9619
9620
9621def _probe_nary(f, args, ctx):
9622 if z3_debug():
9623 _z3_assert(len(args) > 0, "At least one argument expected")
9624 num = len(args)
9625 r = _to_probe(args[0], ctx)
9626 for i in range(num - 1):
9627 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9628 return r
9629
9630
9631def _probe_and(args, ctx):
9632 return _probe_nary(Z3_probe_and, args, ctx)
9633
9634
9635def _probe_or(args, ctx):
9636 return _probe_nary(Z3_probe_or, args, ctx)
9637
9638
9639def FailIf(p, ctx=None):
9640 """Return a tactic that fails if the probe `p` evaluates to true.
9641 Otherwise, it returns the input goal unmodified.
9642
9643 In the following example, the tactic applies 'simplify' if and only if there are
9644 more than 2 constraints in the goal.
9645
9646 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9647 >>> x, y = Ints('x y')
9648 >>> g = Goal()
9649 >>> g.add(x > 0)
9650 >>> g.add(y > 0)
9651 >>> t(g)
9652 [[x > 0, y > 0]]
9653 >>> g.add(x == y + 1)
9654 >>> t(g)
9655 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9656 """
9657 p = _to_probe(p, ctx)
9658 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9659
9660
9661def When(p, t, ctx=None):
9662 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9663 Otherwise, it returns the input goal unmodified.
9664
9665 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9666 >>> x, y = Ints('x y')
9667 >>> g = Goal()
9668 >>> g.add(x > 0)
9669 >>> g.add(y > 0)
9670 >>> t(g)
9671 [[x > 0, y > 0]]
9672 >>> g.add(x == y + 1)
9673 >>> t(g)
9674 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9675 """
9676 p = _to_probe(p, ctx)
9677 t = _to_tactic(t, ctx)
9678 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9679
9680
9681def Cond(p, t1, t2, ctx=None):
9682 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9683
9684 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9685 """
9686 p = _to_probe(p, ctx)
9687 t1 = _to_tactic(t1, ctx)
9688 t2 = _to_tactic(t2, ctx)
9689 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9690
9691#########################################
9692#
9693# Utils
9694#
9695#########################################
9696
9697
9698def simplify(a, *arguments, **keywords):
9699 """Simplify the expression `a` using the given options.
9700
9701 This function has many options. Use `help_simplify` to obtain the complete list.
9702
9703 >>> x = Int('x')
9704 >>> y = Int('y')
9705 >>> simplify(x + 1 + y + x + 1)
9706 2 + 2*x + y
9707 >>> simplify((x + 1)*(y + 1), som=True)
9708 1 + x + y + x*y
9709 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9710 And(Not(x == y), Not(x == 1), Not(y == 1))
9711 >>> simplify(And(x == 0, y == 1), elim_and=True)
9712 Not(Or(Not(x == 0), Not(y == 1)))
9713 """
9714 if z3_debug():
9715 _z3_assert(is_expr(a), "Z3 expression expected")
9716 if len(arguments) > 0 or len(keywords) > 0:
9717 p = args2params(arguments, keywords, a.ctx)
9718 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9719 else:
9720 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9721
9722
9723def help_simplify():
9724 """Return a string describing all options available for Z3 `simplify` procedure."""
9725 print(Z3_simplify_get_help(main_ctx().ref()))
9726
9727
9728def simplify_param_descrs():
9729 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9730 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9731
9732
9733def substitute(t, *m):
9734 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9735 Every occurrence in t of from is replaced with to.
9736
9737 >>> x = Int('x')
9738 >>> y = Int('y')
9739 >>> substitute(x + 1, (x, y + 1))
9740 y + 1 + 1
9741 >>> f = Function('f', IntSort(), IntSort())
9742 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9743 1 + 1
9744 """
9745 if isinstance(m, tuple):
9746 m1 = _get_args(m)
9747 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9748 m = m1
9749 if z3_debug():
9750 _z3_assert(is_expr(t), "Z3 expression expected")
9751 _z3_assert(
9752 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9753 "Z3 invalid substitution, expression pairs expected.")
9754 _z3_assert(
9755 all([p[0].sort().eq(p[1].sort()) for p in m]),
9756 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9757 num = len(m)
9758 _from = (Ast * num)()
9759 _to = (Ast * num)()
9760 for i in range(num):
9761 _from[i] = m[i][0].as_ast()
9762 _to[i] = m[i][1].as_ast()
9763 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9764
9765
9766def substitute_vars(t, *m):
9767 """Substitute the free variables in t with the expression in m.
9768
9769 >>> v0 = Var(0, IntSort())
9770 >>> v1 = Var(1, IntSort())
9771 >>> x = Int('x')
9772 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9773 >>> # replace v0 with x+1 and v1 with x
9774 >>> substitute_vars(f(v0, v1), x + 1, x)
9775 f(x + 1, x)
9776 """
9777 if z3_debug():
9778 _z3_assert(is_expr(t), "Z3 expression expected")
9779 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9780 num = len(m)
9781 _to = (Ast * num)()
9782 for i in range(num):
9783 _to[i] = m[i].as_ast()
9784 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9785
9786def substitute_funs(t, *m):
9787 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9788 Every occurrence in to of the function from is replaced with the expression to.
9789 The expression to can have free variables, that refer to the arguments of from.
9790 For examples, see
9791 """
9792 if isinstance(m, tuple):
9793 m1 = _get_args(m)
9794 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9795 m = m1
9796 if z3_debug():
9797 _z3_assert(is_expr(t), "Z3 expression expected")
9798 _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.")
9799 num = len(m)
9800 _from = (FuncDecl * num)()
9801 _to = (Ast * num)()
9802 for i in range(num):
9803 _from[i] = m[i][0].as_func_decl()
9804 _to[i] = m[i][1].as_ast()
9805 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9806
9807
9808def Sum(*args):
9809 """Create the sum of the Z3 expressions.
9810
9811 >>> a, b, c = Ints('a b c')
9812 >>> Sum(a, b, c)
9813 a + b + c
9814 >>> Sum([a, b, c])
9815 a + b + c
9816 >>> A = IntVector('a', 5)
9817 >>> Sum(A)
9818 a__0 + a__1 + a__2 + a__3 + a__4
9819 """
9820 args = _get_args(args)
9821 if len(args) == 0:
9822 return 0
9823 ctx = _ctx_from_ast_arg_list(args)
9824 if ctx is None:
9825 return _reduce(lambda a, b: a + b, args, 0)
9826 args = _coerce_expr_list(args, ctx)
9827 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9828 return _reduce(lambda a, b: a + b, args, 0)
9829 else:
9830 _args, sz = _to_ast_array(args)
9831 return _to_expr_ref(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9832
9833
9834def Product(*args):
9835 """Create the product of the Z3 expressions.
9836
9837 >>> a, b, c = Ints('a b c')
9838 >>> Product(a, b, c)
9839 a*b*c
9840 >>> Product([a, b, c])
9841 a*b*c
9842 >>> A = IntVector('a', 5)
9843 >>> Product(A)
9844 a__0*a__1*a__2*a__3*a__4
9845 """
9846 args = _get_args(args)
9847 if len(args) == 0:
9848 return 1
9849 ctx = _ctx_from_ast_arg_list(args)
9850 if ctx is None:
9851 return _reduce(lambda a, b: a * b, args, 1)
9852 args = _coerce_expr_list(args, ctx)
9853 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9854 return _reduce(lambda a, b: a * b, args, 1)
9855 else:
9856 _args, sz = _to_ast_array(args)
9857 return _to_expr_ref(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9858
9859def Abs(arg):
9860 """Create the absolute value of an arithmetic expression"""
9861 return If(arg > 0, arg, -arg)
9862
9863
9864def AtMost(*args):
9865 """Create an at-most Pseudo-Boolean k constraint.
9866
9867 >>> a, b, c = Bools('a b c')
9868 >>> f = AtMost(a, b, c, 2)
9869 """
9870 args = _get_args(args)
9871 if z3_debug():
9872 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9873 ctx = _ctx_from_ast_arg_list(args)
9874 if z3_debug():
9875 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9876 args1 = _coerce_expr_list(args[:-1], ctx)
9877 k = args[-1]
9878 _args, sz = _to_ast_array(args1)
9879 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9880
9881
9882def AtLeast(*args):
9883 """Create an at-least Pseudo-Boolean k constraint.
9884
9885 >>> a, b, c = Bools('a b c')
9886 >>> f = AtLeast(a, b, c, 2)
9887 """
9888 args = _get_args(args)
9889 if z3_debug():
9890 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9891 ctx = _ctx_from_ast_arg_list(args)
9892 if z3_debug():
9893 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9894 args1 = _coerce_expr_list(args[:-1], ctx)
9895 k = args[-1]
9896 _args, sz = _to_ast_array(args1)
9897 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9898
9899
9900def _reorder_pb_arg(arg):
9901 a, b = arg
9902 if not _is_int(b) and _is_int(a):
9903 return b, a
9904 return arg
9905
9906
9907def _pb_args_coeffs(args, default_ctx=None):
9908 args = _get_args_ast_list(args)
9909 if len(args) == 0:
9910 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9911 args = [_reorder_pb_arg(arg) for arg in args]
9912 args, coeffs = zip(*args)
9913 if z3_debug():
9914 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9915 ctx = _ctx_from_ast_arg_list(args)
9916 if z3_debug():
9917 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9918 args = _coerce_expr_list(args, ctx)
9919 _args, sz = _to_ast_array(args)
9920 _coeffs = (ctypes.c_int * len(coeffs))()
9921 for i in range(len(coeffs)):
9922 _z3_check_cint_overflow(coeffs[i], "coefficient")
9923 _coeffs[i] = coeffs[i]
9924 return ctx, sz, _args, _coeffs, args
9925
9926
9927def PbLe(args, k):
9928 """Create a Pseudo-Boolean inequality k constraint.
9929
9930 >>> a, b, c = Bools('a b c')
9931 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9932 """
9933 _z3_check_cint_overflow(k, "k")
9934 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9935 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9936
9937
9938def PbGe(args, k):
9939 """Create a Pseudo-Boolean inequality k constraint.
9940
9941 >>> a, b, c = Bools('a b c')
9942 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9943 """
9944 _z3_check_cint_overflow(k, "k")
9945 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9946 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9947
9948
9949def PbEq(args, k, ctx=None):
9950 """Create a Pseudo-Boolean equality k constraint.
9951
9952 >>> a, b, c = Bools('a b c')
9953 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9954 """
9955 _z3_check_cint_overflow(k, "k")
9956 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9957 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9958
9959
9960def solve(*args, **keywords):
9961 """Solve the constraints `*args`.
9962
9963 This is a simple function for creating demonstrations. It creates a solver,
9964 configure it using the options in `keywords`, adds the constraints
9965 in `args`, and invokes check.
9966
9967 >>> a = Int('a')
9968 >>> solve(a > 0, a < 2)
9969 [a = 1]
9970 """
9971 show = keywords.pop("show", False)
9972 s = Solver()
9973 s.set(**keywords)
9974 s.add(*args)
9975 if show:
9976 print(s)
9977 r = s.check()
9978 if r == unsat:
9979 print("no solution")
9980 elif r == unknown:
9981 print("failed to solve")
9982 try:
9983 print(s.model())
9984 except Z3Exception:
9985 return
9986 else:
9987 print(s.model())
9988
9989
9990def solve_using(s, *args, **keywords):
9991 """Solve the constraints `*args` using solver `s`.
9992
9993 This is a simple function for creating demonstrations. It is similar to `solve`,
9994 but it uses the given solver `s`.
9995 It configures solver `s` using the options in `keywords`, adds the constraints
9996 in `args`, and invokes check.
9997 """
9998 show = keywords.pop("show", False)
9999 if z3_debug():
10000 _z3_assert(isinstance(s, Solver), "Solver object expected")
10001 s.set(**keywords)
10002 s.add(*args)
10003 if show:
10004 print("Problem:")
10005 print(s)
10006 r = s.check()
10007 if r == unsat:
10008 print("no solution")
10009 elif r == unknown:
10010 print("failed to solve")
10011 try:
10012 print(s.model())
10013 except Z3Exception:
10014 return
10015 else:
10016 if show:
10017 print("Solution:")
10018 print(s.model())
10019
10020
10021def prove(claim, show=False, **keywords):
10022 """Try to prove the given claim.
10023
10024 This is a simple function for creating demonstrations. It tries to prove
10025 `claim` by showing the negation is unsatisfiable.
10026
10027 >>> p, q = Bools('p q')
10028 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
10029 proved
10030 """
10031 if z3_debug():
10032 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10033 s = Solver()
10034 s.set(**keywords)
10035 s.add(Not(claim))
10036 if show:
10037 print(s)
10038 r = s.check()
10039 if r == unsat:
10040 print("proved")
10041 elif r == unknown:
10042 print("failed to prove")
10043 print(s.model())
10044 else:
10045 print("counterexample")
10046 print(s.model())
10047
10048
10049def _solve_html(*args, **keywords):
10050 """Version of function `solve` that renders HTML output."""
10051 show = keywords.pop("show", False)
10052 s = Solver()
10053 s.set(**keywords)
10054 s.add(*args)
10055 if show:
10056 print("<b>Problem:</b>")
10057 print(s)
10058 r = s.check()
10059 if r == unsat:
10060 print("<b>no solution</b>")
10061 elif r == unknown:
10062 print("<b>failed to solve</b>")
10063 try:
10064 print(s.model())
10065 except Z3Exception:
10066 return
10067 else:
10068 if show:
10069 print("<b>Solution:</b>")
10070 print(s.model())
10071
10072
10073def _solve_using_html(s, *args, **keywords):
10074 """Version of function `solve_using` that renders HTML."""
10075 show = keywords.pop("show", False)
10076 if z3_debug():
10077 _z3_assert(isinstance(s, Solver), "Solver object expected")
10078 s.set(**keywords)
10079 s.add(*args)
10080 if show:
10081 print("<b>Problem:</b>")
10082 print(s)
10083 r = s.check()
10084 if r == unsat:
10085 print("<b>no solution</b>")
10086 elif r == unknown:
10087 print("<b>failed to solve</b>")
10088 try:
10089 print(s.model())
10090 except Z3Exception:
10091 return
10092 else:
10093 if show:
10094 print("<b>Solution:</b>")
10095 print(s.model())
10096
10097
10098def _prove_html(claim, show=False, **keywords):
10099 """Version of function `prove` that renders HTML."""
10100 if z3_debug():
10101 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10102 s = Solver()
10103 s.set(**keywords)
10104 s.add(Not(claim))
10105 if show:
10106 print(s)
10107 r = s.check()
10108 if r == unsat:
10109 print("<b>proved</b>")
10110 elif r == unknown:
10111 print("<b>failed to prove</b>")
10112 print(s.model())
10113 else:
10114 print("<b>counterexample</b>")
10115 print(s.model())
10116
10117
10118def _dict2sarray(sorts, ctx):
10119 sz = len(sorts)
10120 _names = (Symbol * sz)()
10121 _sorts = (Sort * sz)()
10122 i = 0
10123 for k in sorts:
10124 v = sorts[k]
10125 if z3_debug():
10126 _z3_assert(isinstance(k, str), "String expected")
10127 _z3_assert(is_sort(v), "Z3 sort expected")
10128 _names[i] = to_symbol(k, ctx)
10129 _sorts[i] = v.ast
10130 i = i + 1
10131 return sz, _names, _sorts
10132
10133
10134def _dict2darray(decls, ctx):
10135 sz = len(decls)
10136 _names = (Symbol * sz)()
10137 _decls = (FuncDecl * sz)()
10138 i = 0
10139 for k in decls:
10140 v = decls[k]
10141 if z3_debug():
10142 _z3_assert(isinstance(k, str), "String expected")
10143 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10144 _names[i] = to_symbol(k, ctx)
10145 if is_const(v):
10146 _decls[i] = v.decl().ast
10147 else:
10148 _decls[i] = v.ast
10149 i = i + 1
10150 return sz, _names, _decls
10151
10152class ParserContext:
10153 def __init__(self, ctx= None):
10154 self.ctx = _get_ctx(ctx)
10155 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10156 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10157
10158 def __del__(self):
10159 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10160 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10161 self.pctx = None
10162
10163 def add_sort(self, sort):
10164 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10165
10166 def add_decl(self, decl):
10167 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10168
10169 def from_string(self, s):
10170 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10171
10172def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10173 """Parse a string in SMT 2.0 format using the given sorts and decls.
10174
10175 The arguments sorts and decls are Python dictionaries used to initialize
10176 the symbol table used for the SMT 2.0 parser.
10177
10178 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10179 [x > 0, x < 10]
10180 >>> x, y = Ints('x y')
10181 >>> f = Function('f', IntSort(), IntSort())
10182 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10183 [x + f(y) > 0]
10184 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10185 [a > 0]
10186 """
10187 ctx = _get_ctx(ctx)
10188 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10189 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10190 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10191
10192
10193def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10194 """Parse a file in SMT 2.0 format using the given sorts and decls.
10195
10196 This function is similar to parse_smt2_string().
10197 """
10198 ctx = _get_ctx(ctx)
10199 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10200 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10201 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10202
10203
10204#########################################
10205#
10206# Floating-Point Arithmetic
10207#
10208#########################################
10209
10210
10211# Global default rounding mode
10212_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10213_dflt_fpsort_ebits = 11
10214_dflt_fpsort_sbits = 53
10215
10216
10217def get_default_rounding_mode(ctx=None):
10218 """Retrieves the global default rounding mode."""
10219 global _dflt_rounding_mode
10220 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10221 return RTZ(ctx)
10222 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10223 return RTN(ctx)
10224 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10225 return RTP(ctx)
10226 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10227 return RNE(ctx)
10228 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10229 return RNA(ctx)
10230
10231
10232_ROUNDING_MODES = frozenset({
10233 Z3_OP_FPA_RM_TOWARD_ZERO,
10234 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10235 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10236 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10237 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10238})
10239
10240
10241def set_default_rounding_mode(rm, ctx=None):
10242 global _dflt_rounding_mode
10243 if is_fprm_value(rm):
10244 _dflt_rounding_mode = rm.kind()
10245 else:
10246 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10247 _dflt_rounding_mode = rm
10248
10249
10250def get_default_fp_sort(ctx=None):
10251 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10252
10253
10254def set_default_fp_sort(ebits, sbits, ctx=None):
10255 global _dflt_fpsort_ebits
10256 global _dflt_fpsort_sbits
10257 _dflt_fpsort_ebits = ebits
10258 _dflt_fpsort_sbits = sbits
10259
10260
10261def _dflt_rm(ctx=None):
10262 return get_default_rounding_mode(ctx)
10263
10264
10265def _dflt_fps(ctx=None):
10266 return get_default_fp_sort(ctx)
10267
10268
10269def _coerce_fp_expr_list(alist, ctx):
10270 first_fp_sort = None
10271 for a in alist:
10272 if is_fp(a):
10273 if first_fp_sort is None:
10274 first_fp_sort = a.sort()
10275 elif first_fp_sort == a.sort():
10276 pass # OK, same as before
10277 else:
10278 # we saw at least 2 different float sorts; something will
10279 # throw a sort mismatch later, for now assume None.
10280 first_fp_sort = None
10281 break
10282
10283 r = []
10284 for i in range(len(alist)):
10285 a = alist[i]
10286 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10287 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10288 r.append(FPVal(a, None, first_fp_sort, ctx))
10289 else:
10290 r.append(a)
10291 return _coerce_expr_list(r, ctx)
10292
10293
10294# FP Sorts
10295
10296class FPSortRef(SortRef):
10297 """Floating-point sort."""
10298
10299 def ebits(self):
10300 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10301 >>> b = FPSort(8, 24)
10302 >>> b.ebits()
10303 8
10304 """
10305 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10306
10307 def sbits(self):
10308 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10309 >>> b = FPSort(8, 24)
10310 >>> b.sbits()
10311 24
10312 """
10313 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10314
10315 def cast(self, val):
10316 """Try to cast `val` as a floating-point expression.
10317 >>> b = FPSort(8, 24)
10318 >>> b.cast(1.0)
10319 1
10320 >>> b.cast(1.0).sexpr()
10321 '(fp #b0 #x7f #b00000000000000000000000)'
10322 """
10323 if is_expr(val):
10324 if z3_debug():
10325 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10326 return val
10327 else:
10328 return FPVal(val, None, self, self.ctx)
10329
10330
10331def Float16(ctx=None):
10332 """Floating-point 16-bit (half) sort."""
10333 ctx = _get_ctx(ctx)
10334 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10335
10336
10337def FloatHalf(ctx=None):
10338 """Floating-point 16-bit (half) sort."""
10339 ctx = _get_ctx(ctx)
10340 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10341
10342
10343def Float32(ctx=None):
10344 """Floating-point 32-bit (single) sort."""
10345 ctx = _get_ctx(ctx)
10346 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10347
10348
10349def FloatSingle(ctx=None):
10350 """Floating-point 32-bit (single) sort."""
10351 ctx = _get_ctx(ctx)
10352 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10353
10354
10355def Float64(ctx=None):
10356 """Floating-point 64-bit (double) sort."""
10357 ctx = _get_ctx(ctx)
10358 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10359
10360
10361def FloatDouble(ctx=None):
10362 """Floating-point 64-bit (double) sort."""
10363 ctx = _get_ctx(ctx)
10364 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10365
10366
10367def Float128(ctx=None):
10368 """Floating-point 128-bit (quadruple) sort."""
10369 ctx = _get_ctx(ctx)
10370 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10371
10372
10373def FloatQuadruple(ctx=None):
10374 """Floating-point 128-bit (quadruple) sort."""
10375 ctx = _get_ctx(ctx)
10376 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10377
10378
10379class FPRMSortRef(SortRef):
10380 """"Floating-point rounding mode sort."""
10381
10382
10383def is_fp_sort(s):
10384 """Return True if `s` is a Z3 floating-point sort.
10385
10386 >>> is_fp_sort(FPSort(8, 24))
10387 True
10388 >>> is_fp_sort(IntSort())
10389 False
10390 """
10391 return isinstance(s, FPSortRef)
10392
10393
10394def is_fprm_sort(s):
10395 """Return True if `s` is a Z3 floating-point rounding mode sort.
10396
10397 >>> is_fprm_sort(FPSort(8, 24))
10398 False
10399 >>> is_fprm_sort(RNE().sort())
10400 True
10401 """
10402 return isinstance(s, FPRMSortRef)
10403
10404# FP Expressions
10405
10406
10407class FPRef(ExprRef):
10408 """Floating-point expressions."""
10409
10410 def sort(self):
10411 """Return the sort of the floating-point expression `self`.
10412
10413 >>> x = FP('1.0', FPSort(8, 24))
10414 >>> x.sort()
10415 FPSort(8, 24)
10416 >>> x.sort() == FPSort(8, 24)
10417 True
10418 """
10419 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10420
10421 def ebits(self):
10422 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10423 >>> b = FPSort(8, 24)
10424 >>> b.ebits()
10425 8
10426 """
10427 return self.sort().ebits()
10428
10429 def sbits(self):
10430 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10431 >>> b = FPSort(8, 24)
10432 >>> b.sbits()
10433 24
10434 """
10435 return self.sort().sbits()
10436
10437 def as_string(self):
10438 """Return a Z3 floating point expression as a Python string."""
10439 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10440
10441 def __le__(self, other):
10442 return fpLEQ(self, other, self.ctx)
10443
10444 def __lt__(self, other):
10445 return fpLT(self, other, self.ctx)
10446
10447 def __ge__(self, other):
10448 return fpGEQ(self, other, self.ctx)
10449
10450 def __gt__(self, other):
10451 return fpGT(self, other, self.ctx)
10452
10453 def __add__(self, other):
10454 """Create the Z3 expression `self + other`.
10455
10456 >>> x = FP('x', FPSort(8, 24))
10457 >>> y = FP('y', FPSort(8, 24))
10458 >>> x + y
10459 x + y
10460 >>> (x + y).sort()
10461 FPSort(8, 24)
10462 """
10463 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10464 return fpAdd(_dflt_rm(), a, b, self.ctx)
10465
10466 def __radd__(self, other):
10467 """Create the Z3 expression `other + self`.
10468
10469 >>> x = FP('x', FPSort(8, 24))
10470 >>> 10 + x
10471 1.25*(2**3) + x
10472 """
10473 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10474 return fpAdd(_dflt_rm(), a, b, self.ctx)
10475
10476 def __sub__(self, other):
10477 """Create the Z3 expression `self - other`.
10478
10479 >>> x = FP('x', FPSort(8, 24))
10480 >>> y = FP('y', FPSort(8, 24))
10481 >>> x - y
10482 x - y
10483 >>> (x - y).sort()
10484 FPSort(8, 24)
10485 """
10486 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10487 return fpSub(_dflt_rm(), a, b, self.ctx)
10488
10489 def __rsub__(self, other):
10490 """Create the Z3 expression `other - self`.
10491
10492 >>> x = FP('x', FPSort(8, 24))
10493 >>> 10 - x
10494 1.25*(2**3) - x
10495 """
10496 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10497 return fpSub(_dflt_rm(), a, b, self.ctx)
10498
10499 def __mul__(self, other):
10500 """Create the Z3 expression `self * other`.
10501
10502 >>> x = FP('x', FPSort(8, 24))
10503 >>> y = FP('y', FPSort(8, 24))
10504 >>> x * y
10505 x * y
10506 >>> (x * y).sort()
10507 FPSort(8, 24)
10508 >>> 10 * y
10509 1.25*(2**3) * y
10510 """
10511 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10512 return fpMul(_dflt_rm(), a, b, self.ctx)
10513
10514 def __rmul__(self, other):
10515 """Create the Z3 expression `other * self`.
10516
10517 >>> x = FP('x', FPSort(8, 24))
10518 >>> y = FP('y', FPSort(8, 24))
10519 >>> x * y
10520 x * y
10521 >>> x * 10
10522 x * 1.25*(2**3)
10523 """
10524 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10525 return fpMul(_dflt_rm(), a, b, self.ctx)
10526
10527 def __pos__(self):
10528 """Create the Z3 expression `+self`."""
10529 return self
10530
10531 def __neg__(self):
10532 """Create the Z3 expression `-self`.
10533
10534 >>> x = FP('x', Float32())
10535 >>> -x
10536 -x
10537 """
10538 return fpNeg(self)
10539
10540 def __div__(self, other):
10541 """Create the Z3 expression `self / other`.
10542
10543 >>> x = FP('x', FPSort(8, 24))
10544 >>> y = FP('y', FPSort(8, 24))
10545 >>> x / y
10546 x / y
10547 >>> (x / y).sort()
10548 FPSort(8, 24)
10549 >>> 10 / y
10550 1.25*(2**3) / y
10551 """
10552 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10553 return fpDiv(_dflt_rm(), a, b, self.ctx)
10554
10555 def __rdiv__(self, other):
10556 """Create the Z3 expression `other / self`.
10557
10558 >>> x = FP('x', FPSort(8, 24))
10559 >>> y = FP('y', FPSort(8, 24))
10560 >>> x / y
10561 x / y
10562 >>> x / 10
10563 x / 1.25*(2**3)
10564 """
10565 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10566 return fpDiv(_dflt_rm(), a, b, self.ctx)
10567
10568 def __truediv__(self, other):
10569 """Create the Z3 expression division `self / other`."""
10570 return self.__div__(other)
10571
10572 def __rtruediv__(self, other):
10573 """Create the Z3 expression division `other / self`."""
10574 return self.__rdiv__(other)
10575
10576 def __mod__(self, other):
10577 """Create the Z3 expression mod `self % other`."""
10578 return fpRem(self, other)
10579
10580 def __rmod__(self, other):
10581 """Create the Z3 expression mod `other % self`."""
10582 return fpRem(other, self)
10583
10584
10585class FPRMRef(ExprRef):
10586 """Floating-point rounding mode expressions"""
10587
10588 def as_string(self):
10589 """Return a Z3 floating point expression as a Python string."""
10590 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10591
10592
10593def RoundNearestTiesToEven(ctx=None):
10594 ctx = _get_ctx(ctx)
10595 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10596
10597
10598def RNE(ctx=None):
10599 ctx = _get_ctx(ctx)
10600 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10601
10602
10603def RoundNearestTiesToAway(ctx=None):
10604 ctx = _get_ctx(ctx)
10605 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10606
10607
10608def RNA(ctx=None):
10609 ctx = _get_ctx(ctx)
10610 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10611
10612
10613def RoundTowardPositive(ctx=None):
10614 ctx = _get_ctx(ctx)
10615 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10616
10617
10618def RTP(ctx=None):
10619 ctx = _get_ctx(ctx)
10620 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10621
10622
10623def RoundTowardNegative(ctx=None):
10624 ctx = _get_ctx(ctx)
10625 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10626
10627
10628def RTN(ctx=None):
10629 ctx = _get_ctx(ctx)
10630 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10631
10632
10633def RoundTowardZero(ctx=None):
10634 ctx = _get_ctx(ctx)
10635 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10636
10637
10638def RTZ(ctx=None):
10639 ctx = _get_ctx(ctx)
10640 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10641
10642
10643def is_fprm(a):
10644 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10645
10646 >>> rm = RNE()
10647 >>> is_fprm(rm)
10648 True
10649 >>> rm = 1.0
10650 >>> is_fprm(rm)
10651 False
10652 """
10653 return isinstance(a, FPRMRef)
10654
10655
10656def is_fprm_value(a):
10657 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10658 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10659
10660# FP Numerals
10661
10662
10663class FPNumRef(FPRef):
10664 """The sign of the numeral.
10665
10666 >>> x = FPVal(+1.0, FPSort(8, 24))
10667 >>> x.sign()
10668 False
10669 >>> x = FPVal(-1.0, FPSort(8, 24))
10670 >>> x.sign()
10671 True
10672 """
10673
10674 def sign(self):
10675 num = ctypes.c_bool()
10676 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10677 if nsign is False:
10678 raise Z3Exception("error retrieving the sign of a numeral.")
10679 return num.value != 0
10680
10681 """The sign of a floating-point numeral as a bit-vector expression.
10682
10683 Remark: NaN's are invalid arguments.
10684 """
10685
10686 def sign_as_bv(self):
10687 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10688
10689 """The significand of the numeral.
10690
10691 >>> x = FPVal(2.5, FPSort(8, 24))
10692 >>> x.significand()
10693 1.25
10694 """
10695
10696 def significand(self):
10697 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10698
10699 """The significand of the numeral as a long.
10700
10701 >>> x = FPVal(2.5, FPSort(8, 24))
10702 >>> x.significand_as_long()
10703 1.25
10704 """
10705
10706 def significand_as_long(self):
10707 ptr = (ctypes.c_ulonglong * 1)()
10708 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10709 raise Z3Exception("error retrieving the significand of a numeral.")
10710 return ptr[0]
10711
10712 """The significand of the numeral as a bit-vector expression.
10713
10714 Remark: NaN are invalid arguments.
10715 """
10716
10717 def significand_as_bv(self):
10718 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10719
10720 """The exponent of the numeral.
10721
10722 >>> x = FPVal(2.5, FPSort(8, 24))
10723 >>> x.exponent()
10724 1
10725 """
10726
10727 def exponent(self, biased=True):
10728 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10729
10730 """The exponent of the numeral as a long.
10731
10732 >>> x = FPVal(2.5, FPSort(8, 24))
10733 >>> x.exponent_as_long()
10734 1
10735 """
10736
10737 def exponent_as_long(self, biased=True):
10738 ptr = (ctypes.c_longlong * 1)()
10739 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10740 raise Z3Exception("error retrieving the exponent of a numeral.")
10741 return ptr[0]
10742
10743 """The exponent of the numeral as a bit-vector expression.
10744
10745 Remark: NaNs are invalid arguments.
10746 """
10747
10748 def exponent_as_bv(self, biased=True):
10749 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10750
10751 """Indicates whether the numeral is a NaN."""
10752
10753 def isNaN(self):
10754 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10755
10756 """Indicates whether the numeral is +oo or -oo."""
10757
10758 def isInf(self):
10759 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10760
10761 """Indicates whether the numeral is +zero or -zero."""
10762
10763 def isZero(self):
10764 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10765
10766 """Indicates whether the numeral is normal."""
10767
10768 def isNormal(self):
10769 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10770
10771 """Indicates whether the numeral is subnormal."""
10772
10773 def isSubnormal(self):
10774 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10775
10776 """Indicates whether the numeral is positive."""
10777
10778 def isPositive(self):
10779 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10780
10781 """Indicates whether the numeral is negative."""
10782
10783 def isNegative(self):
10784 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10785
10786 """
10787 The string representation of the numeral.
10788
10789 >>> x = FPVal(20, FPSort(8, 24))
10790 >>> x.as_string()
10791 1.25*(2**4)
10792 """
10793
10794 def as_string(self):
10795 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10796 return ("FPVal(%s, %s)" % (s, self.sort()))
10797
10798 def py_value(self):
10799 bv = simplify(fpToIEEEBV(self))
10800 binary = bv.py_value()
10801 if not isinstance(binary, int):
10802 return None
10803 # Decode the IEEE 754 binary representation
10804 import struct
10805 bytes_rep = binary.to_bytes(8, byteorder='big')
10806 return struct.unpack('>d', bytes_rep)[0]
10807
10808
10809def is_fp(a):
10810 """Return `True` if `a` is a Z3 floating-point expression.
10811
10812 >>> b = FP('b', FPSort(8, 24))
10813 >>> is_fp(b)
10814 True
10815 >>> is_fp(b + 1.0)
10816 True
10817 >>> is_fp(Int('x'))
10818 False
10819 """
10820 return isinstance(a, FPRef)
10821
10822
10823def is_fp_value(a):
10824 """Return `True` if `a` is a Z3 floating-point numeral value.
10825
10826 >>> b = FP('b', FPSort(8, 24))
10827 >>> is_fp_value(b)
10828 False
10829 >>> b = FPVal(1.0, FPSort(8, 24))
10830 >>> b
10831 1
10832 >>> is_fp_value(b)
10833 True
10834 """
10835 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10836
10837
10838def FPSort(ebits, sbits, ctx=None):
10839 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10840
10841 >>> Single = FPSort(8, 24)
10842 >>> Double = FPSort(11, 53)
10843 >>> Single
10844 FPSort(8, 24)
10845 >>> x = Const('x', Single)
10846 >>> eq(x, FP('x', FPSort(8, 24)))
10847 True
10848 """
10849 ctx = _get_ctx(ctx)
10850 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10851
10852
10853def _to_float_str(val, exp=0):
10854 if isinstance(val, float):
10855 if math.isnan(val):
10856 res = "NaN"
10857 elif val == 0.0:
10858 sone = math.copysign(1.0, val)
10859 if sone < 0.0:
10860 return "-0.0"
10861 else:
10862 return "+0.0"
10863 elif val == float("+inf"):
10864 res = "+oo"
10865 elif val == float("-inf"):
10866 res = "-oo"
10867 else:
10868 v = val.as_integer_ratio()
10869 num = v[0]
10870 den = v[1]
10871 rvs = str(num) + "/" + str(den)
10872 res = rvs
10873 elif isinstance(val, bool):
10874 if val:
10875 res = "1.0"
10876 else:
10877 res = "0.0"
10878 elif _is_int(val):
10879 res = str(val)
10880 elif isinstance(val, str):
10881 inx = val.find("*(2**")
10882 if inx == -1:
10883 res = val
10884 if exp != 0:
10885 inx = val.lower().find("p")
10886 if inx != -1:
10887 res = val[:inx]
10888 exp = int(val[inx + 1:]) + int(exp)
10889 elif val[-1] == ")":
10890 res = val[0:inx]
10891 exp = str(int(val[inx + 5:-1]) + int(exp))
10892 else:
10893 _z3_assert(False, "String does not have floating-point numeral form.")
10894 elif z3_debug():
10895 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10896 if exp == 0:
10897 return res
10898 else:
10899 return res + "p" + str(exp)
10900
10901
10902def fpNaN(s):
10903 """Create a Z3 floating-point NaN term.
10904
10905 >>> s = FPSort(8, 24)
10906 >>> set_fpa_pretty(True)
10907 >>> fpNaN(s)
10908 NaN
10909 >>> pb = get_fpa_pretty()
10910 >>> set_fpa_pretty(False)
10911 >>> fpNaN(s)
10912 fpNaN(FPSort(8, 24))
10913 >>> set_fpa_pretty(pb)
10914 """
10915 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10916 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10917
10918
10919def fpPlusInfinity(s):
10920 """Create a Z3 floating-point +oo term.
10921
10922 >>> s = FPSort(8, 24)
10923 >>> pb = get_fpa_pretty()
10924 >>> set_fpa_pretty(True)
10925 >>> fpPlusInfinity(s)
10926 +oo
10927 >>> set_fpa_pretty(False)
10928 >>> fpPlusInfinity(s)
10929 fpPlusInfinity(FPSort(8, 24))
10930 >>> set_fpa_pretty(pb)
10931 """
10932 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10933 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10934
10935
10936def fpMinusInfinity(s):
10937 """Create a Z3 floating-point -oo term."""
10938 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10939 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10940
10941
10942def fpInfinity(s, negative):
10943 """Create a Z3 floating-point +oo or -oo term."""
10944 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10945 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10946 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10947
10948
10949def fpPlusZero(s):
10950 """Create a Z3 floating-point +0.0 term."""
10951 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10952 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10953
10954
10955def fpMinusZero(s):
10956 """Create a Z3 floating-point -0.0 term."""
10957 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10958 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10959
10960
10961def fpZero(s, negative):
10962 """Create a Z3 floating-point +0.0 or -0.0 term."""
10963 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10964 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10965 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10966
10967
10968def FPVal(sig, exp=None, fps=None, ctx=None):
10969 """Return a floating-point value of value `sig * 2**exp` and sort `fps`.
10970 If `exp=None`, then the exponent is zero.
10971 If `ctx=None`, then the global context is used.
10972
10973 >>> v = FPVal(20.0, FPSort(8, 24))
10974 >>> v
10975 1.25*(2**4)
10976 >>> print("0x%.8x" % v.exponent_as_long(False))
10977 0x00000004
10978 >>> v = FPVal(2.25, FPSort(8, 24))
10979 >>> v
10980 1.125*(2**1)
10981 >>> v = FPVal(-2.25, FPSort(8, 24))
10982 >>> v
10983 -1.125*(2**1)
10984 >>> FPVal(-0.0, FPSort(8, 24))
10985 -0.0
10986 >>> FPVal(0.0, FPSort(8, 24))
10987 +0.0
10988 >>> FPVal(+0.0, FPSort(8, 24))
10989 +0.0
10990 >>> FPVal(1.0, 3, Float32())
10991 1*(2**3)
10992 >>> FPVal(1, 3, Float32())
10993 1*(2**3)
10994 >>> FPVal("1.5", -2, Float32())
10995 1.5*(2**-2)
10996 >>> FPVal("1.25*(2**4)", 1, Float32())
10997 1.25*(2**5)
10998 >>> FPVal("1.25*(2**4)", -4, Float32())
10999 1.25
11000 >>> FPVal("1p2", 3, Float32())
11001 1*(2**5)
11002 >>> FPVal("1P2", 3, Float32())
11003 1*(2**5)
11004 >>> FPVal("1.5p-2", 2, Float32())
11005 1.5
11006 >>> FPVal(1.5, 0, Float32())
11007 1.5
11008 >>> FPVal(1.5, fps=Float32())
11009 1.5
11010 >>> [FPVal(v, 3, Float32()) for v in
11011 ... [float("nan"), float("inf"), float("-inf"), 0.0, -0.0]]
11012 [NaN, +oo, -oo, +0.0, -0.0]
11013 >>> [FPVal(v, -2, Float32()) for v in
11014 ... ["NaN", "+oo", "-oo", "+0.0", "-0.0"]]
11015 [NaN, +oo, -oo, +0.0, -0.0]
11016 """
11017 ctx = _get_ctx(ctx)
11018 if is_fp_sort(exp):
11019 fps = exp
11020 exp = None
11021 elif fps is None:
11022 fps = _dflt_fps(ctx)
11023 _z3_assert(is_fp_sort(fps), "sort mismatch")
11024 if exp is None:
11025 exp = 0
11026 val = _to_float_str(sig)
11027 if val == "NaN" or val == "nan":
11028 return fpNaN(fps)
11029 elif val == "-0.0":
11030 return fpMinusZero(fps)
11031 elif val == "0.0" or val == "+0.0":
11032 return fpPlusZero(fps)
11033 elif val == "+oo" or val == "+inf" or val == "+Inf":
11034 return fpPlusInfinity(fps)
11035 elif val == "-oo" or val == "-inf" or val == "-Inf":
11036 return fpMinusInfinity(fps)
11037 else:
11038 return FPNumRef(Z3_mk_numeral(ctx.ref(), _to_float_str(sig, exp), fps.ast), ctx)
11039
11040
11041def FP(name, fpsort, ctx=None):
11042 """Return a floating-point constant named `name`.
11043 `fpsort` is the floating-point sort.
11044 If `ctx=None`, then the global context is used.
11045
11046 >>> x = FP('x', FPSort(8, 24))
11047 >>> is_fp(x)
11048 True
11049 >>> x.ebits()
11050 8
11051 >>> x.sort()
11052 FPSort(8, 24)
11053 >>> word = FPSort(8, 24)
11054 >>> x2 = FP('x', word)
11055 >>> eq(x, x2)
11056 True
11057 """
11058 if isinstance(fpsort, FPSortRef) and ctx is None:
11059 ctx = fpsort.ctx
11060 else:
11061 ctx = _get_ctx(ctx)
11062 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
11063
11064
11065def FPs(names, fpsort, ctx=None):
11066 """Return an array of floating-point constants.
11067
11068 >>> x, y, z = FPs('x y z', FPSort(8, 24))
11069 >>> x.sort()
11070 FPSort(8, 24)
11071 >>> x.sbits()
11072 24
11073 >>> x.ebits()
11074 8
11075 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
11076 (x + y) * z
11077 """
11078 ctx = _get_ctx(ctx)
11079 if isinstance(names, str):
11080 names = names.split(" ")
11081 return [FP(name, fpsort, ctx) for name in names]
11082
11083
11084def fpAbs(a, ctx=None):
11085 """Create a Z3 floating-point absolute value expression.
11086
11087 >>> s = FPSort(8, 24)
11088 >>> rm = RNE()
11089 >>> x = FPVal(1.0, s)
11090 >>> fpAbs(x)
11091 fpAbs(1)
11092 >>> y = FPVal(-20.0, s)
11093 >>> y
11094 -1.25*(2**4)
11095 >>> fpAbs(y)
11096 fpAbs(-1.25*(2**4))
11097 >>> fpAbs(-1.25*(2**4))
11098 fpAbs(-1.25*(2**4))
11099 >>> fpAbs(x).sort()
11100 FPSort(8, 24)
11101 """
11102 ctx = _get_ctx(ctx)
11103 [a] = _coerce_fp_expr_list([a], ctx)
11104 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
11105
11106
11107def fpNeg(a, ctx=None):
11108 """Create a Z3 floating-point addition expression.
11109
11110 >>> s = FPSort(8, 24)
11111 >>> rm = RNE()
11112 >>> x = FP('x', s)
11113 >>> fpNeg(x)
11114 -x
11115 >>> fpNeg(x).sort()
11116 FPSort(8, 24)
11117 """
11118 ctx = _get_ctx(ctx)
11119 [a] = _coerce_fp_expr_list([a], ctx)
11120 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
11121
11122
11123def _mk_fp_unary(f, rm, a, ctx):
11124 ctx = _get_ctx(ctx)
11125 [a] = _coerce_fp_expr_list([a], ctx)
11126 if z3_debug():
11127 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11128 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
11129 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
11130
11131
11132def _mk_fp_unary_pred(f, a, ctx):
11133 ctx = _get_ctx(ctx)
11134 [a] = _coerce_fp_expr_list([a], ctx)
11135 if z3_debug():
11136 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
11137 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
11138
11139
11140def _mk_fp_bin(f, rm, a, b, ctx):
11141 ctx = _get_ctx(ctx)
11142 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11143 if z3_debug():
11144 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11145 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
11146 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
11147
11148
11149def _mk_fp_bin_norm(f, a, b, ctx):
11150 ctx = _get_ctx(ctx)
11151 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11152 if z3_debug():
11153 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11154 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11155
11156
11157def _mk_fp_bin_pred(f, a, b, ctx):
11158 ctx = _get_ctx(ctx)
11159 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11160 if z3_debug():
11161 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11162 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11163
11164
11165def _mk_fp_tern(f, rm, a, b, c, ctx):
11166 ctx = _get_ctx(ctx)
11167 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11168 if z3_debug():
11169 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11170 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11171 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11172 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11173
11174
11175def fpAdd(rm, a, b, ctx=None):
11176 """Create a Z3 floating-point addition expression.
11177
11178 >>> s = FPSort(8, 24)
11179 >>> rm = RNE()
11180 >>> x = FP('x', s)
11181 >>> y = FP('y', s)
11182 >>> fpAdd(rm, x, y)
11183 x + y
11184 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11185 fpAdd(RTZ(), x, y)
11186 >>> fpAdd(rm, x, y).sort()
11187 FPSort(8, 24)
11188 """
11189 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11190
11191
11192def fpSub(rm, a, b, ctx=None):
11193 """Create a Z3 floating-point subtraction expression.
11194
11195 >>> s = FPSort(8, 24)
11196 >>> rm = RNE()
11197 >>> x = FP('x', s)
11198 >>> y = FP('y', s)
11199 >>> fpSub(rm, x, y)
11200 x - y
11201 >>> fpSub(rm, x, y).sort()
11202 FPSort(8, 24)
11203 """
11204 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11205
11206
11207def fpMul(rm, a, b, ctx=None):
11208 """Create a Z3 floating-point multiplication expression.
11209
11210 >>> s = FPSort(8, 24)
11211 >>> rm = RNE()
11212 >>> x = FP('x', s)
11213 >>> y = FP('y', s)
11214 >>> fpMul(rm, x, y)
11215 x * y
11216 >>> fpMul(rm, x, y).sort()
11217 FPSort(8, 24)
11218 """
11219 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11220
11221
11222def fpDiv(rm, a, b, ctx=None):
11223 """Create a Z3 floating-point division expression.
11224
11225 >>> s = FPSort(8, 24)
11226 >>> rm = RNE()
11227 >>> x = FP('x', s)
11228 >>> y = FP('y', s)
11229 >>> fpDiv(rm, x, y)
11230 x / y
11231 >>> fpDiv(rm, x, y).sort()
11232 FPSort(8, 24)
11233 """
11234 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11235
11236
11237def fpRem(a, b, ctx=None):
11238 """Create a Z3 floating-point remainder expression.
11239
11240 >>> s = FPSort(8, 24)
11241 >>> x = FP('x', s)
11242 >>> y = FP('y', s)
11243 >>> fpRem(x, y)
11244 fpRem(x, y)
11245 >>> fpRem(x, y).sort()
11246 FPSort(8, 24)
11247 """
11248 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11249
11250
11251def fpMin(a, b, ctx=None):
11252 """Create a Z3 floating-point minimum expression.
11253
11254 >>> s = FPSort(8, 24)
11255 >>> rm = RNE()
11256 >>> x = FP('x', s)
11257 >>> y = FP('y', s)
11258 >>> fpMin(x, y)
11259 fpMin(x, y)
11260 >>> fpMin(x, y).sort()
11261 FPSort(8, 24)
11262 """
11263 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11264
11265
11266def fpMax(a, b, ctx=None):
11267 """Create a Z3 floating-point maximum expression.
11268
11269 >>> s = FPSort(8, 24)
11270 >>> rm = RNE()
11271 >>> x = FP('x', s)
11272 >>> y = FP('y', s)
11273 >>> fpMax(x, y)
11274 fpMax(x, y)
11275 >>> fpMax(x, y).sort()
11276 FPSort(8, 24)
11277 """
11278 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11279
11280
11281def fpFMA(rm, a, b, c, ctx=None):
11282 """Create a Z3 floating-point fused multiply-add expression.
11283 """
11284 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11285
11286
11287def fpSqrt(rm, a, ctx=None):
11288 """Create a Z3 floating-point square root expression.
11289 """
11290 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11291
11292
11293def fpRoundToIntegral(rm, a, ctx=None):
11294 """Create a Z3 floating-point roundToIntegral expression.
11295 """
11296 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11297
11298
11299def fpIsNaN(a, ctx=None):
11300 """Create a Z3 floating-point isNaN expression.
11301
11302 >>> s = FPSort(8, 24)
11303 >>> x = FP('x', s)
11304 >>> y = FP('y', s)
11305 >>> fpIsNaN(x)
11306 fpIsNaN(x)
11307 """
11308 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11309
11310
11311def fpIsInf(a, ctx=None):
11312 """Create a Z3 floating-point isInfinite expression.
11313
11314 >>> s = FPSort(8, 24)
11315 >>> x = FP('x', s)
11316 >>> fpIsInf(x)
11317 fpIsInf(x)
11318 """
11319 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11320
11321
11322def fpIsZero(a, ctx=None):
11323 """Create a Z3 floating-point isZero expression.
11324 """
11325 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11326
11327
11328def fpIsNormal(a, ctx=None):
11329 """Create a Z3 floating-point isNormal expression.
11330 """
11331 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11332
11333
11334def fpIsSubnormal(a, ctx=None):
11335 """Create a Z3 floating-point isSubnormal expression.
11336 """
11337 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11338
11339
11340def fpIsNegative(a, ctx=None):
11341 """Create a Z3 floating-point isNegative expression.
11342 """
11343 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11344
11345
11346def fpIsPositive(a, ctx=None):
11347 """Create a Z3 floating-point isPositive expression.
11348 """
11349 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11350
11351
11352def _check_fp_args(a, b):
11353 if z3_debug():
11354 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11355
11356
11357def fpLT(a, b, ctx=None):
11358 """Create the Z3 floating-point expression `other < self`.
11359
11360 >>> x, y = FPs('x y', FPSort(8, 24))
11361 >>> fpLT(x, y)
11362 x < y
11363 >>> (x < y).sexpr()
11364 '(fp.lt x y)'
11365 """
11366 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11367
11368
11369def fpLEQ(a, b, ctx=None):
11370 """Create the Z3 floating-point expression `other <= self`.
11371
11372 >>> x, y = FPs('x y', FPSort(8, 24))
11373 >>> fpLEQ(x, y)
11374 x <= y
11375 >>> (x <= y).sexpr()
11376 '(fp.leq x y)'
11377 """
11378 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11379
11380
11381def fpGT(a, b, ctx=None):
11382 """Create the Z3 floating-point expression `other > self`.
11383
11384 >>> x, y = FPs('x y', FPSort(8, 24))
11385 >>> fpGT(x, y)
11386 x > y
11387 >>> (x > y).sexpr()
11388 '(fp.gt x y)'
11389 """
11390 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11391
11392
11393def fpGEQ(a, b, ctx=None):
11394 """Create the Z3 floating-point expression `other >= self`.
11395
11396 >>> x, y = FPs('x y', FPSort(8, 24))
11397 >>> fpGEQ(x, y)
11398 x >= y
11399 >>> (x >= y).sexpr()
11400 '(fp.geq x y)'
11401 """
11402 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11403
11404
11405def fpEQ(a, b, ctx=None):
11406 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11407
11408 >>> x, y = FPs('x y', FPSort(8, 24))
11409 >>> fpEQ(x, y)
11410 fpEQ(x, y)
11411 >>> fpEQ(x, y).sexpr()
11412 '(fp.eq x y)'
11413 """
11414 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11415
11416
11417def fpNEQ(a, b, ctx=None):
11418 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11419
11420 >>> x, y = FPs('x y', FPSort(8, 24))
11421 >>> fpNEQ(x, y)
11422 Not(fpEQ(x, y))
11423 >>> (x != y).sexpr()
11424 '(distinct x y)'
11425 """
11426 return Not(fpEQ(a, b, ctx))
11427
11428
11429def fpFP(sgn, exp, sig, ctx=None):
11430 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11431
11432 >>> s = FPSort(8, 24)
11433 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11434 >>> print(x)
11435 fpFP(1, 127, 4194304)
11436 >>> xv = FPVal(-1.5, s)
11437 >>> print(xv)
11438 -1.5
11439 >>> slvr = Solver()
11440 >>> slvr.add(fpEQ(x, xv))
11441 >>> slvr.check()
11442 sat
11443 >>> xv = FPVal(+1.5, s)
11444 >>> print(xv)
11445 1.5
11446 >>> slvr = Solver()
11447 >>> slvr.add(fpEQ(x, xv))
11448 >>> slvr.check()
11449 unsat
11450 """
11451 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11452 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11453 ctx = _get_ctx(ctx)
11454 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11455 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11456
11457
11458def fpToFP(a1, a2=None, a3=None, ctx=None):
11459 """Create a Z3 floating-point conversion expression from other term sorts
11460 to floating-point.
11461
11462 From a bit-vector term in IEEE 754-2008 format:
11463 >>> x = FPVal(1.0, Float32())
11464 >>> x_bv = fpToIEEEBV(x)
11465 >>> simplify(fpToFP(x_bv, Float32()))
11466 1
11467
11468 From a floating-point term with different precision:
11469 >>> x = FPVal(1.0, Float32())
11470 >>> x_db = fpToFP(RNE(), x, Float64())
11471 >>> x_db.sort()
11472 FPSort(11, 53)
11473
11474 From a real term:
11475 >>> x_r = RealVal(1.5)
11476 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11477 1.5
11478
11479 From a signed bit-vector term:
11480 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11481 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11482 -1.25*(2**2)
11483 """
11484 ctx = _get_ctx(ctx)
11485 if is_bv(a1) and is_fp_sort(a2):
11486 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11487 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11488 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11489 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11490 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11491 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11492 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11493 else:
11494 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11495
11496
11497def fpBVToFP(v, sort, ctx=None):
11498 """Create a Z3 floating-point conversion expression that represents the
11499 conversion from a bit-vector term to a floating-point term.
11500
11501 >>> x_bv = BitVecVal(0x3F800000, 32)
11502 >>> x_fp = fpBVToFP(x_bv, Float32())
11503 >>> x_fp
11504 fpToFP(1065353216)
11505 >>> simplify(x_fp)
11506 1
11507 """
11508 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11509 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11510 ctx = _get_ctx(ctx)
11511 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11512
11513
11514def fpFPToFP(rm, v, sort, ctx=None):
11515 """Create a Z3 floating-point conversion expression that represents the
11516 conversion from a floating-point term to a floating-point term of different precision.
11517
11518 >>> x_sgl = FPVal(1.0, Float32())
11519 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11520 >>> x_dbl
11521 fpToFP(RNE(), 1)
11522 >>> simplify(x_dbl)
11523 1
11524 >>> x_dbl.sort()
11525 FPSort(11, 53)
11526 """
11527 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11528 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11529 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11530 ctx = _get_ctx(ctx)
11531 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11532
11533
11534def fpRealToFP(rm, v, sort, ctx=None):
11535 """Create a Z3 floating-point conversion expression that represents the
11536 conversion from a real term to a floating-point term.
11537
11538 >>> x_r = RealVal(1.5)
11539 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11540 >>> x_fp
11541 fpToFP(RNE(), 3/2)
11542 >>> simplify(x_fp)
11543 1.5
11544 """
11545 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11546 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11547 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11548 ctx = _get_ctx(ctx)
11549 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11550
11551
11552def fpSignedToFP(rm, v, sort, ctx=None):
11553 """Create a Z3 floating-point conversion expression that represents the
11554 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11555
11556 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11557 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11558 >>> x_fp
11559 fpToFP(RNE(), 4294967291)
11560 >>> simplify(x_fp)
11561 -1.25*(2**2)
11562 """
11563 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11564 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11565 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11566 ctx = _get_ctx(ctx)
11567 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11568
11569
11570def fpUnsignedToFP(rm, v, sort, ctx=None):
11571 """Create a Z3 floating-point conversion expression that represents the
11572 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11573
11574 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11575 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11576 >>> x_fp
11577 fpToFPUnsigned(RNE(), 4294967291)
11578 >>> simplify(x_fp)
11579 1*(2**32)
11580 """
11581 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11582 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11583 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11584 ctx = _get_ctx(ctx)
11585 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11586
11587
11588def fpToFPUnsigned(rm, x, s, ctx=None):
11589 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11590 if z3_debug():
11591 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11592 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11593 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11594 ctx = _get_ctx(ctx)
11595 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11596
11597
11598def fpToSBV(rm, x, s, ctx=None):
11599 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11600
11601 >>> x = FP('x', FPSort(8, 24))
11602 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11603 >>> print(is_fp(x))
11604 True
11605 >>> print(is_bv(y))
11606 True
11607 >>> print(is_fp(y))
11608 False
11609 >>> print(is_bv(x))
11610 False
11611 """
11612 if z3_debug():
11613 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11614 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11615 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11616 ctx = _get_ctx(ctx)
11617 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11618
11619
11620def fpToUBV(rm, x, s, ctx=None):
11621 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11622
11623 >>> x = FP('x', FPSort(8, 24))
11624 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11625 >>> print(is_fp(x))
11626 True
11627 >>> print(is_bv(y))
11628 True
11629 >>> print(is_fp(y))
11630 False
11631 >>> print(is_bv(x))
11632 False
11633 """
11634 if z3_debug():
11635 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11636 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11637 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11638 ctx = _get_ctx(ctx)
11639 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11640
11641
11642def fpToReal(x, ctx=None):
11643 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11644
11645 >>> x = FP('x', FPSort(8, 24))
11646 >>> y = fpToReal(x)
11647 >>> print(is_fp(x))
11648 True
11649 >>> print(is_real(y))
11650 True
11651 >>> print(is_fp(y))
11652 False
11653 >>> print(is_real(x))
11654 False
11655 """
11656 if z3_debug():
11657 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11658 ctx = _get_ctx(ctx)
11659 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11660
11661
11662def fpToIEEEBV(x, ctx=None):
11663 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11664
11665 The size of the resulting bit-vector is automatically determined.
11666
11667 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11668 knows only one NaN and it will always produce the same bit-vector representation of
11669 that NaN.
11670
11671 >>> x = FP('x', FPSort(8, 24))
11672 >>> y = fpToIEEEBV(x)
11673 >>> print(is_fp(x))
11674 True
11675 >>> print(is_bv(y))
11676 True
11677 >>> print(is_fp(y))
11678 False
11679 >>> print(is_bv(x))
11680 False
11681 """
11682 if z3_debug():
11683 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11684 ctx = _get_ctx(ctx)
11685 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11686
11687
11688#########################################
11689#
11690# Strings, Sequences and Regular expressions
11691#
11692#########################################
11693
11694class SeqSortRef(SortRef):
11695 """Sequence sort."""
11696
11697 def is_string(self):
11698 """Determine if sort is a string
11699 >>> s = StringSort()
11700 >>> s.is_string()
11701 True
11702 >>> s = SeqSort(IntSort())
11703 >>> s.is_string()
11704 False
11705 """
11706 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11707
11708 def basis(self):
11709 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11710
11711class CharSortRef(SortRef):
11712 """Character sort."""
11713
11714
11715def StringSort(ctx=None):
11716 """Create a string sort
11717 >>> s = StringSort()
11718 >>> print(s)
11719 String
11720 """
11721 ctx = _get_ctx(ctx)
11722 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11723
11724def CharSort(ctx=None):
11725 """Create a character sort
11726 >>> ch = CharSort()
11727 >>> print(ch)
11728 Char
11729 """
11730 ctx = _get_ctx(ctx)
11731 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11732
11733
11734def SeqSort(s):
11735 """Create a sequence sort over elements provided in the argument
11736 >>> s = SeqSort(IntSort())
11737 >>> s == Unit(IntVal(1)).sort()
11738 True
11739 """
11740 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11741
11742
11743class SeqRef(ExprRef):
11744 """Sequence expression."""
11745
11746 def sort(self):
11747 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11748
11749 def __add__(self, other):
11750 return Concat(self, other)
11751
11752 def __radd__(self, other):
11753 return Concat(other, self)
11754
11755 def __pow__(self, other):
11756 return SeqPower(self, other)
11757
11758 def __getitem__(self, i):
11759 if _is_int(i):
11760 i = IntVal(i, self.ctx)
11761 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11762
11763 def at(self, i):
11764 if _is_int(i):
11765 i = IntVal(i, self.ctx)
11766 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11767
11768 def is_string(self):
11769 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11770
11771 def is_string_value(self):
11772 return Z3_is_string(self.ctx_ref(), self.as_ast())
11773
11774 def as_string(self):
11775 """Return a string representation of sequence expression."""
11776 if self.is_string_value():
11777 string_length = ctypes.c_uint()
11778 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11779 return string_at(chars, size=string_length.value).decode("latin-1")
11780 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11781
11782 def py_value(self):
11783 return self.as_string()
11784
11785 def __le__(self, other):
11786 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11787
11788 def __lt__(self, other):
11789 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11790
11791 def __ge__(self, other):
11792 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11793
11794 def __gt__(self, other):
11795 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11796
11797
11798def _coerce_char(ch, ctx=None):
11799 if isinstance(ch, str):
11800 ctx = _get_ctx(ctx)
11801 ch = CharVal(ch, ctx)
11802 if not is_expr(ch):
11803 raise Z3Exception("Character expression expected")
11804 return ch
11805
11806class CharRef(ExprRef):
11807 """Character expression."""
11808
11809 def __le__(self, other):
11810 other = _coerce_char(other, self.ctx)
11811 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11812
11813 def to_int(self):
11814 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11815
11816 def to_bv(self):
11817 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11818
11819 def is_digit(self):
11820 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11821
11822
11823def CharVal(ch, ctx=None):
11824 ctx = _get_ctx(ctx)
11825 if isinstance(ch, str):
11826 ch = ord(ch)
11827 if not isinstance(ch, int):
11828 raise Z3Exception("character value should be an ordinal")
11829 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11830
11831def CharFromBv(bv):
11832 if not is_expr(bv):
11833 raise Z3Exception("Bit-vector expression needed")
11834 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11835
11836def CharToBv(ch, ctx=None):
11837 ch = _coerce_char(ch, ctx)
11838 return ch.to_bv()
11839
11840def CharToInt(ch, ctx=None):
11841 ch = _coerce_char(ch, ctx)
11842 return ch.to_int()
11843
11844def CharIsDigit(ch, ctx=None):
11845 ch = _coerce_char(ch, ctx)
11846 return ch.is_digit()
11847
11848def _coerce_seq(s, ctx=None):
11849 if isinstance(s, str):
11850 ctx = _get_ctx(ctx)
11851 s = StringVal(s, ctx)
11852 if not is_expr(s):
11853 raise Z3Exception("Non-expression passed as a sequence")
11854 if not is_seq(s):
11855 raise Z3Exception("Non-sequence passed as a sequence")
11856 return s
11857
11858
11859def _get_ctx2(a, b, ctx=None):
11860 if is_expr(a):
11861 return a.ctx
11862 if is_expr(b):
11863 return b.ctx
11864 if ctx is None:
11865 ctx = main_ctx()
11866 return ctx
11867
11868
11869def is_seq(a):
11870 """Return `True` if `a` is a Z3 sequence expression.
11871 >>> print (is_seq(Unit(IntVal(0))))
11872 True
11873 >>> print (is_seq(StringVal("abc")))
11874 True
11875 """
11876 return isinstance(a, SeqRef)
11877
11878
11879def is_string(a: Any) -> bool:
11880 """Return `True` if `a` is a Z3 string expression.
11881 >>> print (is_string(StringVal("ab")))
11882 True
11883 """
11884 return isinstance(a, SeqRef) and a.is_string()
11885
11886
11887def is_string_value(a: Any) -> bool:
11888 """return 'True' if 'a' is a Z3 string constant expression.
11889 >>> print (is_string_value(StringVal("a")))
11890 True
11891 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11892 False
11893 """
11894 return isinstance(a, SeqRef) and a.is_string_value()
11895
11896def StringVal(s, ctx=None):
11897 """create a string expression"""
11898 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11899 ctx = _get_ctx(ctx)
11900 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11901
11902
11903def String(name, ctx=None):
11904 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11905
11906 >>> x = String('x')
11907 """
11908 ctx = _get_ctx(ctx)
11909 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11910
11911
11912def Strings(names, ctx=None):
11913 """Return a tuple of String constants. """
11914 ctx = _get_ctx(ctx)
11915 if isinstance(names, str):
11916 names = names.split(" ")
11917 return [String(name, ctx) for name in names]
11918
11919
11920def SubString(s, offset, length):
11921 """Extract substring or subsequence starting at offset.
11922
11923 This is a convenience function that redirects to Extract(s, offset, length).
11924
11925 >>> s = StringVal("hello world")
11926 >>> SubString(s, 6, 5) # Extract "world"
11927 str.substr("hello world", 6, 5)
11928 >>> simplify(SubString(StringVal("hello"), 1, 3))
11929 "ell"
11930 """
11931 return Extract(s, offset, length)
11932
11933
11934def SubSeq(s, offset, length):
11935 """Extract substring or subsequence starting at offset.
11936
11937 This is a convenience function that redirects to Extract(s, offset, length).
11938
11939 >>> s = StringVal("hello world")
11940 >>> SubSeq(s, 0, 5) # Extract "hello"
11941 str.substr("hello world", 0, 5)
11942 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11943 "stin"
11944 """
11945 return Extract(s, offset, length)
11946
11947
11948def Empty(s):
11949 """Create the empty sequence of the given sort
11950 >>> e = Empty(StringSort())
11951 >>> e2 = StringVal("")
11952 >>> print(e.eq(e2))
11953 True
11954 >>> e3 = Empty(SeqSort(IntSort()))
11955 >>> print(e3)
11956 Empty(Seq(Int))
11957 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11958 >>> print(e4)
11959 Empty(ReSort(Seq(Int)))
11960 """
11961 if isinstance(s, SeqSortRef):
11962 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11963 if isinstance(s, ReSortRef):
11964 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11965 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11966
11967
11968def Full(s):
11969 """Create the regular expression that accepts the universal language
11970 >>> e = Full(ReSort(SeqSort(IntSort())))
11971 >>> print(e)
11972 Full(ReSort(Seq(Int)))
11973 >>> e1 = Full(ReSort(StringSort()))
11974 >>> print(e1)
11975 Full(ReSort(String))
11976 """
11977 if isinstance(s, ReSortRef):
11978 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11979 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11980
11981
11982
11983def Unit(a):
11984 """Create a singleton sequence"""
11985 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11986
11987
11988def PrefixOf(a, b):
11989 """Check if 'a' is a prefix of 'b'
11990 >>> s1 = PrefixOf("ab", "abc")
11991 >>> simplify(s1)
11992 True
11993 >>> s2 = PrefixOf("bc", "abc")
11994 >>> simplify(s2)
11995 False
11996 """
11997 ctx = _get_ctx2(a, b)
11998 a = _coerce_seq(a, ctx)
11999 b = _coerce_seq(b, ctx)
12000 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12001
12002
12003def SuffixOf(a, b):
12004 """Check if 'a' is a suffix of 'b'
12005 >>> s1 = SuffixOf("ab", "abc")
12006 >>> simplify(s1)
12007 False
12008 >>> s2 = SuffixOf("bc", "abc")
12009 >>> simplify(s2)
12010 True
12011 """
12012 ctx = _get_ctx2(a, b)
12013 a = _coerce_seq(a, ctx)
12014 b = _coerce_seq(b, ctx)
12015 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12016
12017
12018def Contains(a, b):
12019 """Check if 'a' contains 'b'
12020 >>> s1 = Contains("abc", "ab")
12021 >>> simplify(s1)
12022 True
12023 >>> s2 = Contains("abc", "bc")
12024 >>> simplify(s2)
12025 True
12026 >>> x, y, z = Strings('x y z')
12027 >>> s3 = Contains(Concat(x,y,z), y)
12028 >>> simplify(s3)
12029 True
12030 """
12031 ctx = _get_ctx2(a, b)
12032 a = _coerce_seq(a, ctx)
12033 b = _coerce_seq(b, ctx)
12034 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12035
12036
12037def Replace(s, src, dst):
12038 """Replace the first occurrence of 'src' by 'dst' in 's'
12039 >>> r = Replace("aaa", "a", "b")
12040 >>> simplify(r)
12041 "baa"
12042 """
12043 ctx = _get_ctx2(dst, s)
12044 if ctx is None and is_expr(src):
12045 ctx = src.ctx
12046 src = _coerce_seq(src, ctx)
12047 dst = _coerce_seq(dst, ctx)
12048 s = _coerce_seq(s, ctx)
12049 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
12050
12051
12052def IndexOf(s, substr, offset=None):
12053 """Retrieve the index of substring within a string starting at a specified offset.
12054 >>> simplify(IndexOf("abcabc", "bc", 0))
12055 1
12056 >>> simplify(IndexOf("abcabc", "bc", 2))
12057 4
12058 """
12059 if offset is None:
12060 offset = IntVal(0)
12061 ctx = None
12062 if is_expr(offset):
12063 ctx = offset.ctx
12064 ctx = _get_ctx2(s, substr, ctx)
12065 s = _coerce_seq(s, ctx)
12066 substr = _coerce_seq(substr, ctx)
12067 if _is_int(offset):
12068 offset = IntVal(offset, ctx)
12069 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
12070
12071
12072def LastIndexOf(s, substr):
12073 """Retrieve the last index of substring within a string"""
12074 ctx = None
12075 ctx = _get_ctx2(s, substr, ctx)
12076 s = _coerce_seq(s, ctx)
12077 substr = _coerce_seq(substr, ctx)
12078 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
12079
12080
12081def Length(s):
12082 """Obtain the length of a sequence 's'
12083 >>> l = Length(StringVal("abc"))
12084 >>> simplify(l)
12085 3
12086 """
12087 s = _coerce_seq(s)
12088 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
12089
12090def SeqPower(s, n):
12091 """Concatenate the sequence 's' with itself 'n' times. It is the empty sequence for n <= 0
12092 >>> p = SeqPower(StringVal("ab"), 2)
12093 >>> simplify(p)
12094 "abab"
12095 """
12096 s = _coerce_seq(s)
12097 n = _py2expr(n, s.ctx)
12098 return SeqRef(Z3_mk_seq_power(s.ctx_ref(), s.as_ast(), n.as_ast()), s.ctx)
12099
12100def SeqMap(f, s):
12101 """Map function 'f' over sequence 's'"""
12102 ctx = _get_ctx2(f, s)
12103 s = _coerce_seq(s, ctx)
12104 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
12105
12106def SeqMapI(f, i, s):
12107 """Map function 'f' over sequence 's' at index 'i'"""
12108 ctx = _get_ctx2(f, s)
12109 s = _coerce_seq(s, ctx)
12110 if not is_expr(i):
12111 i = _py2expr(i)
12112 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
12113
12114def SeqFoldLeft(f, a, s):
12115 ctx = _get_ctx2(f, s)
12116 s = _coerce_seq(s, ctx)
12117 a = _py2expr(a)
12118 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
12119
12120def SeqFoldLeftI(f, i, a, s):
12121 ctx = _get_ctx2(f, s)
12122 s = _coerce_seq(s, ctx)
12123 a = _py2expr(a)
12124 i = _py2expr(i)
12125 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
12126
12127def StrToInt(s):
12128 """Convert string expression to integer
12129 >>> a = StrToInt("1")
12130 >>> simplify(1 == a)
12131 True
12132 >>> b = StrToInt("2")
12133 >>> simplify(1 == b)
12134 False
12135 >>> c = StrToInt(IntToStr(2))
12136 >>> simplify(1 == c)
12137 False
12138 """
12139 s = _coerce_seq(s)
12140 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
12141
12142
12143def IntToStr(s):
12144 """Convert integer expression to string"""
12145 if not is_expr(s):
12146 s = _py2expr(s)
12147 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
12148
12149
12150def StrToCode(s):
12151 """Convert a unit length string to integer code"""
12152 if not is_expr(s):
12153 s = _py2expr(s)
12154 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
12155
12156def StrFromCode(c):
12157 """Convert code to a string"""
12158 if not is_expr(c):
12159 c = _py2expr(c)
12160 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
12161
12162def Re(s, ctx=None):
12163 """The regular expression that accepts sequence 's'
12164 >>> s1 = Re("ab")
12165 >>> s2 = Re(StringVal("ab"))
12166 >>> s3 = Re(Unit(BoolVal(True)))
12167 """
12168 s = _coerce_seq(s, ctx)
12169 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12170
12171
12172# Regular expressions
12173
12174class ReSortRef(SortRef):
12175 """Regular expression sort."""
12176
12177 def basis(self):
12178 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12179
12180
12181def ReSort(s):
12182 if is_ast(s):
12183 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12184 if s is None or isinstance(s, Context):
12185 ctx = _get_ctx(s)
12186 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12187 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12188
12189
12190class ReRef(ExprRef):
12191 """Regular expressions."""
12192
12193 def __add__(self, other):
12194 return Union(self, other)
12195
12196
12197def is_re(s):
12198 return isinstance(s, ReRef)
12199
12200
12201def InRe(s, re):
12202 """Create regular expression membership test
12203 >>> re = Union(Re("a"),Re("b"))
12204 >>> print (simplify(InRe("a", re)))
12205 True
12206 >>> print (simplify(InRe("b", re)))
12207 True
12208 >>> print (simplify(InRe("c", re)))
12209 False
12210 """
12211 s = _coerce_seq(s, re.ctx)
12212 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12213
12214
12215def Union(*args):
12216 """Create union of regular expressions.
12217 >>> re = Union(Re("a"), Re("b"), Re("c"))
12218 >>> print (simplify(InRe("d", re)))
12219 False
12220 """
12221 args = _get_args(args)
12222 sz = len(args)
12223 if z3_debug():
12224 _z3_assert(sz > 0, "At least one argument expected.")
12225 arg0 = args[0]
12226 if is_finite_set(arg0):
12227 for a in args[1:]:
12228 if not is_finite_set(a):
12229 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12230 arg0 = arg0 | a
12231 return arg0
12232 if z3_debug():
12233 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12234 if sz == 1:
12235 return args[0]
12236 ctx = args[0].ctx
12237 v = (Ast * sz)()
12238 for i in range(sz):
12239 v[i] = args[i].as_ast()
12240 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12241
12242
12243def Intersect(*args):
12244 """Create intersection of regular expressions.
12245 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12246 """
12247 args = _get_args(args)
12248 sz = len(args)
12249 if z3_debug():
12250 _z3_assert(sz > 0, "At least one argument expected.")
12251 arg0 = args[0]
12252 if is_finite_set(arg0):
12253 for a in args[1:]:
12254 if not is_finite_set(a):
12255 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12256 arg0 = arg0 & a
12257 return arg0
12258 if z3_debug():
12259 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12260 if sz == 1:
12261 return args[0]
12262 ctx = args[0].ctx
12263 v = (Ast * sz)()
12264 for i in range(sz):
12265 v[i] = args[i].as_ast()
12266 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12267
12268
12269def Plus(re):
12270 """Create the regular expression accepting one or more repetitions of argument.
12271 >>> re = Plus(Re("a"))
12272 >>> print(simplify(InRe("aa", re)))
12273 True
12274 >>> print(simplify(InRe("ab", re)))
12275 False
12276 >>> print(simplify(InRe("", re)))
12277 False
12278 """
12279 if z3_debug():
12280 _z3_assert(is_expr(re), "expression expected")
12281 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12282
12283
12284def Option(re):
12285 """Create the regular expression that optionally accepts the argument.
12286 >>> re = Option(Re("a"))
12287 >>> print(simplify(InRe("a", re)))
12288 True
12289 >>> print(simplify(InRe("", re)))
12290 True
12291 >>> print(simplify(InRe("aa", re)))
12292 False
12293 """
12294 if z3_debug():
12295 _z3_assert(is_expr(re), "expression expected")
12296 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12297
12298
12299def Complement(re):
12300 """Create the complement regular expression."""
12301 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12302
12303
12304def Star(re):
12305 """Create the regular expression accepting zero or more repetitions of argument.
12306 >>> re = Star(Re("a"))
12307 >>> print(simplify(InRe("aa", re)))
12308 True
12309 >>> print(simplify(InRe("ab", re)))
12310 False
12311 >>> print(simplify(InRe("", re)))
12312 True
12313 """
12314 if z3_debug():
12315 _z3_assert(is_expr(re), "expression expected")
12316 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12317
12318
12319def Loop(re, lo, hi=0):
12320 """Create the regular expression accepting between a lower and upper bound repetitions
12321 >>> re = Loop(Re("a"), 1, 3)
12322 >>> print(simplify(InRe("aa", re)))
12323 True
12324 >>> print(simplify(InRe("aaaa", re)))
12325 False
12326 >>> print(simplify(InRe("", re)))
12327 False
12328 """
12329 if z3_debug():
12330 _z3_assert(is_expr(re), "expression expected")
12331 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12332
12333
12334def Range(lo, hi, ctx=None):
12335 """Create the range regular expression over two sequences of length 1
12336 >>> range = Range("a","z")
12337 >>> print(simplify(InRe("b", range)))
12338 True
12339 >>> print(simplify(InRe("bb", range)))
12340 False
12341 """
12342 lo = _coerce_seq(lo, ctx)
12343 hi = _coerce_seq(hi, ctx)
12344 if z3_debug():
12345 _z3_assert(is_expr(lo), "expression expected")
12346 _z3_assert(is_expr(hi), "expression expected")
12347 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12348
12349def Diff(a, b, ctx=None):
12350 """Create the difference regular expression
12351 """
12352 if z3_debug():
12353 _z3_assert(is_expr(a), "expression expected")
12354 _z3_assert(is_expr(b), "expression expected")
12355 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12356
12357def AllChar(regex_sort, ctx=None):
12358 """Create a regular expression that accepts all single character strings
12359 """
12360 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12361
12362# Special Relations
12363
12364
12365def PartialOrder(a, index):
12366 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12367
12368
12369def LinearOrder(a, index):
12370 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12371
12372
12373def TreeOrder(a, index):
12374 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12375
12376
12377def PiecewiseLinearOrder(a, index):
12378 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12379
12380
12381def TransitiveClosure(f):
12382 """Given a binary relation R, such that the two arguments have the same sort
12383 create the transitive closure relation R+.
12384 The transitive closure R+ is a new relation.
12385 """
12386 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12387
12388def to_Ast(ptr,):
12389 ast = Ast(ptr)
12390 super(ctypes.c_void_p, ast).__init__(ptr)
12391 return ast
12392
12393def to_ContextObj(ptr,):
12394 ctx = ContextObj(ptr)
12395 super(ctypes.c_void_p, ctx).__init__(ptr)
12396 return ctx
12397
12398def to_AstVectorObj(ptr,):
12399 v = AstVectorObj(ptr)
12400 super(ctypes.c_void_p, v).__init__(ptr)
12401 return v
12402
12403# NB. my-hacky-class only works for a single instance of OnClause
12404# it should be replaced with a proper correlation between OnClause
12405# and object references that can be passed over the FFI.
12406# for UserPropagator we use a global dictionary, which isn't great code.
12407
12408_my_hacky_class = None
12409def on_clause_eh(ctx, p, n, dep, clause):
12410 onc = _my_hacky_class
12411 p = _to_expr_ref(to_Ast(p), onc.ctx)
12412 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12413 deps = [dep[i] for i in range(n)]
12414 onc.on_clause(p, deps, clause)
12415
12416_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12417
12418class OnClause:
12419 def __init__(self, s, on_clause):
12420 self.s = s
12421 self.ctx = s.ctx
12422 self.on_clause = on_clause
12423 self.idx = 22
12424 global _my_hacky_class
12425 _my_hacky_class = self
12426 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12427
12428
12429class PropClosures:
12430 def __init__(self):
12431 self.bases = {}
12432 self.lock = None
12433
12434 def set_threaded(self):
12435 if self.lock is None:
12436 import threading
12437 self.lock = threading.Lock()
12438
12439 def get(self, ctx):
12440 if self.lock:
12441 with self.lock:
12442 r = self.bases[ctx]
12443 else:
12444 r = self.bases[ctx]
12445 return r
12446
12447 def set(self, ctx, r):
12448 if self.lock:
12449 with self.lock:
12450 self.bases[ctx] = r
12451 else:
12452 self.bases[ctx] = r
12453
12454 def insert(self, r):
12455 if self.lock:
12456 with self.lock:
12457 id = len(self.bases) + 3
12458 self.bases[id] = r
12459 else:
12460 id = len(self.bases) + 3
12461 self.bases[id] = r
12462 return id
12463
12464
12465_prop_closures = None
12466
12467
12468def ensure_prop_closures():
12469 global _prop_closures
12470 if _prop_closures is None:
12471 _prop_closures = PropClosures()
12472
12473
12474def user_prop_push(ctx, cb):
12475 prop = _prop_closures.get(ctx)
12476 prop.cb = cb
12477 prop.push()
12478
12479
12480def user_prop_pop(ctx, cb, num_scopes):
12481 prop = _prop_closures.get(ctx)
12482 prop.cb = cb
12483 prop.pop(num_scopes)
12484
12485
12486def user_prop_fresh(ctx, _new_ctx):
12487 _prop_closures.set_threaded()
12488 prop = _prop_closures.get(ctx)
12489 nctx = Context()
12490 Z3_del_context(nctx.ctx)
12491 new_ctx = to_ContextObj(_new_ctx)
12492 nctx.ctx = new_ctx
12493 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12494 nctx.owner = False
12495 new_prop = prop.fresh(nctx)
12496 _prop_closures.set(new_prop.id, new_prop)
12497 return new_prop.id
12498
12499
12500def user_prop_fixed(ctx, cb, id, value):
12501 prop = _prop_closures.get(ctx)
12502 old_cb = prop.cb
12503 prop.cb = cb
12504 id = _to_expr_ref(to_Ast(id), prop.ctx())
12505 value = _to_expr_ref(to_Ast(value), prop.ctx())
12506 prop.fixed(id, value)
12507 prop.cb = old_cb
12508
12509def user_prop_created(ctx, cb, id):
12510 prop = _prop_closures.get(ctx)
12511 old_cb = prop.cb
12512 prop.cb = cb
12513 id = _to_expr_ref(to_Ast(id), prop.ctx())
12514 prop.created(id)
12515 prop.cb = old_cb
12516
12517
12518def user_prop_final(ctx, cb):
12519 prop = _prop_closures.get(ctx)
12520 old_cb = prop.cb
12521 prop.cb = cb
12522 prop.final()
12523 prop.cb = old_cb
12524
12525def user_prop_eq(ctx, cb, x, y):
12526 prop = _prop_closures.get(ctx)
12527 old_cb = prop.cb
12528 prop.cb = cb
12529 x = _to_expr_ref(to_Ast(x), prop.ctx())
12530 y = _to_expr_ref(to_Ast(y), prop.ctx())
12531 prop.eq(x, y)
12532 prop.cb = old_cb
12533
12534def user_prop_diseq(ctx, cb, x, y):
12535 prop = _prop_closures.get(ctx)
12536 old_cb = prop.cb
12537 prop.cb = cb
12538 x = _to_expr_ref(to_Ast(x), prop.ctx())
12539 y = _to_expr_ref(to_Ast(y), prop.ctx())
12540 prop.diseq(x, y)
12541 prop.cb = old_cb
12542
12543def user_prop_decide(ctx, cb, t_ref, idx, phase):
12544 prop = _prop_closures.get(ctx)
12545 old_cb = prop.cb
12546 prop.cb = cb
12547 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12548 prop.decide(t, idx, phase)
12549 prop.cb = old_cb
12550
12551def user_prop_binding(ctx, cb, q_ref, inst_ref):
12552 prop = _prop_closures.get(ctx)
12553 old_cb = prop.cb
12554 prop.cb = cb
12555 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12556 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12557 r = prop.binding(q, inst)
12558 prop.cb = old_cb
12559 return r
12560
12561
12562_user_prop_push = Z3_push_eh(user_prop_push)
12563_user_prop_pop = Z3_pop_eh(user_prop_pop)
12564_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12565_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12566_user_prop_created = Z3_created_eh(user_prop_created)
12567_user_prop_final = Z3_final_eh(user_prop_final)
12568_user_prop_eq = Z3_eq_eh(user_prop_eq)
12569_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12570_user_prop_decide = Z3_decide_eh(user_prop_decide)
12571_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12572
12573
12574def PropagateFunction(name, *sig):
12575 """Create a function that gets tracked by user propagator.
12576 Every term headed by this function symbol is tracked.
12577 If a term is fixed and the fixed callback is registered a
12578 callback is invoked that the term headed by this function is fixed.
12579 """
12580 sig = _get_args(sig)
12581 if z3_debug():
12582 _z3_assert(len(sig) > 0, "At least two arguments expected")
12583 arity = len(sig) - 1
12584 rng = sig[arity]
12585 if z3_debug():
12586 _z3_assert(is_sort(rng), "Z3 sort expected")
12587 dom = (Sort * arity)()
12588 for i in range(arity):
12589 if z3_debug():
12590 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12591 dom[i] = sig[i].ast
12592 ctx = rng.ctx
12593 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12594
12595
12596
12597class UserPropagateBase:
12598
12599 #
12600 # Either solver is set or ctx is set.
12601 # Propagators that are created through callbacks
12602 # to "fresh" inherit the context of that is supplied
12603 # as argument to the callback.
12604 # This context should not be deleted. It is owned by the solver.
12605 #
12606 def __init__(self, s, ctx=None):
12607 assert s is None or ctx is None
12608 ensure_prop_closures()
12609 self.solver = s
12610 self._ctx = None
12611 self.fresh_ctx = None
12612 self.cb = None
12613 self.id = _prop_closures.insert(self)
12614 self.fixed = None
12615 self.final = None
12616 self.eq = None
12617 self.diseq = None
12618 self.decide = None
12619 self.created = None
12620 self.binding = None
12621 if ctx:
12622 self.fresh_ctx = ctx
12623 if s:
12624 Z3_solver_propagate_init(self.ctx_ref(),
12625 s.solver,
12626 ctypes.c_void_p(self.id),
12627 _user_prop_push,
12628 _user_prop_pop,
12629 _user_prop_fresh)
12630
12631 def __del__(self):
12632 if self._ctx:
12633 self._ctx.ctx = None
12634
12635 def ctx(self):
12636 if self.fresh_ctx:
12637 return self.fresh_ctx
12638 else:
12639 return self.solver.ctx
12640
12641 def ctx_ref(self):
12642 return self.ctx().ref()
12643
12644 def add_fixed(self, fixed):
12645 if self.fixed:
12646 raise Z3Exception("fixed callback already registered")
12647 if self._ctx:
12648 raise Z3Exception("context already initialized")
12649 if self.solver:
12650 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12651 self.fixed = fixed
12652
12653 def add_created(self, created):
12654 if self.created:
12655 raise Z3Exception("created callback already registered")
12656 if self._ctx:
12657 raise Z3Exception("context already initialized")
12658 if self.solver:
12659 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12660 self.created = created
12661
12662 def add_final(self, final):
12663 if self.final:
12664 raise Z3Exception("final callback already registered")
12665 if self._ctx:
12666 raise Z3Exception("context already initialized")
12667 if self.solver:
12668 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12669 self.final = final
12670
12671 def add_eq(self, eq):
12672 if self.eq:
12673 raise Z3Exception("eq callback already registered")
12674 if self._ctx:
12675 raise Z3Exception("context already initialized")
12676 if self.solver:
12677 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12678 self.eq = eq
12679
12680 def add_diseq(self, diseq):
12681 if self.diseq:
12682 raise Z3Exception("diseq callback already registered")
12683 if self._ctx:
12684 raise Z3Exception("context already initialized")
12685 if self.solver:
12686 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12687 self.diseq = diseq
12688
12689 def add_decide(self, decide):
12690 if self.decide:
12691 raise Z3Exception("decide callback already registered")
12692 if self._ctx:
12693 raise Z3Exception("context already initialized")
12694 if self.solver:
12695 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12696 self.decide = decide
12697
12698 def add_on_binding(self, binding):
12699 if self.binding:
12700 raise Z3Exception("binding callback already registered")
12701 if self._ctx:
12702 raise Z3Exception("context already initialized")
12703 if self.solver:
12704 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12705 self.binding = binding
12706
12707 def push(self):
12708 raise Z3Exception("push needs to be overwritten")
12709
12710 def pop(self, num_scopes):
12711 raise Z3Exception("pop needs to be overwritten")
12712
12713 def fresh(self, new_ctx):
12714 raise Z3Exception("fresh needs to be overwritten")
12715
12716 def add(self, e):
12717 if self._ctx:
12718 raise Z3Exception("context already initialized")
12719 if self.solver:
12720 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12721 else:
12722 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12723
12724 #
12725 # Tell the solver to perform the next split on a given term
12726 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12727 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12728 #
12729 def next_split(self, t, idx, phase):
12730 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12731
12732 #
12733 # Propagation can only be invoked as during a fixed or final callback.
12734 #
12735 def propagate(self, e, ids, eqs=[]):
12736 _ids, num_fixed = _to_ast_array(ids)
12737 num_eqs = len(eqs)
12738 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12739 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12740 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12741 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12742
12743 def conflict(self, deps = [], eqs = []):
12744 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
12745
12746
12747class FiniteFieldSortRef(SortRef):
12748 """A prime field. Use SolverFor('QF_FF') for incremental field solving."""
12749 def size(self):
12750 return int(Z3_get_finite_field_sort_size(self.ctx_ref(), self.ast))
12751
12752 def cast(self, value):
12753 if is_expr(value):
12754 if not self.eq(value.sort()):
12755 raise Z3Exception("finite-field sort mismatch")
12756 return value
12757 return FiniteFieldVal(value, self)
12758
12759
12760class FiniteFieldRef(ExprRef):
12761 def sort(self):
12762 return FiniteFieldSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
12763
12764 def as_long(self):
12765 if not Z3_is_numeral_ast(self.ctx_ref(), self.as_ast()):
12766 raise Z3Exception("finite-field numeral expected")
12767 return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast()))
12768
12769 def _binary(self, other, operation):
12770 other = self.sort().cast(other)
12771 args = (Ast * 2)(self.as_ast(), other.as_ast())
12772 return FiniteFieldRef(operation(self.ctx_ref(), 2, args), self.ctx)
12773
12774 def __add__(self, other):
12775 return self._binary(other, Z3_mk_ff_add)
12776
12777 def __radd__(self, other):
12778 return self + other
12779
12780 def __mul__(self, other):
12781 return self._binary(other, Z3_mk_ff_mul)
12782
12783 def __rmul__(self, other):
12784 return self * other
12785
12786 def __neg__(self):
12787 return FiniteFieldRef(Z3_mk_ff_neg(self.ctx_ref(), self.as_ast()), self.ctx)
12788
12789 def __sub__(self, other):
12790 return self + -self.sort().cast(other)
12791
12792 def __rsub__(self, other):
12793 return self.sort().cast(other) + -self
12794
12795 def __pow__(self, n):
12796 if not isinstance(n, int) or n < 0:
12797 raise Z3Exception("finite-field exponent must be a nonnegative integer")
12798 result, base = FiniteFieldVal(1, self.sort()), self
12799 while n:
12800 if n & 1:
12801 result = result * base
12802 n >>= 1
12803 if n:
12804 base = base * base
12805 return result
12806
12807
12808def FiniteFieldSort(prime, ctx=None):
12809 ctx = _get_ctx(ctx)
12810 return FiniteFieldSortRef(Z3_mk_finite_field_sort(ctx.ref(), str(prime)), ctx)
12811
12812
12813def FiniteFieldVal(value, field, ctx=None):
12814 if not isinstance(field, FiniteFieldSortRef):
12815 field = FiniteFieldSort(field, ctx)
12816 if not isinstance(value, (int, str)):
12817 raise Z3Exception("finite-field value must be an integer")
12818 return FiniteFieldRef(Z3_mk_numeral(field.ctx_ref(), str(value), field.ast), field.ctx)
12819
12820
12821def FiniteFieldElem(name, field, ctx=None):
12822 if not isinstance(field, FiniteFieldSortRef):
12823 field = FiniteFieldSort(field, ctx)
12824 return Const(name, field)
12825
12826
12827def FiniteFieldElems(names, field, ctx=None):
12828 if not isinstance(field, FiniteFieldSortRef):
12829 field = FiniteFieldSort(field, ctx)
12830 return [Const(name, field) for name in (names.split() if isinstance(names, str) else names)]
12831
12832
12833def FiniteFieldBitsum(*args):
12834 args = _get_args(args)
12835 if len(args) < 2 or not isinstance(args[0], FiniteFieldRef):
12836 raise Z3Exception("bitsum needs at least two field arguments")
12837 field = args[0].sort()
12838 values = [field.cast(a) for a in args]
12839 raw = (Ast * len(values))(*[a.as_ast() for a in values])
12840 return FiniteFieldRef(Z3_mk_ff_bitsum(field.ctx_ref(), len(values), raw), field.ctx)
approx(self, precision=10)
Definition z3py.py:3273
as_decimal(self, prec)
Definition z3py.py:3285
__rmod__(self, other)
Definition z3py.py:2744
__mod__(self, other)
Definition z3py.py:2729
__pow__(self, other)
Definition z3py.py:2653
__gt__(self, other)
Definition z3py.py:2802
__lt__(self, other)
Definition z3py.py:2789
__rtruediv__(self, other)
Definition z3py.py:2725
__rmul__(self, other)
Definition z3py.py:2620
__abs__(self)
Definition z3py.py:2828
__rsub__(self, other)
Definition z3py.py:2643
__add__(self, other)
Definition z3py.py:2582
__sub__(self, other)
Definition z3py.py:2630
is_real(self)
Definition z3py.py:2571
is_int(self)
Definition z3py.py:2557
__radd__(self, other)
Definition z3py.py:2595
__truediv__(self, other)
Definition z3py.py:2704
__le__(self, other)
Definition z3py.py:2776
__rpow__(self, other)
Definition z3py.py:2667
__pos__(self)
Definition z3py.py:2767
sort(self)
Definition z3py.py:2547
__mul__(self, other)
Definition z3py.py:2605
__rdiv__(self, other)
Definition z3py.py:2708
__ge__(self, other)
Definition z3py.py:2815
__neg__(self)
Definition z3py.py:2756
__div__(self, other)
Definition z3py.py:2681
Arithmetic.
Definition z3py.py:2452
subsort(self, other)
Definition z3py.py:2486
cast(self, val)
Definition z3py.py:2490
domain(self)
Definition z3py.py:4903
domain_n(self, i)
Definition z3py.py:4912
__getitem__(self, arg)
Definition z3py.py:4925
range(self)
Definition z3py.py:4916
sort(self)
Definition z3py.py:4894
default(self)
Definition z3py.py:4937
domain_n(self, i)
Definition z3py.py:4876
erase(self, k)
Definition z3py.py:6818
__deepcopy__(self, memo={})
Definition z3py.py:6755
__init__(self, m=None, ctx=None)
Definition z3py.py:6744
__repr__(self)
Definition z3py.py:6815
__len__(self)
Definition z3py.py:6762
keys(self)
Definition z3py.py:6847
__setitem__(self, k, v)
Definition z3py.py:6799
__contains__(self, key)
Definition z3py.py:6775
__del__(self)
Definition z3py.py:6758
__getitem__(self, key)
Definition z3py.py:6788
reset(self)
Definition z3py.py:6832
__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:6724
translate(self, other_ctx)
Definition z3py.py:6705
__repr__(self)
Definition z3py.py:6727
__len__(self)
Definition z3py.py:6597
__init__(self, v=None, ctx=None)
Definition z3py.py:6582
push(self, v)
Definition z3py.py:6657
__getitem__(self, i)
Definition z3py.py:6610
sexpr(self)
Definition z3py.py:6730
__del__(self)
Definition z3py.py:6593
__setitem__(self, i, v)
Definition z3py.py:6639
__contains__(self, item)
Definition z3py.py:6682
__copy__(self)
Definition z3py.py:6721
resize(self, sz)
Definition z3py.py:6669
as_binary_string(self)
Definition z3py.py:4216
as_signed_long(self)
Definition z3py.py:4190
as_string(self)
Definition z3py.py:4213
__and__(self, other)
Definition z3py.py:3880
__rmod__(self, other)
Definition z3py.py:4021
__rrshift__(self, other)
Definition z3py.py:4147
__mod__(self, other)
Definition z3py.py:4000
__or__(self, other)
Definition z3py.py:3857
__rlshift__(self, other)
Definition z3py.py:4161
__gt__(self, other)
Definition z3py.py:4071
__lt__(self, other)
Definition z3py.py:4055
__invert__(self)
Definition z3py.py:3946
__rtruediv__(self, other)
Definition z3py.py:3996
__rmul__(self, other)
Definition z3py.py:3824
__rxor__(self, other)
Definition z3py.py:3916
__ror__(self, other)
Definition z3py.py:3870
__rsub__(self, other)
Definition z3py.py:3847
__add__(self, other)
Definition z3py.py:3788
__sub__(self, other)
Definition z3py.py:3834
__radd__(self, other)
Definition z3py.py:3801
size(self)
Definition z3py.py:3777
__rand__(self, other)
Definition z3py.py:3893
__truediv__(self, other)
Definition z3py.py:3976
__le__(self, other)
Definition z3py.py:4039
__xor__(self, other)
Definition z3py.py:3903
__lshift__(self, other)
Definition z3py.py:4133
__pos__(self)
Definition z3py.py:3926
sort(self)
Definition z3py.py:3766
__mul__(self, other)
Definition z3py.py:3811
__rdiv__(self, other)
Definition z3py.py:3980
__ge__(self, other)
Definition z3py.py:4087
__neg__(self)
Definition z3py.py:3935
__rshift__(self, other)
Definition z3py.py:4103
__div__(self, other)
Definition z3py.py:3957
Bit-Vectors.
Definition z3py.py:3719
subsort(self, other)
Definition z3py.py:3731
cast(self, val)
Definition z3py.py:3734
__and__(self, other)
Definition z3py.py:1703
__or__(self, other)
Definition z3py.py:1706
__invert__(self)
Definition z3py.py:1712
__rmul__(self, other)
Definition z3py.py:1689
__add__(self, other)
Definition z3py.py:1681
py_value(self)
Definition z3py.py:1715
__radd__(self, other)
Definition z3py.py:1686
__xor__(self, other)
Definition z3py.py:1709
sort(self)
Definition z3py.py:1678
__mul__(self, other)
Definition z3py.py:1692
Booleans.
Definition z3py.py:1639
subsort(self, other)
Definition z3py.py:1665
is_bool(self)
Definition z3py.py:1671
cast(self, val)
Definition z3py.py:1642
__deepcopy__(self, memo={})
Definition z3py.py:7614
__eq__(self, other)
Definition z3py.py:7617
__ne__(self, other)
Definition z3py.py:7620
__init__(self, r)
Definition z3py.py:7611
real_part(self)
Definition z3py.py:3327
imag_part(self)
Definition z3py.py:3330
subsort(self, other)
Definition z3py.py:3307
cast(self, val)
Definition z3py.py:3310
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
__deepcopy__(self, memo={})
Definition z3py.py:5670
create(self)
Definition z3py.py:5709
__init__(self, name, ctx=None)
Definition z3py.py:5665
__repr__(self)
Definition z3py.py:5706
declare(self, name, *args)
Definition z3py.py:5685
create_polymorphic(self, type_params)
Definition z3py.py:5725
declare_core(self, name, rec_name, *args)
Definition z3py.py:5675
update_field(self, field_accessor, new_value)
Definition z3py.py:6034
constructor(self, idx)
Definition z3py.py:5946
accessor(self, i, j)
Definition z3py.py:5993
num_constructors(self)
Definition z3py.py:5933
recognizer(self, idx)
Definition z3py.py:5965
Expressions.
Definition z3py.py:1024
update(self, *args)
Definition z3py.py:1180
as_ast(self)
Definition z3py.py:1035
__hash__(self)
Definition z3py.py:1081
kind(self)
Definition z3py.py:1121
children(self)
Definition z3py.py:1165
serialize(self)
Definition z3py.py:1207
get_id(self)
Definition z3py.py:1038
num_args(self)
Definition z3py.py:1128
__eq__(self, other)
Definition z3py.py:1064
__ne__(self, other)
Definition z3py.py:1085
from_string(self, s)
Definition z3py.py:1204
sort_kind(self)
Definition z3py.py:1053
arg(self, idx)
Definition z3py.py:1144
sort(self)
Definition z3py.py:1041
params(self)
Definition z3py.py:1103
decl(self)
Definition z3py.py:1106
__and__(self, other)
Definition z3py.py:5485
__or__(self, other)
Definition z3py.py:5481
__sub__(self, other)
Definition z3py.py:5489
Finite Sets.
Definition z3py.py:5413
subsort(self, other)
Definition z3py.py:5435
cast(self, val)
Definition z3py.py:5420
Function Declarations.
Definition z3py.py:781
as_func_decl(self)
Definition z3py.py:795
domain(self, i)
Definition z3py.py:819
as_ast(self)
Definition z3py.py:789
__call__(self, *args)
Definition z3py.py:882
arity(self)
Definition z3py.py:809
get_id(self)
Definition z3py.py:792
range(self)
Definition z3py.py:831
params(self)
Definition z3py.py:854
Definition z3py.py:6866
__deepcopy__(self, memo={})
Definition z3py.py:6874
ctx
Definition z3py.py:6871
__repr__(self)
Definition z3py.py:6971
num_args(self)
Definition z3py.py:6881
entry
Definition z3py.py:6870
value(self)
Definition z3py.py:6930
__init__(self, entry, ctx)
Definition z3py.py:6869
__del__(self)
Definition z3py.py:6877
as_list(self)
Definition z3py.py:6952
arg_value(self, idx)
Definition z3py.py:6899
__deepcopy__(self, memo={})
Definition z3py.py:7069
translate(self, other_ctx)
Definition z3py.py:7061
arity(self)
Definition z3py.py:7027
__repr__(self)
Definition z3py.py:7089
num_entries(self)
Definition z3py.py:7011
__init__(self, f, ctx)
Definition z3py.py:6978
__del__(self)
Definition z3py.py:6984
as_list(self)
Definition z3py.py:7072
else_value(self)
Definition z3py.py:6988
entry(self, idx)
Definition z3py.py:7041
__copy__(self)
Definition z3py.py:7066
__deepcopy__(self, memo={})
Definition z3py.py:6527
get(self, i)
Definition z3py.py:6383
prec(self)
Definition z3py.py:6327
translate(self, target)
Definition z3py.py:6501
append(self, *args)
Definition z3py.py:6428
as_expr(self)
Definition z3py.py:6550
assert_exprs(self, *args)
Definition z3py.py:6413
__repr__(self)
Definition z3py.py:6490
__len__(self)
Definition z3py.py:6370
inconsistent(self)
Definition z3py.py:6309
dimacs(self, include_names=True)
Definition z3py.py:6497
__getitem__(self, arg)
Definition z3py.py:6396
size(self)
Definition z3py.py:6357
precision(self)
Definition z3py.py:6348
simplify(self, *arguments, **keywords)
Definition z3py.py:6530
sexpr(self)
Definition z3py.py:6493
add(self, *args)
Definition z3py.py:6450
__del__(self)
Definition z3py.py:6287
convert_model(self, model)
Definition z3py.py:6461
insert(self, *args)
Definition z3py.py:6439
depth(self)
Definition z3py.py:6291
__init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition z3py.py:6277
__copy__(self)
Definition z3py.py:6524
as_binary_string(self)
Definition z3py.py:3158
py_value(self)
Definition z3py.py:3166
as_long(self)
Definition z3py.py:3137
as_string(self)
Definition z3py.py:3150
__deepcopy__(self, memo={})
Definition z3py.py:7437
eval(self, t, model_completion=False)
Definition z3py.py:7113
translate(self, target)
Definition z3py.py:7402
__getitem__(self, idx)
Definition z3py.py:7314
num_sorts(self)
Definition z3py.py:7239
get_universe(self, s)
Definition z3py.py:7294
get_sort(self, idx)
Definition z3py.py:7254
project(self, vars, fml)
Definition z3py.py:7410
__repr__(self)
Definition z3py.py:7106
__len__(self)
Definition z3py.py:7170
get_interp(self, decl)
Definition z3py.py:7187
__init__(self, m, ctx)
Definition z3py.py:7096
sexpr(self)
Definition z3py.py:7109
sorts(self)
Definition z3py.py:7277
__del__(self)
Definition z3py.py:7102
decls(self)
Definition z3py.py:7361
project_with_witness(self, vars, fml)
Definition z3py.py:7422
update_value(self, x, value)
Definition z3py.py:7380
evaluate(self, t, model_completion=False)
Definition z3py.py:7144
__copy__(self)
Definition z3py.py:7434
__deepcopy__(self, memo={})
Definition z3py.py:6221
__init__(self, descr, ctx=None)
Definition z3py.py:6215
get_kind(self, n)
Definition z3py.py:6243
get_documentation(self, n)
Definition z3py.py:6248
__getitem__(self, arg)
Definition z3py.py:6253
get_name(self, i)
Definition z3py.py:6238
Parameter Sets.
Definition z3py.py:6142
__deepcopy__(self, memo={})
Definition z3py.py:6156
validate(self, ds)
Definition z3py.py:6183
__repr__(self)
Definition z3py.py:6180
__init__(self, ctx=None, params=None)
Definition z3py.py:6148
set(self, name, val)
Definition z3py.py:6163
__del__(self)
Definition z3py.py:6159
Patterns.
Definition z3py.py:2075
as_ast(self)
Definition z3py.py:2080
get_id(self)
Definition z3py.py:2083
Quantifiers.
Definition z3py.py:2142
num_no_patterns(self)
Definition z3py.py:2260
no_pattern(self, idx)
Definition z3py.py:2264
num_patterns(self)
Definition z3py.py:2230
var_name(self, idx)
Definition z3py.py:2293
__getitem__(self, arg)
Definition z3py.py:2199
var_sort(self, idx)
Definition z3py.py:2309
pattern(self, idx)
Definition z3py.py:2242
numerator_as_long(self)
Definition z3py.py:3199
is_int_value(self)
Definition z3py.py:3229
as_fraction(self)
Definition z3py.py:3257
py_value(self)
Definition z3py.py:3266
numerator(self)
Definition z3py.py:3173
is_real(self)
Definition z3py.py:3226
as_long(self)
Definition z3py.py:3232
is_int(self)
Definition z3py.py:3223
denominator_as_long(self)
Definition z3py.py:3212
as_string(self)
Definition z3py.py:3248
denominator(self)
Definition z3py.py:3188
as_decimal(self, prec)
Definition z3py.py:3236
__init__(self, c, ctx)
Definition z3py.py:5743
__init__(self, c, ctx)
Definition z3py.py:5755
Strings, Sequences and Regular expressions.
Definition z3py.py:11694
__init__(self, solver=None, ctx=None, logFile=None)
Definition z3py.py:7658
assert_and_track(self, a, p)
Definition z3py.py:7827
num_scopes(self)
Definition z3py.py:7739
append(self, *args)
Definition z3py.py:7805
__iadd__(self, fml)
Definition z3py.py:7801
backtrack_level
Definition z3py.py:7661
pop(self, num=1)
Definition z3py.py:7717
import_model_converter(self, other)
Definition z3py.py:7905
assert_exprs(self, *args)
Definition z3py.py:7771
model(self)
Definition z3py.py:7886
set(self, *args, **keys)
Definition z3py.py:7682
__enter__(self)
Definition z3py.py:7675
add(self, *args)
Definition z3py.py:7790
__del__(self)
Definition z3py.py:7671
insert(self, *args)
Definition z3py.py:7816
check(self, *assumptions)
Definition z3py.py:7857
push(self)
Definition z3py.py:7695
__exit__(self, *exc_info)
Definition z3py.py:7679
reset(self)
Definition z3py.py:7757
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:7467
__deepcopy__(self, memo={})
Definition z3py.py:7475
__getattr__(self, name)
Definition z3py.py:7570
__getitem__(self, idx)
Definition z3py.py:7514
__init__(self, stats, ctx)
Definition z3py.py:7470
__repr__(self)
Definition z3py.py:7482
__len__(self)
Definition z3py.py:7500
__del__(self)
Definition z3py.py:7478
get_key_value(self, key)
Definition z3py.py:7550
subsort(self, other)
Definition z3py.py:757
cast(self, val)
Definition z3py.py:760
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_sort Z3_API Z3_mk_complex_sort(Z3_context c)
Create the Complex sort. Complex numbers are pairs of Reals.
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_ast Z3_API Z3_mk_complex(Z3_context c, Z3_ast re, Z3_ast im)
Create a complex number with the given real and imaginary components. Integer components are coerced ...
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_imag_part(Z3_context c, Z3_ast z)
Return the imaginary component of a Complex expression.
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_mk_real_part(Z3_context c, Z3_ast z)
Return the real component of a Complex expression.
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:3395
RotateRight(a, b)
Definition z3py.py:4651
_symbol2py(ctx, s)
Definition z3py.py:140
is_complex(a)
Definition z3py.py:3339
BitVecVal(val, bv, ctx=None)
Definition z3py.py:4301
BVSNegNoOverflow(a)
Definition z3py.py:4837
SetAdd(s, e)
Definition z3py.py:5331
SetSort(s)
Sets.
Definition z3py.py:5274
_coerce_exprs(a, b, ctx=None)
Definition z3py.py:1316
UGT(a, b)
Definition z3py.py:4522
is_probe(p)
Definition z3py.py:9564
SetDel(s, e)
Definition z3py.py:5344
bool is_le(Any a)
Definition z3py.py:3044
BoolSort(ctx=None)
Definition z3py.py:1845
is_bv_sort(s)
Definition z3py.py:3752
ComplexSort(ctx=None)
Definition z3py.py:3344
_ctx_from_ast_args(*args)
Definition z3py.py:542
RatVal(a, b, ctx=None)
Definition z3py.py:3489
_to_func_decl_ref(a, ctx)
Definition z3py.py:968
SetUnion(*args)
Definition z3py.py:5299
_valid_accessor(acc)
Datatypes.
Definition z3py.py:5629
BitVec(name, bv, ctx=None)
Definition z3py.py:4318
EmptySet(s)
Definition z3py.py:5279
BVMulNoUnderflow(a, b)
Definition z3py.py:4851
CreateDatatypes(*ds)
Definition z3py.py:5764
is_func_decl(a)
Definition z3py.py:913
FiniteSetUnion(s1, s2)
Definition z3py.py:5522
get_as_array_func(n)
Definition z3py.py:7454
Distinct(*args)
Definition z3py.py:1528
RecAddDefinition(f, args, body)
Definition z3py.py:990
ToInt(a)
Definition z3py.py:3652
Implies(a, b, ctx=None)
Definition z3py.py:1939
UGE(a, b)
Definition z3py.py:4504
Complex(name, ctx=None)
Definition z3py.py:3350
Ext(a, b)
Definition z3py.py:5213
_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:4463
RealSort(ctx=None)
Definition z3py.py:3429
IsSubset(a, b)
Definition z3py.py:5393
DeclareTypeVar(name, ctx=None)
Definition z3py.py:764
_get_args_ast_list(args)
Definition z3py.py:168
bool is_to_real(Any a)
Definition z3py.py:3104
_to_ref_array(ref, args)
Definition z3py.py:562
get_map_func(a)
Definition z3py.py:5019
is_finite_set(a)
Definition z3py.py:5454
_z3_check_cint_overflow(n, name)
Definition z3py.py:118
bool is_and(Any a)
Definition z3py.py:1775
TupleSort(name, sorts, ctx=None)
Definition z3py.py:6085
_coerce_expr_list(alist, ctx=None)
Definition z3py.py:1351
is_select(a)
Definition z3py.py:5243
SignExt(n, a)
Definition z3py.py:4667
Int(name, ctx=None)
Definition z3py.py:3522
Bools(names, ctx=None)
Definition z3py.py:1894
_probe_and(args, ctx)
Definition z3py.py:9631
Int2BV(a, num_bits)
Definition z3py.py:4277
Lambda(vs, body)
Definition z3py.py:2425
_to_param_value(val)
Definition z3py.py:178
FreshFunction(*sig)
Definition z3py.py:949
RealVector(prefix, sz, ctx=None)
Definition z3py.py:3603
BVRedOr(a)
Definition z3py.py:4756
is_finite_set_sort(s)
Definition z3py.py:5465
SRem(a, b)
Definition z3py.py:4582
FiniteSetFilter(f, set)
Definition z3py.py:5601
SortRef _sort(Context ctx, Any a)
Definition z3py.py:732
set_option(*args, **kws)
Definition z3py.py:328
ExprRef RealVar(int idx, ctx=None)
Definition z3py.py:1611
bool is_sub(Any a)
Definition z3py.py:2991
is_bv(a)
Definition z3py.py:4225
SetDifference(a, b)
Definition z3py.py:5367
bool is_arith_sort(Any s)
Definition z3py.py:2528
BitVecs(names, bv, ctx=None)
Definition z3py.py:4342
_check_same_sort(a, b, ctx=None)
Definition z3py.py:1303
bool is_mod(Any a)
Definition z3py.py:3032
BoolVector(prefix, sz, ctx=None)
Definition z3py.py:1910
FiniteSetEmpty(set_sort)
Definition z3py.py:5503
_has_probe(args)
Definition z3py.py:1995
IsMember(e, s)
Definition z3py.py:5380
get_param(name)
Definition z3py.py:334
BVAddNoUnderflow(a, b)
Definition z3py.py:4809
deserialize(st)
Definition z3py.py:1213
bool is_not(Any a)
Definition z3py.py:1811
BvXnor(a, b)
Definition z3py.py:4789
ComplexVal(real, imag=0, ctx=None)
Definition z3py.py:3363
FiniteSetMap(f, set)
Definition z3py.py:5588
Extract(high, low, a)
Definition z3py.py:4409
Function(name, *sig)
Definition z3py.py:926
get_version()
Definition z3py.py:100
FreshConst(sort, prefix="c")
Definition z3py.py:1588
ULT(a, b)
Definition z3py.py:4486
EnumSort(name, values, ctx=None)
Definition z3py.py:6109
is_complex_sort(s)
Definition z3py.py:3334
bool is_is_int(Any a)
Definition z3py.py:3092
_to_int_str(val)
Definition z3py.py:3446
is_algebraic_value(a)
Definition z3py.py:2953
is_bv_value(a)
Definition z3py.py:4239
BVSDivNoOverflow(a, b)
Definition z3py.py:4830
bool is_eq(Any a)
Definition z3py.py:1823
Context main_ctx()
Definition z3py.py:266
CreatePolymorphicDatatype(d, type_params)
Definition z3py.py:5860
BvNand(a, b)
Definition z3py.py:4763
SetIntersect(*args)
Definition z3py.py:5315
simplify(a, *arguments, **keywords)
Utils.
Definition z3py.py:9698
BV2Int(a, is_signed=False)
Definition z3py.py:4254
FreshInt(prefix="x", ctx=None)
Definition z3py.py:3561
_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:3119
RealPart(value)
Definition z3py.py:3383
is_map(a)
Definition z3py.py:4994
Context _get_ctx(ctx)
Definition z3py.py:287
Or(*args)
Definition z3py.py:2036
is_re(s)
Definition z3py.py:12197
FiniteSetIntersect(s1, s2)
Definition z3py.py:5533
args2params(arguments, keywords, ctx=None)
Definition z3py.py:6188
bool is_idiv(Any a)
Definition z3py.py:3020
Consts(names, sort)
Definition z3py.py:1573
Cond(p, t1, t2, ctx=None)
Definition z3py.py:9681
_to_pattern(arg)
Definition z3py.py:2129
RealVarVector(int n, ctx=None)
Definition z3py.py:1621
is_arith(a)
Definition z3py.py:2840
bool is_true(Any a)
Definition z3py.py:1743
bool is_false(Any a)
Definition z3py.py:1761
bool is_int(a)
Definition z3py.py:2861
If(a, b, c, ctx=None)
Definition z3py.py:1505
bool eq(AstRef a, AstRef b)
Definition z3py.py:503
is_app_of(a, k)
Definition z3py.py:1492
is_app(a)
Definition z3py.py:1389
bool is_add(Any a)
Definition z3py.py:2967
z3_error_handler(c, e)
Definition z3py.py:184
None reset_params()
Definition z3py.py:322
Reals(names, ctx=None)
Definition z3py.py:3588
is_int_value(a)
Definition z3py.py:2907
set_param(*args, **kws)
Definition z3py.py:298
is_pattern(a)
Definition z3py.py:2087
_coerce_seq(s, ctx=None)
Definition z3py.py:11848
bool is_distinct(Any a)
Definition z3py.py:1833
bool is_lt(Any a)
Definition z3py.py:3056
FiniteSetRange(low, high)
Definition z3py.py:5614
ULE(a, b)
Definition z3py.py:4468
is_real(a)
Definition z3py.py:2880
Abs(arg)
Definition z3py.py:9859
FullSet(s)
Definition z3py.py:5290
to_symbol(s, ctx=None)
Definition z3py.py:132
FiniteSetMember(elem, set)
Definition z3py.py:5555
bool is_mul(Any a)
Definition z3py.py:2979
bool is_ast(Any a)
Definition z3py.py:482
_get_args(args)
Definition z3py.py:152
Singleton(elem)
Definition z3py.py:5513
And(*args)
Definition z3py.py:2003
RepeatBitVec(n, a)
Definition z3py.py:4725
FiniteSetDifference(s1, s2)
Definition z3py.py:5544
get_version_string()
Definition z3py.py:91
FreshReal(prefix="b", ctx=None)
Definition z3py.py:3618
Array(name, *sorts)
Definition z3py.py:5078
Concat(*args)
Definition z3py.py:4363
_reduce(func, sequence, initial)
Definition z3py.py:1344
_is_algebraic(ctx, a)
Definition z3py.py:2903
Ints(names, ctx=None)
Definition z3py.py:3535
Select(a, *args)
Definition z3py.py:5152
Const(name, sort)
Definition z3py.py:1561
is_array_sort(a)
Definition z3py.py:4950
bool is_div(Any a)
Definition z3py.py:3003
ExprRef Var(int idx, SortRef s)
Definition z3py.py:1596
BVAddNoOverflow(a, b, signed)
Definition z3py.py:4802
BvNor(a, b)
Definition z3py.py:4776
Real(name, ctx=None)
Definition z3py.py:3575
FreshBool(prefix="b", ctx=None)
Definition z3py.py:1925
BitVecSort(sz, ctx=None)
Definition z3py.py:4286
open_log(fname)
Definition z3py.py:122
RecFunction(name, *sig)
Definition z3py.py:972
FiniteSetSize(set)
Definition z3py.py:5567
bool is_ge(Any a)
Definition z3py.py:3068
Model(ctx=None, eval={})
Definition z3py.py:7441
BVSubNoOverflow(a, b)
Definition z3py.py:4816
bool is_gt(Any a)
Definition z3py.py:3080
In(elem, set)
Definition z3py.py:5564
is_default(a)
Definition z3py.py:5010
is_K(a)
Definition z3py.py:4981
Bool(name, ctx=None)
Definition z3py.py:1882
_is_int(v)
Definition z3py.py:76
is_const_array(a)
Definition z3py.py:4968
Sqrt(a, ctx=None)
Definition z3py.py:3687
FiniteSetSort(elem_sort)
Definition z3py.py:5494
Default(a)
Definition z3py.py:5124
_ctx_from_ast_arg_list(args, default_ctx=None)
Definition z3py.py:528
SetComplement(s)
Definition z3py.py:5357
is_as_array(n)
Definition z3py.py:7449
is_store(a)
Definition z3py.py:5256
FiniteSetSubset(s1, s2)
Definition z3py.py:5577
bool is_or(Any a)
Definition z3py.py:1787
is_quantifier(a)
Definition z3py.py:2337
_mk_bin(f, a, b)
Definition z3py.py:1552
K(dom, v)
Definition z3py.py:5191
Xor(a, b, ctx=None)
Definition z3py.py:1953
Store(a, *args)
Definition z3py.py:5135
bool is_array(Any a)
Definition z3py.py:4954
mk_not(a)
Definition z3py.py:1988
is_expr(a)
Definition z3py.py:1366
_array_select(ar, arg)
Definition z3py.py:4941
is_const(a)
Definition z3py.py:1415
BoolVal(val, ctx=None)
Definition z3py.py:1863
RealVal(val, ctx=None)
Definition z3py.py:3470
bool is_implies(Any a)
Definition z3py.py:1799
z3_debug()
Definition z3py.py:70
get_full_version()
Definition z3py.py:109
IntVector(prefix, sz, ctx=None)
Definition z3py.py:3548
_coerce_expr_merge(s, a)
Definition z3py.py:1285
Context get_ctx(ctx)
Definition z3py.py:294
LShR(a, b)
Definition z3py.py:4603
ArraySort(*sig)
Definition z3py.py:5043
Map(f, *args)
Definition z3py.py:5168
is_rational_value(a)
Definition z3py.py:2931
_probe_or(args, ctx)
Definition z3py.py:9635
BVRedAnd(a)
Definition z3py.py:4749
Cbrt(a, ctx=None)
Definition z3py.py:3700
_to_expr_ref(a, ctx)
Definition z3py.py:1227
DisjointSum(name, sorts, ctx=None)
Definition z3py.py:6097
IntSort(ctx=None)
Definition z3py.py:3412
is_seq(a)
Definition z3py.py:11869
Not(a, ctx=None)
Definition z3py.py:1969
_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:2404
ToReal(a)
Definition z3py.py:3632
URem(a, b)
Definition z3py.py:4561
bool is_bool(Any a)
Definition z3py.py:1725
StringVal(s, ctx=None)
Definition z3py.py:11896
IsInt(a)
Definition z3py.py:3670
_is_numeral(ctx, a)
Definition z3py.py:2899
MultiPattern(*args)
Definition z3py.py:2105
ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2386
ZeroExt(n, a)
Definition z3py.py:4697
Complexes(names, ctx=None)
Definition z3py.py:3356
_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:6060
BVSubNoUnderflow(a, b, signed)
Definition z3py.py:4823
UDiv(a, b)
Definition z3py.py:4540
ImagPart(value)
Definition z3py.py:3389
Q(a, b, ctx=None)
Definition z3py.py:3509
Update(a, *args)
Definition z3py.py:5092
get_var_index(a)
Definition z3py.py:1459
append_log(s)
Definition z3py.py:127
AsArray(f)
Definition z3py.py:5225
is_var(a)
Definition z3py.py:1434
SortRef DeclareSort(name, ctx=None)
Definition z3py.py:736
IntVal(val, ctx=None)
Definition z3py.py:3458
BVMulNoOverflow(a, b, signed)
Definition z3py.py:4844
RotateLeft(a, b)
Definition z3py.py:4635
_mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2351
_z3_assert(cond, msg)
Definition z3py.py:113