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_BV_SORT:
706 return BitVecSortRef(s, ctx)
707 elif k == Z3_ARRAY_SORT:
708 return ArraySortRef(s, ctx)
709 elif k == Z3_DATATYPE_SORT:
710 return DatatypeSortRef(s, ctx)
711 elif k == Z3_FINITE_DOMAIN_SORT:
712 return FiniteDomainSortRef(s, ctx)
713 elif k == Z3_FLOATING_POINT_SORT:
714 return FPSortRef(s, ctx)
715 elif k == Z3_ROUNDING_MODE_SORT:
716 return FPRMSortRef(s, ctx)
717 elif k == Z3_RE_SORT:
718 return ReSortRef(s, ctx)
719 elif k == Z3_SEQ_SORT:
720 return SeqSortRef(s, ctx)
721 elif k == Z3_CHAR_SORT:
722 return CharSortRef(s, ctx)
723 elif k == Z3_TYPE_VAR:
724 return TypeVarRef(s, ctx)
725 return SortRef(s, ctx)
726
727
728def _sort(ctx : Context, a : Any) -> SortRef:
729 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
730
731
732def DeclareSort(name, ctx= None) -> SortRef:
733 """Create a new uninterpreted sort named `name`.
734
735 If `ctx=None`, then the new sort is declared in the global Z3Py context.
736
737 >>> A = DeclareSort('A')
738 >>> a = Const('a', A)
739 >>> b = Const('b', A)
740 >>> a.sort() == A
741 True
742 >>> b.sort() == A
743 True
744 >>> a == b
745 a == b
746 """
747 ctx = _get_ctx(ctx)
748 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
749
751 """Type variable reference"""
752
753 def subsort(self, other):
754 return True
755
756 def cast(self, val):
757 return val
758
759
760def DeclareTypeVar(name, ctx=None):
761 """Create a new type variable named `name`.
762
763 If `ctx=None`, then the new sort is declared in the global Z3Py context.
764
765 """
766 ctx = _get_ctx(ctx)
767 return TypeVarRef(Z3_mk_type_variable(ctx.ref(), to_symbol(name, ctx)), ctx)
768
769
770
775
776
778 """Function declaration. Every constant and function have an associated declaration.
779
780 The declaration assigns a name, a sort (i.e., type), and for function
781 the sort (i.e., type) of each of its arguments. Note that, in Z3,
782 a constant is a function with 0 arguments.
783 """
784
785 def as_ast(self):
786 return Z3_func_decl_to_ast(self.ctx_ref(), self.astast)
787
788 def get_id(self):
789 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
790
791 def as_func_decl(self):
792 return self.astast
793
794 def name(self):
795 """Return the name of the function declaration `self`.
796
797 >>> f = Function('f', IntSort(), IntSort())
798 >>> f.name()
799 'f'
800 >>> isinstance(f.name(), str)
801 True
802 """
803 return _symbol2py(self.ctxctx, Z3_get_decl_name(self.ctx_ref(), self.astast))
804
805 def arity(self):
806 """Return the number of arguments of a function declaration.
807 If `self` is a constant, then `self.arity()` is 0.
808
809 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
810 >>> f.arity()
811 2
812 """
813 return int(Z3_get_arity(self.ctx_ref(), self.astast))
814
815 def domain(self, i):
816 """Return the sort of the argument `i` of a function declaration.
817 This method assumes that `0 <= i < self.arity()`.
818
819 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
820 >>> f.domain(0)
821 Int
822 >>> f.domain(1)
823 Real
824 """
825 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.astast, i), self.ctxctx)
826
827 def range(self):
828 """Return the sort of the range of a function declaration.
829 For constants, this is the sort of the constant.
830
831 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
832 >>> f.range()
833 Bool
834 """
835 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.astast), self.ctxctx)
836
837 def kind(self):
838 """Return the internal kind of a function declaration.
839 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
840
841 >>> x = Int('x')
842 >>> d = (x + 1).decl()
843 >>> d.kind() == Z3_OP_ADD
844 True
845 >>> d.kind() == Z3_OP_MUL
846 False
847 """
848 return Z3_get_decl_kind(self.ctx_ref(), self.astast)
849
850 def params(self):
851 ctx = self.ctxctx
853 result = [None for i in range(n)]
854 for i in range(n):
855 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.astast, i)
856 if k == Z3_PARAMETER_INT:
857 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.astast, i)
858 elif k == Z3_PARAMETER_DOUBLE:
859 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.astast, i)
860 elif k == Z3_PARAMETER_RATIONAL:
861 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.astast, i)
862 elif k == Z3_PARAMETER_SYMBOL:
863 result[i] = _symbol2py(ctx, Z3_get_decl_symbol_parameter(self.ctx_ref(), self.astast, i))
864 elif k == Z3_PARAMETER_SORT:
865 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.astast, i), ctx)
866 elif k == Z3_PARAMETER_AST:
867 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.astast, i), ctx)
868 elif k == Z3_PARAMETER_FUNC_DECL:
869 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.astast, i), ctx)
870 elif k == Z3_PARAMETER_INTERNAL:
871 result[i] = "internal parameter"
872 elif k == Z3_PARAMETER_ZSTRING:
873 result[i] = "internal string"
874 else:
875 raise Z3Exception("Unexpected parameter kind")
876 return result
877
878 def __call__(self, *args):
879 """Create a Z3 application expression using the function `self`, and the given arguments.
880
881 The arguments must be Z3 expressions. This method assumes that
882 the sorts of the elements in `args` match the sorts of the
883 domain. Limited coercion is supported. For example, if
884 args[0] is a Python integer, and the function expects a Z3
885 integer, then the argument is automatically converted into a
886 Z3 integer.
887
888 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
889 >>> x = Int('x')
890 >>> y = Real('y')
891 >>> f(x, y)
892 f(x, y)
893 >>> f(x, x)
894 f(x, ToReal(x))
895 """
896 args = _get_args(args)
897 num = len(args)
898 _args = (Ast * num)()
899 saved = []
900 for i in range(num):
901 # self.domain(i).cast(args[i]) may create a new Z3 expression,
902 # then we must save in 'saved' to prevent it from being garbage collected.
903 tmp = self.domain(i).cast(args[i])
904 saved.append(tmp)
905 _args[i] = tmp.as_ast()
906 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.astast, len(args), _args), self.ctxctx)
907
908
910 """Return `True` if `a` is a Z3 function declaration.
911
912 >>> f = Function('f', IntSort(), IntSort())
913 >>> is_func_decl(f)
914 True
915 >>> x = Real('x')
916 >>> is_func_decl(x)
917 False
918 """
919 return isinstance(a, FuncDeclRef)
920
921
922def Function(name, *sig):
923 """Create a new Z3 uninterpreted function with the given sorts.
924
925 >>> f = Function('f', IntSort(), IntSort())
926 >>> f(f(0))
927 f(f(0))
928 """
929 sig = _get_args(sig)
930 if z3_debug():
931 _z3_assert(len(sig) > 0, "At least two arguments expected")
932 arity = len(sig) - 1
933 rng = sig[arity]
934 if z3_debug():
935 _z3_assert(is_sort(rng), "Z3 sort expected")
936 dom = (Sort * arity)()
937 for i in range(arity):
938 if z3_debug():
939 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
940 dom[i] = sig[i].ast
941 ctx = rng.ctx
942 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
943
944
946 """Create a new fresh Z3 uninterpreted function with the given sorts.
947 """
948 sig = _get_args(sig)
949 if z3_debug():
950 _z3_assert(len(sig) > 0, "At least two arguments expected")
951 arity = len(sig) - 1
952 rng = sig[arity]
953 if z3_debug():
954 _z3_assert(is_sort(rng), "Z3 sort expected")
955 dom = (z3.Sort * arity)()
956 for i in range(arity):
957 if z3_debug():
958 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
959 dom[i] = sig[i].ast
960 ctx = rng.ctx
961 return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), "f", arity, dom, rng.ast), ctx)
962
963
965 return FuncDeclRef(a, ctx)
966
967
968def RecFunction(name, *sig):
969 """Create a new Z3 recursive with the given sorts."""
970 sig = _get_args(sig)
971 if z3_debug():
972 _z3_assert(len(sig) > 0, "At least two arguments expected")
973 arity = len(sig) - 1
974 rng = sig[arity]
975 if z3_debug():
976 _z3_assert(is_sort(rng), "Z3 sort expected")
977 dom = (Sort * arity)()
978 for i in range(arity):
979 if z3_debug():
980 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
981 dom[i] = sig[i].ast
982 ctx = rng.ctx
983 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
984
985
986def RecAddDefinition(f, args, body):
987 """Set the body of a recursive function.
988 Recursive definitions can be simplified if they are applied to ground
989 arguments.
990 >>> ctx = Context()
991 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
992 >>> n = Int('n', ctx)
993 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
994 >>> simplify(fac(5))
995 120
996 >>> s = Solver(ctx=ctx)
997 >>> s.add(fac(n) < 3)
998 >>> s.check()
999 sat
1000 >>> s.model().eval(fac(5))
1001 120
1002 """
1003 if is_app(args):
1004 args = [args]
1005 ctx = body.ctx
1006 args = _get_args(args)
1007 n = len(args)
1008 _args = (Ast * n)()
1009 for i in range(n):
1010 _args[i] = args[i].ast
1011 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
1012
1013
1018
1019
1021 """Constraints, formulas and terms are expressions in Z3.
1022
1023 Expressions are ASTs. Every expression has a sort.
1024 There are three main kinds of expressions:
1025 function applications, quantifiers and bounded variables.
1026 A constant is a function application with 0 arguments.
1027 For quantifier free problems, all expressions are
1028 function applications.
1029 """
1030
1031 def as_ast(self):
1032 return self.astast
1033
1034 def get_id(self):
1035 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
1036
1037 def sort(self):
1038 """Return the sort of expression `self`.
1039
1040 >>> x = Int('x')
1041 >>> (x + 1).sort()
1042 Int
1043 >>> y = Real('y')
1044 >>> (x + y).sort()
1045 Real
1046 """
1047 return _sort(self.ctxctx, self.as_astas_ast())
1048
1049 def sort_kind(self):
1050 """Shorthand for `self.sort().kind()`.
1051
1052 >>> a = Array('a', IntSort(), IntSort())
1053 >>> a.sort_kind() == Z3_ARRAY_SORT
1054 True
1055 >>> a.sort_kind() == Z3_INT_SORT
1056 False
1057 """
1058 return self.sort().kind()
1059
1060 def __eq__(self, other):
1061 """Return a Z3 expression that represents the constraint `self == other`.
1062
1063 If `other` is `None`, then this method simply returns `False`.
1064
1065 >>> a = Int('a')
1066 >>> b = Int('b')
1067 >>> a == b
1068 a == b
1069 >>> a is None
1070 False
1071 """
1072 if other is None:
1073 return False
1074 a, b = _coerce_exprs(self, other)
1075 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctx)
1076
1077 def __hash__(self):
1078 """ Hash code. """
1079 return AstRef.__hash__(self)
1080
1081 def __ne__(self, other):
1082 """Return a Z3 expression that represents the constraint `self != other`.
1083
1084 If `other` is `None`, then this method simply returns `True`.
1085
1086 >>> a = Int('a')
1087 >>> b = Int('b')
1088 >>> a != b
1089 a != b
1090 >>> a is not None
1091 True
1092 """
1093 if other is None:
1094 return True
1095 a, b = _coerce_exprs(self, other)
1096 _args, sz = _to_ast_array((a, b))
1097 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctxctx)
1098
1099 def params(self):
1100 return self.decl().params()
1101
1102 def decl(self):
1103 """Return the Z3 function declaration associated with a Z3 application.
1104
1105 >>> f = Function('f', IntSort(), IntSort())
1106 >>> a = Int('a')
1107 >>> t = f(a)
1108 >>> eq(t.decl(), f)
1109 True
1110 >>> (a + 1).decl()
1111 +
1112 """
1113 if z3_debug():
1114 _z3_assert(is_app(self), "Z3 application expected")
1115 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_astas_ast()), self.ctxctx)
1116
1117 def kind(self):
1118 """Return the Z3 internal kind of a function application."""
1119 if z3_debug():
1120 _z3_assert(is_app(self), "Z3 application expected")
1122
1123
1124 def num_args(self):
1125 """Return the number of arguments of a Z3 application.
1126
1127 >>> a = Int('a')
1128 >>> b = Int('b')
1129 >>> (a + b).num_args()
1130 2
1131 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1132 >>> t = f(a, b, 0)
1133 >>> t.num_args()
1134 3
1135 """
1136 if z3_debug():
1137 _z3_assert(is_app(self), "Z3 application expected")
1138 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_astas_ast()))
1139
1140 def arg(self, idx):
1141 """Return argument `idx` of the application `self`.
1142
1143 This method assumes that `self` is a function application with at least `idx+1` arguments.
1144
1145 >>> a = Int('a')
1146 >>> b = Int('b')
1147 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1148 >>> t = f(a, b, 0)
1149 >>> t.arg(0)
1150 a
1151 >>> t.arg(1)
1152 b
1153 >>> t.arg(2)
1154 0
1155 """
1156 if z3_debug():
1157 _z3_assert(is_app(self), "Z3 application expected")
1158 _z3_assert(idx < self.num_args(), "Invalid argument index")
1159 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_astas_ast(), idx), self.ctxctx)
1160
1161 def children(self):
1162 """Return a list containing the children of the given expression
1163
1164 >>> a = Int('a')
1165 >>> b = Int('b')
1166 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1167 >>> t = f(a, b, 0)
1168 >>> t.children()
1169 [a, b, 0]
1170 """
1171 if is_app(self):
1172 return [self.arg(i) for i in range(self.num_args())]
1173 else:
1174 return []
1175
1176 def update(self, *args):
1177 """Update the arguments of the expression.
1178
1179 Return a new expression with the same function declaration and updated arguments.
1180 The number of new arguments must match the current number of arguments.
1181
1182 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1183 >>> a = Int('a')
1184 >>> b = Int('b')
1185 >>> c = Int('c')
1186 >>> t = f(a, b)
1187 >>> t.update(c, c)
1188 f(c, c)
1189 """
1190 if z3_debug():
1191 _z3_assert(is_app(self), "Z3 application expected")
1192 _z3_assert(len(args) == self.num_args(), "Number of arguments does not match")
1193 _z3_assert(all([is_expr(arg) for arg in args]), "Z3 expressions expected")
1194 num = len(args)
1195 _args = (Ast * num)()
1196 for i in range(num):
1197 _args[i] = args[i].as_ast()
1198 return _to_expr_ref(Z3_update_term(self.ctx_ref(), self.as_astas_ast(), num, _args), self.ctxctx)
1199
1200 def from_string(self, s):
1201 pass
1202
1203 def serialize(self):
1204 s = Solver()
1205 f = Function('F', self.sort(), BoolSort(self.ctx))
1206 s.add(f(self))
1207 return s.sexpr()
1208
1210 """inverse function to the serialize method on ExprRef.
1211 It is made available to make it easier for users to serialize expressions back and forth between
1212 strings. Solvers can be serialized using the 'sexpr()' method.
1213 """
1214 s = Solver()
1215 s.from_string(st)
1216 if len(s.assertions()) != 1:
1217 raise Z3Exception("single assertion expected")
1218 fml = s.assertions()[0]
1219 if fml.num_args() != 1:
1220 raise Z3Exception("dummy function 'F' expected")
1221 return fml.arg(0)
1222
1223def _to_expr_ref(a, ctx):
1224 if isinstance(a, Pattern):
1225 return PatternRef(a, ctx)
1226 ctx_ref = ctx.ref()
1227 k = Z3_get_ast_kind(ctx_ref, a)
1228 if k == Z3_QUANTIFIER_AST:
1229 return QuantifierRef(a, ctx)
1230 # Check for finite set sort before checking sort kind
1231 s = Z3_get_sort(ctx_ref, a)
1232 if Z3_is_finite_set_sort(ctx_ref, s):
1233 return FiniteSetRef(a, ctx)
1234 sk = Z3_get_sort_kind(ctx_ref, s)
1235 if sk == Z3_BOOL_SORT:
1236 return BoolRef(a, ctx)
1237 if sk == Z3_INT_SORT:
1238 if k == Z3_NUMERAL_AST:
1239 return IntNumRef(a, ctx)
1240 return ArithRef(a, ctx)
1241 if sk == Z3_REAL_SORT:
1242 if k == Z3_NUMERAL_AST:
1243 return RatNumRef(a, ctx)
1244 if _is_algebraic(ctx, a):
1245 return AlgebraicNumRef(a, ctx)
1246 return ArithRef(a, ctx)
1247 if sk == Z3_BV_SORT:
1248 if k == Z3_NUMERAL_AST:
1249 return BitVecNumRef(a, ctx)
1250 else:
1251 return BitVecRef(a, ctx)
1252 if sk == Z3_ARRAY_SORT:
1253 return ArrayRef(a, ctx)
1254 if sk == Z3_DATATYPE_SORT:
1255 return DatatypeRef(a, ctx)
1256 if sk == Z3_FLOATING_POINT_SORT:
1257 if k == Z3_APP_AST and _is_numeral(ctx, a):
1258 return FPNumRef(a, ctx)
1259 else:
1260 return FPRef(a, ctx)
1261 if sk == Z3_FINITE_DOMAIN_SORT:
1262 if k == Z3_NUMERAL_AST:
1263 return FiniteDomainNumRef(a, ctx)
1264 else:
1265 return FiniteDomainRef(a, ctx)
1266 if sk == Z3_ROUNDING_MODE_SORT:
1267 return FPRMRef(a, ctx)
1268 if sk == Z3_SEQ_SORT:
1269 return SeqRef(a, ctx)
1270 if sk == Z3_CHAR_SORT:
1271 return CharRef(a, ctx)
1272 if sk == Z3_RE_SORT:
1273 return ReRef(a, ctx)
1274 return ExprRef(a, ctx)
1275
1276
1278 if is_expr(a):
1279 s1 = a.sort()
1280 if s is None:
1281 return s1
1282 if s1.eq(s):
1283 return s
1284 elif s.subsort(s1):
1285 return s1
1286 elif s1.subsort(s):
1287 return s
1288 else:
1289 if z3_debug():
1290 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1291 _z3_assert(False, "sort mismatch")
1292 else:
1293 return s
1294
1295def _check_same_sort(a, b, ctx=None):
1296 if not isinstance(a, ExprRef):
1297 return False
1298 if not isinstance(b, ExprRef):
1299 return False
1300 if ctx is None:
1301 ctx = a.ctx
1302
1303 a_sort = Z3_get_sort(ctx.ctx, a.ast)
1304 b_sort = Z3_get_sort(ctx.ctx, b.ast)
1305 return Z3_is_eq_sort(ctx.ctx, a_sort, b_sort)
1306
1307
1308def _coerce_exprs(a, b, ctx=None):
1309 if not is_expr(a) and not is_expr(b):
1310 a = _py2expr(a, ctx)
1311 b = _py2expr(b, ctx)
1312 if isinstance(a, str) and isinstance(b, SeqRef):
1313 a = StringVal(a, b.ctx)
1314 if isinstance(b, str) and isinstance(a, SeqRef):
1315 b = StringVal(b, a.ctx)
1316 if isinstance(a, float) and isinstance(b, ArithRef):
1317 a = RealVal(a, b.ctx)
1318 if isinstance(b, float) and isinstance(a, ArithRef):
1319 b = RealVal(b, a.ctx)
1320
1321 if _check_same_sort(a, b, ctx):
1322 return (a, b)
1323
1324 s = None
1325 s = _coerce_expr_merge(s, a)
1326 s = _coerce_expr_merge(s, b)
1327 a = s.cast(a)
1328 b = s.cast(b)
1329 return (a, b)
1330
1331
1332def _reduce(func, sequence, initial):
1333 result = initial
1334 for element in sequence:
1335 result = func(result, element)
1336 return result
1337
1338
1339def _coerce_expr_list(alist, ctx=None):
1340 has_expr = False
1341 for a in alist:
1342 if is_expr(a):
1343 has_expr = True
1344 break
1345 if not has_expr:
1346 alist = [_py2expr(a, ctx) for a in alist]
1347 s = _reduce(_coerce_expr_merge, alist, None)
1348 return [s.cast(a) for a in alist]
1349
1350
1351def is_expr(a):
1352 """Return `True` if `a` is a Z3 expression.
1353
1354 >>> a = Int('a')
1355 >>> is_expr(a)
1356 True
1357 >>> is_expr(a + 1)
1358 True
1359 >>> is_expr(IntSort())
1360 False
1361 >>> is_expr(1)
1362 False
1363 >>> is_expr(IntVal(1))
1364 True
1365 >>> x = Int('x')
1366 >>> is_expr(ForAll(x, x >= 0))
1367 True
1368 >>> is_expr(FPVal(1.0))
1369 True
1370 """
1371 return isinstance(a, ExprRef)
1372
1373
1374def is_app(a):
1375 """Return `True` if `a` is a Z3 function application.
1376
1377 Note that, constants are function applications with 0 arguments.
1378
1379 >>> a = Int('a')
1380 >>> is_app(a)
1381 True
1382 >>> is_app(a + 1)
1383 True
1384 >>> is_app(IntSort())
1385 False
1386 >>> is_app(1)
1387 False
1388 >>> is_app(IntVal(1))
1389 True
1390 >>> x = Int('x')
1391 >>> is_app(ForAll(x, x >= 0))
1392 False
1393 """
1394 if not isinstance(a, ExprRef):
1395 return False
1396 k = _ast_kind(a.ctx, a)
1397 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1398
1399
1401 """Return `True` if `a` is Z3 constant/variable expression.
1402
1403 >>> a = Int('a')
1404 >>> is_const(a)
1405 True
1406 >>> is_const(a + 1)
1407 False
1408 >>> is_const(1)
1409 False
1410 >>> is_const(IntVal(1))
1411 True
1412 >>> x = Int('x')
1413 >>> is_const(ForAll(x, x >= 0))
1414 False
1415 """
1416 return is_app(a) and a.num_args() == 0
1417
1418
1419def is_var(a):
1420 """Return `True` if `a` is variable.
1421
1422 Z3 uses de-Bruijn indices for representing bound variables in
1423 quantifiers.
1424
1425 >>> x = Int('x')
1426 >>> is_var(x)
1427 False
1428 >>> is_const(x)
1429 True
1430 >>> f = Function('f', IntSort(), IntSort())
1431 >>> # Z3 replaces x with bound variables when ForAll is executed.
1432 >>> q = ForAll(x, f(x) == x)
1433 >>> b = q.body()
1434 >>> b
1435 f(Var(0)) == Var(0)
1436 >>> b.arg(1)
1437 Var(0)
1438 >>> is_var(b.arg(1))
1439 True
1440 """
1441 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1442
1443
1445 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1446
1447 >>> x = Int('x')
1448 >>> y = Int('y')
1449 >>> is_var(x)
1450 False
1451 >>> is_const(x)
1452 True
1453 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1454 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1455 >>> q = ForAll([x, y], f(x, y) == x + y)
1456 >>> q.body()
1457 f(Var(1), Var(0)) == Var(1) + Var(0)
1458 >>> b = q.body()
1459 >>> b.arg(0)
1460 f(Var(1), Var(0))
1461 >>> v1 = b.arg(0).arg(0)
1462 >>> v2 = b.arg(0).arg(1)
1463 >>> v1
1464 Var(1)
1465 >>> v2
1466 Var(0)
1467 >>> get_var_index(v1)
1468 1
1469 >>> get_var_index(v2)
1470 0
1471 """
1472 if z3_debug():
1473 _z3_assert(is_var(a), "Z3 bound variable expected")
1474 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1475
1476
1477def is_app_of(a, k):
1478 """Return `True` if `a` is an application of the given kind `k`.
1479
1480 >>> x = Int('x')
1481 >>> n = x + 1
1482 >>> is_app_of(n, Z3_OP_ADD)
1483 True
1484 >>> is_app_of(n, Z3_OP_MUL)
1485 False
1486 """
1487 return is_app(a) and a.kind() == k
1488
1489
1490def If(a, b, c, ctx=None):
1491 """Create a Z3 if-then-else expression.
1492
1493 >>> x = Int('x')
1494 >>> y = Int('y')
1495 >>> max = If(x > y, x, y)
1496 >>> max
1497 If(x > y, x, y)
1498 >>> simplify(max)
1499 If(x <= y, y, x)
1500 """
1501 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1502 return Cond(a, b, c, ctx)
1503 else:
1504 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1505 s = BoolSort(ctx)
1506 a = s.cast(a)
1507 b, c = _coerce_exprs(b, c, ctx)
1508 if z3_debug():
1509 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1510 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1511
1512
1513def Distinct(*args):
1514 """Create a Z3 distinct expression.
1515
1516 >>> x = Int('x')
1517 >>> y = Int('y')
1518 >>> Distinct(x, y)
1519 x != y
1520 >>> z = Int('z')
1521 >>> Distinct(x, y, z)
1522 Distinct(x, y, z)
1523 >>> simplify(Distinct(x, y, z))
1524 Distinct(x, y, z)
1525 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1526 And(Not(x == y), Not(x == z), Not(y == z))
1527 """
1528 args = _get_args(args)
1529 ctx = _ctx_from_ast_arg_list(args)
1530 if z3_debug():
1531 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1532 args = _coerce_expr_list(args, ctx)
1533 _args, sz = _to_ast_array(args)
1534 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1535
1536
1537def _mk_bin(f, a, b):
1538 args = (Ast * 2)()
1539 if z3_debug():
1540 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1541 args[0] = a.as_ast()
1542 args[1] = b.as_ast()
1543 return f(a.ctx.ref(), 2, args)
1544
1545
1546def Const(name, sort):
1547 """Create a constant of the given sort.
1548
1549 >>> Const('x', IntSort())
1550 x
1551 """
1552 if z3_debug():
1553 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1554 ctx = sort.ctx
1555 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1556
1557
1558def Consts(names, sort):
1559 """Create several constants of the given sort.
1560
1561 `names` is a string containing the names of all constants to be created.
1562 Blank spaces separate the names of different constants.
1563
1564 >>> x, y, z = Consts('x y z', IntSort())
1565 >>> x + y + z
1566 x + y + z
1567 """
1568 if isinstance(names, str):
1569 names = names.split(" ")
1570 return [Const(name, sort) for name in names]
1571
1572
1573def FreshConst(sort, prefix="c"):
1574 """Create a fresh constant of a specified sort"""
1575 if z3_debug():
1576 _z3_assert(is_sort(sort), f"Z3 sort expected, got {type(sort)}")
1577 ctx = _get_ctx(sort.ctx)
1578 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1579
1580
1581def Var(idx : int, s : SortRef) -> ExprRef:
1582 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1583 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1584 declarations.
1585
1586 >>> Var(0, IntSort())
1587 Var(0)
1588 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1589 False
1590 """
1591 if z3_debug():
1592 _z3_assert(is_sort(s), "Z3 sort expected")
1593 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1594
1595
1596def RealVar(idx: int, ctx=None) -> ExprRef:
1597 """
1598 Create a real free variable. Free variables are used to create quantified formulas.
1599 They are also used to create polynomials.
1600
1601 >>> RealVar(0)
1602 Var(0)
1603 """
1604 return Var(idx, RealSort(ctx))
1605
1606def RealVarVector(n: int, ctx= None):
1607 """
1608 Create a list of Real free variables.
1609 The variables have ids: 0, 1, ..., n-1
1610
1611 >>> x0, x1, x2, x3 = RealVarVector(4)
1612 >>> x2
1613 Var(2)
1614 """
1615 return [RealVar(i, ctx) for i in range(n)]
1616
1617
1622
1623
1625 """Boolean sort."""
1626
1627 def cast(self, val):
1628 """Try to cast `val` as a Boolean.
1629
1630 >>> x = BoolSort().cast(True)
1631 >>> x
1632 True
1633 >>> is_expr(x)
1634 True
1635 >>> is_expr(True)
1636 False
1637 >>> x.sort()
1638 Bool
1639 """
1640 if isinstance(val, bool):
1641 return BoolVal(val, self.ctxctxctx)
1642 if z3_debug():
1643 if not is_expr(val):
1644 msg = "True, False or Z3 Boolean expression expected. Received %s of type %s"
1645 _z3_assert(is_expr(val), msg % (val, type(val)))
1646 if not self.eq(val.sort()):
1647 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1648 return val
1649
1650 def subsort(self, other):
1651 return isinstance(other, ArithSortRef)
1652
1653 def is_int(self):
1654 return True
1655
1656 def is_bool(self):
1657 return True
1658
1659
1661 """All Boolean expressions are instances of this class."""
1662
1663 def sort(self):
1665
1666 def __add__(self, other):
1667 if isinstance(other, BoolRef):
1668 other = If(other, 1, 0)
1669 return If(self, 1, 0) + other
1670
1671 def __radd__(self, other):
1672 return self + other
1673
1674 def __rmul__(self, other):
1675 return self * other
1676
1677 def __mul__(self, other):
1678 """Create the Z3 expression `self * other`.
1679 """
1680 if isinstance(other, int) and other == 1:
1681 return If(self, 1, 0)
1682 if isinstance(other, int) and other == 0:
1683 return IntVal(0, self.ctxctxctx)
1684 if isinstance(other, BoolRef):
1685 other = If(other, 1, 0)
1686 return If(self, other, 0)
1687
1688 def __and__(self, other):
1689 return And(self, other)
1690
1691 def __or__(self, other):
1692 return Or(self, other)
1693
1694 def __xor__(self, other):
1695 return Xor(self, other)
1696
1697 def __invert__(self):
1698 return Not(self)
1699
1700 def py_value(self):
1701 if is_true(self):
1702 return True
1703 if is_false(self):
1704 return False
1705 return None
1706
1707
1708
1709
1710def is_bool(a : Any) -> bool:
1711 """Return `True` if `a` is a Z3 Boolean expression.
1712
1713 >>> p = Bool('p')
1714 >>> is_bool(p)
1715 True
1716 >>> q = Bool('q')
1717 >>> is_bool(And(p, q))
1718 True
1719 >>> x = Real('x')
1720 >>> is_bool(x)
1721 False
1722 >>> is_bool(x == 0)
1723 True
1724 """
1725 return isinstance(a, BoolRef)
1726
1727
1728def is_true(a : Any) -> bool:
1729 """Return `True` if `a` is the Z3 true expression.
1730
1731 >>> p = Bool('p')
1732 >>> is_true(p)
1733 False
1734 >>> is_true(simplify(p == p))
1735 True
1736 >>> x = Real('x')
1737 >>> is_true(x == 0)
1738 False
1739 >>> # True is a Python Boolean expression
1740 >>> is_true(True)
1741 False
1742 """
1743 return is_app_of(a, Z3_OP_TRUE)
1744
1745
1746def is_false(a : Any) -> bool:
1747 """Return `True` if `a` is the Z3 false expression.
1748
1749 >>> p = Bool('p')
1750 >>> is_false(p)
1751 False
1752 >>> is_false(False)
1753 False
1754 >>> is_false(BoolVal(False))
1755 True
1756 """
1757 return is_app_of(a, Z3_OP_FALSE)
1758
1759
1760def is_and(a : Any) -> bool:
1761 """Return `True` if `a` is a Z3 and expression.
1762
1763 >>> p, q = Bools('p q')
1764 >>> is_and(And(p, q))
1765 True
1766 >>> is_and(Or(p, q))
1767 False
1768 """
1769 return is_app_of(a, Z3_OP_AND)
1770
1771
1772def is_or(a : Any) -> bool:
1773 """Return `True` if `a` is a Z3 or expression.
1774
1775 >>> p, q = Bools('p q')
1776 >>> is_or(Or(p, q))
1777 True
1778 >>> is_or(And(p, q))
1779 False
1780 """
1781 return is_app_of(a, Z3_OP_OR)
1782
1783
1784def is_implies(a : Any) -> bool:
1785 """Return `True` if `a` is a Z3 implication expression.
1786
1787 >>> p, q = Bools('p q')
1788 >>> is_implies(Implies(p, q))
1789 True
1790 >>> is_implies(And(p, q))
1791 False
1792 """
1793 return is_app_of(a, Z3_OP_IMPLIES)
1794
1795
1796def is_not(a : Any) -> bool:
1797 """Return `True` if `a` is a Z3 not expression.
1798
1799 >>> p = Bool('p')
1800 >>> is_not(p)
1801 False
1802 >>> is_not(Not(p))
1803 True
1804 """
1805 return is_app_of(a, Z3_OP_NOT)
1806
1807
1808def is_eq(a : Any) -> bool:
1809 """Return `True` if `a` is a Z3 equality expression.
1810
1811 >>> x, y = Ints('x y')
1812 >>> is_eq(x == y)
1813 True
1814 """
1815 return is_app_of(a, Z3_OP_EQ)
1816
1817
1818def is_distinct(a : Any) -> bool:
1819 """Return `True` if `a` is a Z3 distinct expression.
1820
1821 >>> x, y, z = Ints('x y z')
1822 >>> is_distinct(x == y)
1823 False
1824 >>> is_distinct(Distinct(x, y, z))
1825 True
1826 """
1827 return is_app_of(a, Z3_OP_DISTINCT)
1828
1829
1830def BoolSort(ctx=None):
1831 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1832
1833 >>> BoolSort()
1834 Bool
1835 >>> p = Const('p', BoolSort())
1836 >>> is_bool(p)
1837 True
1838 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1839 >>> r(0, 1)
1840 r(0, 1)
1841 >>> is_bool(r(0, 1))
1842 True
1843 """
1844 ctx = _get_ctx(ctx)
1845 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1846
1847
1848def BoolVal(val, ctx=None):
1849 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1850
1851 >>> BoolVal(True)
1852 True
1853 >>> is_true(BoolVal(True))
1854 True
1855 >>> is_true(True)
1856 False
1857 >>> is_false(BoolVal(False))
1858 True
1859 """
1860 ctx = _get_ctx(ctx)
1861 if val:
1862 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1863 else:
1864 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1865
1866
1867def Bool(name, ctx=None):
1868 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1869
1870 >>> p = Bool('p')
1871 >>> q = Bool('q')
1872 >>> And(p, q)
1873 And(p, q)
1874 """
1875 ctx = _get_ctx(ctx)
1876 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1877
1878
1879def Bools(names, ctx=None):
1880 """Return a tuple of Boolean constants.
1881
1882 `names` is a single string containing all names separated by blank spaces.
1883 If `ctx=None`, then the global context is used.
1884
1885 >>> p, q, r = Bools('p q r')
1886 >>> And(p, Or(q, r))
1887 And(p, Or(q, r))
1888 """
1889 ctx = _get_ctx(ctx)
1890 if isinstance(names, str):
1891 names = names.split(" ")
1892 return [Bool(name, ctx) for name in names]
1893
1894
1895def BoolVector(prefix, sz, ctx=None):
1896 """Return a list of Boolean constants of size `sz`.
1897
1898 The constants are named using the given prefix.
1899 If `ctx=None`, then the global context is used.
1900
1901 >>> P = BoolVector('p', 3)
1902 >>> P
1903 [p__0, p__1, p__2]
1904 >>> And(P)
1905 And(p__0, p__1, p__2)
1906 """
1907 return [Bool("%s__%s" % (prefix, i)) for i in range(sz)]
1908
1909
1910def FreshBool(prefix="b", ctx=None):
1911 """Return a fresh Boolean constant in the given context using the given prefix.
1912
1913 If `ctx=None`, then the global context is used.
1914
1915 >>> b1 = FreshBool()
1916 >>> b2 = FreshBool()
1917 >>> eq(b1, b2)
1918 False
1919 """
1920 ctx = _get_ctx(ctx)
1921 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1922
1923
1924def Implies(a, b, ctx=None):
1925 """Create a Z3 implies expression.
1926
1927 >>> p, q = Bools('p q')
1928 >>> Implies(p, q)
1929 Implies(p, q)
1930 """
1931 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1932 s = BoolSort(ctx)
1933 a = s.cast(a)
1934 b = s.cast(b)
1935 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1936
1937
1938def Xor(a, b, ctx=None):
1939 """Create a Z3 Xor expression.
1940
1941 >>> p, q = Bools('p q')
1942 >>> Xor(p, q)
1943 Xor(p, q)
1944 >>> simplify(Xor(p, q))
1945 Not(p == q)
1946 """
1947 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1948 s = BoolSort(ctx)
1949 a = s.cast(a)
1950 b = s.cast(b)
1951 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1952
1953
1954def Not(a, ctx=None):
1955 """Create a Z3 not expression or probe.
1956
1957 >>> p = Bool('p')
1958 >>> Not(Not(p))
1959 Not(Not(p))
1960 >>> simplify(Not(Not(p)))
1961 p
1962 """
1963 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1964 if is_probe(a):
1965 # Not is also used to build probes
1966 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1967 else:
1968 s = BoolSort(ctx)
1969 a = s.cast(a)
1970 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1971
1972
1973def mk_not(a):
1974 if is_not(a):
1975 return a.arg(0)
1976 else:
1977 return Not(a)
1978
1979
1980def _has_probe(args):
1981 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1982 for arg in args:
1983 if is_probe(arg):
1984 return True
1985 return False
1986
1987
1988def And(*args):
1989 """Create a Z3 and-expression or and-probe.
1990
1991 >>> p, q, r = Bools('p q r')
1992 >>> And(p, q, r)
1993 And(p, q, r)
1994 >>> P = BoolVector('p', 5)
1995 >>> And(P)
1996 And(p__0, p__1, p__2, p__3, p__4)
1997 """
1998 last_arg = None
1999 if len(args) > 0:
2000 last_arg = args[len(args) - 1]
2001 if isinstance(last_arg, Context):
2002 ctx = args[len(args) - 1]
2003 args = args[:len(args) - 1]
2004 elif len(args) == 1 and isinstance(args[0], AstVector):
2005 ctx = args[0].ctx
2006 args = [a for a in args[0]]
2007 else:
2008 ctx = None
2009 args = _get_args(args)
2010 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2011 if z3_debug():
2012 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2013 if _has_probe(args):
2014 return _probe_and(args, ctx)
2015 else:
2016 args = _coerce_expr_list(args, ctx)
2017 _args, sz = _to_ast_array(args)
2018 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
2019
2020
2021def Or(*args):
2022 """Create a Z3 or-expression or or-probe.
2023
2024 >>> p, q, r = Bools('p q r')
2025 >>> Or(p, q, r)
2026 Or(p, q, r)
2027 >>> P = BoolVector('p', 5)
2028 >>> Or(P)
2029 Or(p__0, p__1, p__2, p__3, p__4)
2030 """
2031 last_arg = None
2032 if len(args) > 0:
2033 last_arg = args[len(args) - 1]
2034 if isinstance(last_arg, Context):
2035 ctx = args[len(args) - 1]
2036 args = args[:len(args) - 1]
2037 elif len(args) == 1 and isinstance(args[0], AstVector):
2038 ctx = args[0].ctx
2039 args = [a for a in args[0]]
2040 else:
2041 ctx = None
2042 args = _get_args(args)
2043 ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx))
2044 if z3_debug():
2045 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
2046 if _has_probe(args):
2047 return _probe_or(args, ctx)
2048 else:
2049 args = _coerce_expr_list(args, ctx)
2050 _args, sz = _to_ast_array(args)
2051 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
2052
2053
2058
2059
2061 """Patterns are hints for quantifier instantiation.
2062
2063 """
2064
2065 def as_ast(self):
2067
2068 def get_id(self):
2069 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
2070
2071
2073 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2074
2075 >>> f = Function('f', IntSort(), IntSort())
2076 >>> x = Int('x')
2077 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2078 >>> q
2079 ForAll(x, f(x) == 0)
2080 >>> q.num_patterns()
2081 1
2082 >>> is_pattern(q.pattern(0))
2083 True
2084 >>> q.pattern(0)
2085 f(Var(0))
2086 """
2087 return isinstance(a, PatternRef)
2088
2089
2090def MultiPattern(*args):
2091 """Create a Z3 multi-pattern using the given expressions `*args`
2092
2093 >>> f = Function('f', IntSort(), IntSort())
2094 >>> g = Function('g', IntSort(), IntSort())
2095 >>> x = Int('x')
2096 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2097 >>> q
2098 ForAll(x, f(x) != g(x))
2099 >>> q.num_patterns()
2100 1
2101 >>> is_pattern(q.pattern(0))
2102 True
2103 >>> q.pattern(0)
2104 MultiPattern(f(Var(0)), g(Var(0)))
2105 """
2106 if z3_debug():
2107 _z3_assert(len(args) > 0, "At least one argument expected")
2108 _z3_assert(all([is_expr(a) for a in args]), "Z3 expressions expected")
2109 ctx = args[0].ctx
2110 args, sz = _to_ast_array(args)
2111 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
2112
2113
2115 if is_pattern(arg):
2116 return arg
2117 else:
2118 return MultiPattern(arg)
2119
2120
2125
2126
2128 """Universally and Existentially quantified formulas."""
2129
2130 def as_ast(self):
2131 return self.astastast
2132
2133 def get_id(self):
2134 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
2135
2136 def sort(self):
2137 """Return the Boolean sort or sort of Lambda."""
2138 if self.is_lambda():
2140 return BoolSort(self.ctxctxctxctx)
2141
2142 def is_forall(self):
2143 """Return `True` if `self` is a universal quantifier.
2144
2145 >>> f = Function('f', IntSort(), IntSort())
2146 >>> x = Int('x')
2147 >>> q = ForAll(x, f(x) == 0)
2148 >>> q.is_forall()
2149 True
2150 >>> q = Exists(x, f(x) != 0)
2151 >>> q.is_forall()
2152 False
2153 """
2155
2156 def is_exists(self):
2157 """Return `True` if `self` is an existential quantifier.
2158
2159 >>> f = Function('f', IntSort(), IntSort())
2160 >>> x = Int('x')
2161 >>> q = ForAll(x, f(x) == 0)
2162 >>> q.is_exists()
2163 False
2164 >>> q = Exists(x, f(x) != 0)
2165 >>> q.is_exists()
2166 True
2167 """
2168 return Z3_is_quantifier_exists(self.ctx_ref(), self.astastast)
2169
2170 def is_lambda(self):
2171 """Return `True` if `self` is a lambda expression.
2172
2173 >>> f = Function('f', IntSort(), IntSort())
2174 >>> x = Int('x')
2175 >>> q = Lambda(x, f(x))
2176 >>> q.is_lambda()
2177 True
2178 >>> q = Exists(x, f(x) != 0)
2179 >>> q.is_lambda()
2180 False
2181 """
2182 return Z3_is_lambda(self.ctx_ref(), self.astastast)
2183
2184 def __getitem__(self, arg):
2185 """Return the Z3 expression `self[arg]`.
2186 """
2187 if z3_debug():
2188 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
2189 return _array_select(self, arg)
2190
2191 def weight(self):
2192 """Return the weight annotation of `self`.
2193
2194 >>> f = Function('f', IntSort(), IntSort())
2195 >>> x = Int('x')
2196 >>> q = ForAll(x, f(x) == 0)
2197 >>> q.weight()
2198 1
2199 >>> q = ForAll(x, f(x) == 0, weight=10)
2200 >>> q.weight()
2201 10
2202 """
2203 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.astastast))
2204
2205 def skolem_id(self):
2206 """Return the skolem id of `self`.
2207 """
2209
2210 def qid(self):
2211 """Return the quantifier id of `self`.
2212 """
2214
2215 def num_patterns(self):
2216 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2217
2218 >>> f = Function('f', IntSort(), IntSort())
2219 >>> g = Function('g', IntSort(), IntSort())
2220 >>> x = Int('x')
2221 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2222 >>> q.num_patterns()
2223 2
2224 """
2225 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.astastast))
2226
2227 def pattern(self, idx):
2228 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2229
2230 >>> f = Function('f', IntSort(), IntSort())
2231 >>> g = Function('g', IntSort(), IntSort())
2232 >>> x = Int('x')
2233 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2234 >>> q.num_patterns()
2235 2
2236 >>> q.pattern(0)
2237 f(Var(0))
2238 >>> q.pattern(1)
2239 g(Var(0))
2240 """
2241 if z3_debug():
2242 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
2244
2246 """Return the number of no-patterns."""
2248
2249 def no_pattern(self, idx):
2250 """Return a no-pattern."""
2251 if z3_debug():
2252 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
2254
2255 def body(self):
2256 """Return the expression being quantified.
2257
2258 >>> f = Function('f', IntSort(), IntSort())
2259 >>> x = Int('x')
2260 >>> q = ForAll(x, f(x) == 0)
2261 >>> q.body()
2262 f(Var(0)) == 0
2263 """
2265
2266 def num_vars(self):
2267 """Return the number of variables bounded by this quantifier.
2268
2269 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2270 >>> x = Int('x')
2271 >>> y = Int('y')
2272 >>> q = ForAll([x, y], f(x, y) >= x)
2273 >>> q.num_vars()
2274 2
2275 """
2276 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.astastast))
2277
2278 def var_name(self, idx):
2279 """Return a string representing a name used when displaying the quantifier.
2280
2281 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2282 >>> x = Int('x')
2283 >>> y = Int('y')
2284 >>> q = ForAll([x, y], f(x, y) >= x)
2285 >>> q.var_name(0)
2286 'x'
2287 >>> q.var_name(1)
2288 'y'
2289 """
2290 if z3_debug():
2291 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2293
2294 def var_sort(self, idx):
2295 """Return the sort of a bound variable.
2296
2297 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2298 >>> x = Int('x')
2299 >>> y = Real('y')
2300 >>> q = ForAll([x, y], f(x, y) >= x)
2301 >>> q.var_sort(0)
2302 Int
2303 >>> q.var_sort(1)
2304 Real
2305 """
2306 if z3_debug():
2307 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
2309
2310 def children(self):
2311 """Return a list containing a single element self.body()
2312
2313 >>> f = Function('f', IntSort(), IntSort())
2314 >>> x = Int('x')
2315 >>> q = ForAll(x, f(x) == 0)
2316 >>> q.children()
2317 [f(Var(0)) == 0]
2318 """
2319 return [self.body()]
2320
2321
2323 """Return `True` if `a` is a Z3 quantifier.
2324
2325 >>> f = Function('f', IntSort(), IntSort())
2326 >>> x = Int('x')
2327 >>> q = ForAll(x, f(x) == 0)
2328 >>> is_quantifier(q)
2329 True
2330 >>> is_quantifier(f(x))
2331 False
2332 """
2333 return isinstance(a, QuantifierRef)
2334
2335
2336def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2337 if z3_debug():
2338 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2339 _z3_assert(is_const(vs) or (len(vs) > 0 and all([is_const(v) for v in vs])), "Invalid bounded variable(s)")
2340 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2341 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2342 if is_app(vs):
2343 ctx = vs.ctx
2344 vs = [vs]
2345 else:
2346 ctx = vs[0].ctx
2347 if not is_expr(body):
2348 body = BoolVal(body, ctx)
2349 num_vars = len(vs)
2350 if num_vars == 0:
2351 return body
2352 _vs = (Ast * num_vars)()
2353 for i in range(num_vars):
2354 # TODO: Check if is constant
2355 _vs[i] = vs[i].as_ast()
2356 patterns = [_to_pattern(p) for p in patterns]
2357 num_pats = len(patterns)
2358 _pats = (Pattern * num_pats)()
2359 for i in range(num_pats):
2360 _pats[i] = patterns[i].ast
2361 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2362 qid = to_symbol(qid, ctx)
2363 skid = to_symbol(skid, ctx)
2364 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2365 num_vars, _vs,
2366 num_pats, _pats,
2367 num_no_pats, _no_pats,
2368 body.as_ast()), ctx)
2369
2370
2371def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2372 """Create a Z3 forall formula.
2373
2374 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2375
2376 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2377 >>> x = Int('x')
2378 >>> y = Int('y')
2379 >>> ForAll([x, y], f(x, y) >= x)
2380 ForAll([x, y], f(x, y) >= x)
2381 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2382 ForAll([x, y], f(x, y) >= x)
2383 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2384 ForAll([x, y], f(x, y) >= x)
2385 """
2386 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2387
2388
2389def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2390 """Create a Z3 exists formula.
2391
2392 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2393
2394
2395 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2396 >>> x = Int('x')
2397 >>> y = Int('y')
2398 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2399 >>> q
2400 Exists([x, y], f(x, y) >= x)
2401 >>> is_quantifier(q)
2402 True
2403 >>> r = Tactic('nnf')(q).as_expr()
2404 >>> is_quantifier(r)
2405 False
2406 """
2407 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2408
2409
2410def Lambda(vs, body):
2411 """Create a Z3 lambda expression.
2412
2413 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2414 >>> mem0 = Array('mem0', IntSort(), IntSort())
2415 >>> lo, hi, e, i = Ints('lo hi e i')
2416 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2417 >>> mem1
2418 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2419 """
2420 ctx = body.ctx
2421 if is_app(vs):
2422 vs = [vs]
2423 num_vars = len(vs)
2424 _vs = (Ast * num_vars)()
2425 for i in range(num_vars):
2426 # TODO: Check if is constant
2427 _vs[i] = vs[i].as_ast()
2428 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2429
2430
2435
2436
2438 """Real and Integer sorts."""
2439
2440 def is_real(self):
2441 """Return `True` if `self` is of the sort Real.
2442
2443 >>> x = Real('x')
2444 >>> x.is_real()
2445 True
2446 >>> (x + 1).is_real()
2447 True
2448 >>> x = Int('x')
2449 >>> x.is_real()
2450 False
2451 """
2452 return self.kind() == Z3_REAL_SORT
2453
2454 def is_int(self):
2455 """Return `True` if `self` is of the sort Integer.
2456
2457 >>> x = Int('x')
2458 >>> x.is_int()
2459 True
2460 >>> (x + 1).is_int()
2461 True
2462 >>> x = Real('x')
2463 >>> x.is_int()
2464 False
2465 """
2466 return self.kind() == Z3_INT_SORT
2467
2468 def is_bool(self):
2469 return False
2470
2471 def subsort(self, other):
2472 """Return `True` if `self` is a subsort of `other`."""
2473 return self.is_int() and is_arith_sort(other) and other.is_real()
2474
2475 def cast(self, val):
2476 """Try to cast `val` as an Integer or Real.
2477
2478 >>> IntSort().cast(10)
2479 10
2480 >>> is_int(IntSort().cast(10))
2481 True
2482 >>> is_int(10)
2483 False
2484 >>> RealSort().cast(10)
2485 10
2486 >>> is_real(RealSort().cast(10))
2487 True
2488 """
2489 if is_expr(val):
2490 if z3_debug():
2491 _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
2492 val_s = val.sort()
2493 if self.eq(val_s):
2494 return val
2495 if val_s.is_int() and self.is_real():
2496 return ToReal(val)
2497 if val_s.is_bool() and self.is_int():
2498 return If(val, 1, 0)
2499 if val_s.is_bool() and self.is_real():
2500 return ToReal(If(val, 1, 0))
2501 if z3_debug():
2502 _z3_assert(False, "Z3 Integer/Real expression expected")
2503 else:
2504 if self.is_int():
2505 return IntVal(val, self.ctxctxctx)
2506 if self.is_real():
2507 return RealVal(val, self.ctxctxctx)
2508 if z3_debug():
2509 msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2510 _z3_assert(False, msg % self)
2511
2512
2513def is_arith_sort(s : Any) -> bool:
2514 """Return `True` if s is an arithmetical sort (type).
2515
2516 >>> is_arith_sort(IntSort())
2517 True
2518 >>> is_arith_sort(RealSort())
2519 True
2520 >>> is_arith_sort(BoolSort())
2521 False
2522 >>> n = Int('x') + 1
2523 >>> is_arith_sort(n.sort())
2524 True
2525 """
2526 return isinstance(s, ArithSortRef)
2527
2528
2530 """Integer and Real expressions."""
2531
2532 def sort(self):
2533 """Return the sort (type) of the arithmetical expression `self`.
2534
2535 >>> Int('x').sort()
2536 Int
2537 >>> (Real('x') + 1).sort()
2538 Real
2539 """
2541
2542 def is_int(self):
2543 """Return `True` if `self` is an integer expression.
2544
2545 >>> x = Int('x')
2546 >>> x.is_int()
2547 True
2548 >>> (x + 1).is_int()
2549 True
2550 >>> y = Real('y')
2551 >>> (x + y).is_int()
2552 False
2553 """
2554 return self.sortsort().is_int()
2555
2556 def is_real(self):
2557 """Return `True` if `self` is an real expression.
2558
2559 >>> x = Real('x')
2560 >>> x.is_real()
2561 True
2562 >>> (x + 1).is_real()
2563 True
2564 """
2565 return self.sortsort().is_real()
2566
2567 def __add__(self, other):
2568 """Create the Z3 expression `self + other`.
2569
2570 >>> x = Int('x')
2571 >>> y = Int('y')
2572 >>> x + y
2573 x + y
2574 >>> (x + y).sort()
2575 Int
2576 """
2577 a, b = _coerce_exprs(self, other)
2578 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctxctxctx)
2579
2580 def __radd__(self, other):
2581 """Create the Z3 expression `other + self`.
2582
2583 >>> x = Int('x')
2584 >>> 10 + x
2585 10 + x
2586 """
2587 a, b = _coerce_exprs(self, other)
2588 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctxctxctx)
2589
2590 def __mul__(self, other):
2591 """Create the Z3 expression `self * other`.
2592
2593 >>> x = Real('x')
2594 >>> y = Real('y')
2595 >>> x * y
2596 x*y
2597 >>> (x * y).sort()
2598 Real
2599 """
2600 if isinstance(other, BoolRef):
2601 return If(other, self, 0)
2602 a, b = _coerce_exprs(self, other)
2603 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctxctxctx)
2604
2605 def __rmul__(self, other):
2606 """Create the Z3 expression `other * self`.
2607
2608 >>> x = Real('x')
2609 >>> 10 * x
2610 10*x
2611 """
2612 a, b = _coerce_exprs(self, other)
2613 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctxctxctx)
2614
2615 def __sub__(self, other):
2616 """Create the Z3 expression `self - other`.
2617
2618 >>> x = Int('x')
2619 >>> y = Int('y')
2620 >>> x - y
2621 x - y
2622 >>> (x - y).sort()
2623 Int
2624 """
2625 a, b = _coerce_exprs(self, other)
2626 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctxctxctx)
2627
2628 def __rsub__(self, other):
2629 """Create the Z3 expression `other - self`.
2630
2631 >>> x = Int('x')
2632 >>> 10 - x
2633 10 - x
2634 """
2635 a, b = _coerce_exprs(self, other)
2636 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctxctxctx)
2637
2638 def __pow__(self, other):
2639 """Create the Z3 expression `self**other` (** is the power operator).
2640
2641 >>> x = Real('x')
2642 >>> x**3
2643 x**3
2644 >>> (x**3).sort()
2645 Real
2646 >>> simplify(IntVal(2)**8)
2647 256
2648 """
2649 a, b = _coerce_exprs(self, other)
2650 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2651
2652 def __rpow__(self, other):
2653 """Create the Z3 expression `other**self` (** is the power operator).
2654
2655 >>> x = Real('x')
2656 >>> 2**x
2657 2**x
2658 >>> (2**x).sort()
2659 Real
2660 >>> simplify(2**IntVal(8))
2661 256
2662 """
2663 a, b = _coerce_exprs(self, other)
2664 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2665
2666 def __div__(self, other):
2667 """Create the Z3 expression `other/self`.
2668
2669 >>> x = Int('x')
2670 >>> y = Int('y')
2671 >>> x/y
2672 x/y
2673 >>> (x/y).sort()
2674 Int
2675 >>> (x/y).sexpr()
2676 '(div x y)'
2677 >>> x = Real('x')
2678 >>> y = Real('y')
2679 >>> x/y
2680 x/y
2681 >>> (x/y).sort()
2682 Real
2683 >>> (x/y).sexpr()
2684 '(/ x y)'
2685 """
2686 a, b = _coerce_exprs(self, other)
2687 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2688
2689 def __truediv__(self, other):
2690 """Create the Z3 expression `other/self`."""
2691 return self.__div__(other)
2692
2693 def __rdiv__(self, other):
2694 """Create the Z3 expression `other/self`.
2695
2696 >>> x = Int('x')
2697 >>> 10/x
2698 10/x
2699 >>> (10/x).sexpr()
2700 '(div 10 x)'
2701 >>> x = Real('x')
2702 >>> 10/x
2703 10/x
2704 >>> (10/x).sexpr()
2705 '(/ 10.0 x)'
2706 """
2707 a, b = _coerce_exprs(self, other)
2708 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2709
2710 def __rtruediv__(self, other):
2711 """Create the Z3 expression `other/self`."""
2712 return self.__rdiv__(other)
2713
2714 def __mod__(self, other):
2715 """Create the Z3 expression `other%self`.
2716
2717 >>> x = Int('x')
2718 >>> y = Int('y')
2719 >>> x % y
2720 x%y
2721 >>> simplify(IntVal(10) % IntVal(3))
2722 1
2723 """
2724 a, b = _coerce_exprs(self, other)
2725 if z3_debug():
2726 _z3_assert(a.is_int(), "Z3 integer expression expected")
2727 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2728
2729 def __rmod__(self, other):
2730 """Create the Z3 expression `other%self`.
2731
2732 >>> x = Int('x')
2733 >>> 10 % x
2734 10%x
2735 """
2736 a, b = _coerce_exprs(self, other)
2737 if z3_debug():
2738 _z3_assert(a.is_int(), "Z3 integer expression expected")
2739 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
2740
2741 def __neg__(self):
2742 """Return an expression representing `-self`.
2743
2744 >>> x = Int('x')
2745 >>> -x
2746 -x
2747 >>> simplify(-(-x))
2748 x
2749 """
2750 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
2751
2752 def __pos__(self):
2753 """Return `self`.
2754
2755 >>> x = Int('x')
2756 >>> +x
2757 x
2758 """
2759 return self
2760
2761 def __le__(self, other):
2762 """Create the Z3 expression `other <= self`.
2763
2764 >>> x, y = Ints('x y')
2765 >>> x <= y
2766 x <= y
2767 >>> y = Real('y')
2768 >>> x <= y
2769 ToReal(x) <= y
2770 """
2771 a, b = _coerce_exprs(self, other)
2772 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2773
2774 def __lt__(self, other):
2775 """Create the Z3 expression `other < self`.
2776
2777 >>> x, y = Ints('x y')
2778 >>> x < y
2779 x < y
2780 >>> y = Real('y')
2781 >>> x < y
2782 ToReal(x) < y
2783 """
2784 a, b = _coerce_exprs(self, other)
2785 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2786
2787 def __gt__(self, other):
2788 """Create the Z3 expression `other > self`.
2789
2790 >>> x, y = Ints('x y')
2791 >>> x > y
2792 x > y
2793 >>> y = Real('y')
2794 >>> x > y
2795 ToReal(x) > y
2796 """
2797 a, b = _coerce_exprs(self, other)
2798 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2799
2800 def __ge__(self, other):
2801 """Create the Z3 expression `other >= self`.
2802
2803 >>> x, y = Ints('x y')
2804 >>> x >= y
2805 x >= y
2806 >>> y = Real('y')
2807 >>> x >= y
2808 ToReal(x) >= y
2809 """
2810 a, b = _coerce_exprs(self, other)
2811 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
2812
2813 def __abs__(self):
2814 """Return an expression representing `abs(self)`.
2815
2816 >>> x = Int('x')
2817 >>> abs(x)
2818 If(x > 0, x, -x)
2819 >>> eq(abs(x), Abs(x))
2820 True
2821 """
2822 return Abs(self)
2823
2824
2826 """Return `True` if `a` is an arithmetical expression.
2827
2828 >>> x = Int('x')
2829 >>> is_arith(x)
2830 True
2831 >>> is_arith(x + 1)
2832 True
2833 >>> is_arith(1)
2834 False
2835 >>> is_arith(IntVal(1))
2836 True
2837 >>> y = Real('y')
2838 >>> is_arith(y)
2839 True
2840 >>> is_arith(y + 1)
2841 True
2842 """
2843 return isinstance(a, ArithRef)
2844
2845
2846def is_int(a) -> bool:
2847 """Return `True` if `a` is an integer expression.
2848
2849 >>> x = Int('x')
2850 >>> is_int(x + 1)
2851 True
2852 >>> is_int(1)
2853 False
2854 >>> is_int(IntVal(1))
2855 True
2856 >>> y = Real('y')
2857 >>> is_int(y)
2858 False
2859 >>> is_int(y + 1)
2860 False
2861 """
2862 return is_arith(a) and a.is_int()
2863
2864
2865def is_real(a):
2866 """Return `True` if `a` is a real expression.
2867
2868 >>> x = Int('x')
2869 >>> is_real(x + 1)
2870 False
2871 >>> y = Real('y')
2872 >>> is_real(y)
2873 True
2874 >>> is_real(y + 1)
2875 True
2876 >>> is_real(1)
2877 False
2878 >>> is_real(RealVal(1))
2879 True
2880 """
2881 return is_arith(a) and a.is_real()
2882
2883
2884def _is_numeral(ctx, a):
2885 return Z3_is_numeral_ast(ctx.ref(), a)
2886
2887
2888def _is_algebraic(ctx, a):
2889 return Z3_is_algebraic_number(ctx.ref(), a)
2890
2891
2893 """Return `True` if `a` is an integer value of sort Int.
2894
2895 >>> is_int_value(IntVal(1))
2896 True
2897 >>> is_int_value(1)
2898 False
2899 >>> is_int_value(Int('x'))
2900 False
2901 >>> n = Int('x') + 1
2902 >>> n
2903 x + 1
2904 >>> n.arg(1)
2905 1
2906 >>> is_int_value(n.arg(1))
2907 True
2908 >>> is_int_value(RealVal("1/3"))
2909 False
2910 >>> is_int_value(RealVal(1))
2911 False
2912 """
2913 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2914
2915
2917 """Return `True` if `a` is rational value of sort Real.
2918
2919 >>> is_rational_value(RealVal(1))
2920 True
2921 >>> is_rational_value(RealVal("3/5"))
2922 True
2923 >>> is_rational_value(IntVal(1))
2924 False
2925 >>> is_rational_value(1)
2926 False
2927 >>> n = Real('x') + 1
2928 >>> n.arg(1)
2929 1
2930 >>> is_rational_value(n.arg(1))
2931 True
2932 >>> is_rational_value(Real('x'))
2933 False
2934 """
2935 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2936
2937
2939 """Return `True` if `a` is an algebraic value of sort Real.
2940
2941 >>> is_algebraic_value(RealVal("3/5"))
2942 False
2943 >>> n = simplify(Sqrt(2))
2944 >>> n
2945 1.4142135623?
2946 >>> is_algebraic_value(n)
2947 True
2948 """
2949 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2950
2951
2952def is_add(a : Any) -> bool:
2953 """Return `True` if `a` is an expression of the form b + c.
2954
2955 >>> x, y = Ints('x y')
2956 >>> is_add(x + y)
2957 True
2958 >>> is_add(x - y)
2959 False
2960 """
2961 return is_app_of(a, Z3_OP_ADD)
2962
2963
2964def is_mul(a : Any) -> bool:
2965 """Return `True` if `a` is an expression of the form b * c.
2966
2967 >>> x, y = Ints('x y')
2968 >>> is_mul(x * y)
2969 True
2970 >>> is_mul(x - y)
2971 False
2972 """
2973 return is_app_of(a, Z3_OP_MUL)
2974
2975
2976def is_sub(a : Any) -> bool:
2977 """Return `True` if `a` is an expression of the form b - c.
2978
2979 >>> x, y = Ints('x y')
2980 >>> is_sub(x - y)
2981 True
2982 >>> is_sub(x + y)
2983 False
2984 """
2985 return is_app_of(a, Z3_OP_SUB)
2986
2987
2988def is_div(a : Any) -> bool:
2989 """Return `True` if `a` is an expression of the form b / c.
2990
2991 >>> x, y = Reals('x y')
2992 >>> is_div(x / y)
2993 True
2994 >>> is_div(x + y)
2995 False
2996 >>> x, y = Ints('x y')
2997 >>> is_div(x / y)
2998 False
2999 >>> is_idiv(x / y)
3000 True
3001 """
3002 return is_app_of(a, Z3_OP_DIV)
3003
3004
3005def is_idiv(a : Any) -> bool:
3006 """Return `True` if `a` is an expression of the form b div c.
3007
3008 >>> x, y = Ints('x y')
3009 >>> is_idiv(x / y)
3010 True
3011 >>> is_idiv(x + y)
3012 False
3013 """
3014 return is_app_of(a, Z3_OP_IDIV)
3015
3016
3017def is_mod(a : Any) -> bool:
3018 """Return `True` if `a` is an expression of the form b % c.
3019
3020 >>> x, y = Ints('x y')
3021 >>> is_mod(x % y)
3022 True
3023 >>> is_mod(x + y)
3024 False
3025 """
3026 return is_app_of(a, Z3_OP_MOD)
3027
3028
3029def is_le(a : Any) -> bool:
3030 """Return `True` if `a` is an expression of the form b <= c.
3031
3032 >>> x, y = Ints('x y')
3033 >>> is_le(x <= y)
3034 True
3035 >>> is_le(x < y)
3036 False
3037 """
3038 return is_app_of(a, Z3_OP_LE)
3039
3040
3041def is_lt(a : Any) -> bool:
3042 """Return `True` if `a` is an expression of the form b < c.
3043
3044 >>> x, y = Ints('x y')
3045 >>> is_lt(x < y)
3046 True
3047 >>> is_lt(x == y)
3048 False
3049 """
3050 return is_app_of(a, Z3_OP_LT)
3051
3052
3053def is_ge(a : Any) -> bool:
3054 """Return `True` if `a` is an expression of the form b >= c.
3055
3056 >>> x, y = Ints('x y')
3057 >>> is_ge(x >= y)
3058 True
3059 >>> is_ge(x == y)
3060 False
3061 """
3062 return is_app_of(a, Z3_OP_GE)
3063
3064
3065def is_gt(a : Any) -> bool:
3066 """Return `True` if `a` is an expression of the form b > c.
3067
3068 >>> x, y = Ints('x y')
3069 >>> is_gt(x > y)
3070 True
3071 >>> is_gt(x == y)
3072 False
3073 """
3074 return is_app_of(a, Z3_OP_GT)
3075
3076
3077def is_is_int(a : Any) -> bool:
3078 """Return `True` if `a` is an expression of the form IsInt(b).
3079
3080 >>> x = Real('x')
3081 >>> is_is_int(IsInt(x))
3082 True
3083 >>> is_is_int(x)
3084 False
3085 """
3086 return is_app_of(a, Z3_OP_IS_INT)
3087
3088
3089def is_to_real(a : Any) -> bool:
3090 """Return `True` if `a` is an expression of the form ToReal(b).
3091
3092 >>> x = Int('x')
3093 >>> n = ToReal(x)
3094 >>> n
3095 ToReal(x)
3096 >>> is_to_real(n)
3097 True
3098 >>> is_to_real(x)
3099 False
3100 """
3101 return is_app_of(a, Z3_OP_TO_REAL)
3102
3103
3104def is_to_int(a : Any) -> bool:
3105 """Return `True` if `a` is an expression of the form ToInt(b).
3106
3107 >>> x = Real('x')
3108 >>> n = ToInt(x)
3109 >>> n
3110 ToInt(x)
3111 >>> is_to_int(n)
3112 True
3113 >>> is_to_int(x)
3114 False
3115 """
3116 return is_app_of(a, Z3_OP_TO_INT)
3117
3118
3120 """Integer values."""
3121
3122 def as_long(self):
3123 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3124
3125 >>> v = IntVal(1)
3126 >>> v + 1
3127 1 + 1
3128 >>> v.as_long() + 1
3129 2
3130 """
3131 if z3_debug():
3132 _z3_assert(self.is_int(), "Integer value expected")
3133 return int(self.as_string())
3134
3135 def as_string(self):
3136 """Return a Z3 integer numeral as a Python string.
3137 >>> v = IntVal(100)
3138 >>> v.as_string()
3139 '100'
3140 """
3141 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3142
3144 """Return a Z3 integer numeral as a Python binary string.
3145 >>> v = IntVal(10)
3146 >>> v.as_binary_string()
3147 '1010'
3148 """
3150
3151 def py_value(self):
3152 return self.as_long()
3153
3154
3156 """Rational values."""
3157
3158 def numerator(self):
3159 """ Return the numerator of a Z3 rational numeral.
3160
3161 >>> is_rational_value(RealVal("3/5"))
3162 True
3163 >>> n = RealVal("3/5")
3164 >>> n.numerator()
3165 3
3166 >>> is_rational_value(Q(3,5))
3167 True
3168 >>> Q(3,5).numerator()
3169 3
3170 """
3172
3173 def denominator(self):
3174 """ Return the denominator of a Z3 rational numeral.
3175
3176 >>> is_rational_value(Q(3,5))
3177 True
3178 >>> n = Q(3,5)
3179 >>> n.denominator()
3180 5
3181 """
3182 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctxctx)
3183
3185 """ Return the numerator as a Python long.
3186
3187 >>> v = RealVal(10000000000)
3188 >>> v
3189 10000000000
3190 >>> v + 1
3191 10000000000 + 1
3192 >>> v.numerator_as_long() + 1 == 10000000001
3193 True
3194 """
3195 return self.numerator().as_long()
3196
3198 """ Return the denominator as a Python long.
3199
3200 >>> v = RealVal("1/3")
3201 >>> v
3202 1/3
3203 >>> v.denominator_as_long()
3204 3
3205 """
3206 return self.denominator().as_long()
3207
3208 def is_int(self):
3209 return False
3210
3211 def is_real(self):
3212 return True
3213
3214 def is_int_value(self):
3215 return self.denominator().is_int() and self.denominator_as_long() == 1
3216
3217 def as_long(self):
3218 _z3_assert(self.is_int_value(), "Expected integer fraction")
3219 return self.numerator_as_long()
3220
3221 def as_decimal(self, prec):
3222 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3223
3224 >>> v = RealVal("1/5")
3225 >>> v.as_decimal(3)
3226 '0.2'
3227 >>> v = RealVal("1/3")
3228 >>> v.as_decimal(3)
3229 '0.333?'
3230 """
3231 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3232
3233 def as_string(self):
3234 """Return a Z3 rational numeral as a Python string.
3235
3236 >>> v = Q(3,6)
3237 >>> v.as_string()
3238 '1/2'
3239 """
3240 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3241
3242 def as_fraction(self):
3243 """Return a Z3 rational as a Python Fraction object.
3244
3245 >>> v = RealVal("1/5")
3246 >>> v.as_fraction()
3247 Fraction(1, 5)
3248 """
3249 return Fraction(self.numerator_as_long(), self.denominator_as_long())
3250
3251 def py_value(self):
3252 return Z3_get_numeral_double(self.ctx_ref(), self.as_astas_ast())
3253
3254
3256 """Algebraic irrational values."""
3257
3258 def approx(self, precision=10):
3259 """Return a Z3 rational number that approximates the algebraic number `self`.
3260 The result `r` is such that |r - self| <= 1/10^precision
3261
3262 >>> x = simplify(Sqrt(2))
3263 >>> x.approx(20)
3264 6838717160008073720548335/4835703278458516698824704
3265 >>> x.approx(5)
3266 2965821/2097152
3267 """
3269
3270 def as_decimal(self, prec):
3271 """Return a string representation of the algebraic number `self` in decimal notation
3272 using `prec` decimal places.
3273
3274 >>> x = simplify(Sqrt(2))
3275 >>> x.as_decimal(10)
3276 '1.4142135623?'
3277 >>> x.as_decimal(20)
3278 '1.41421356237309504880?'
3279 """
3280 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
3281
3282 def poly(self):
3284
3285 def index(self):
3286 return Z3_algebraic_get_i(self.ctx_ref(), self.as_astas_ast())
3287
3288
3289def _py2expr(a, ctx=None):
3290 if isinstance(a, bool):
3291 return BoolVal(a, ctx)
3292 if _is_int(a):
3293 return IntVal(a, ctx)
3294 if isinstance(a, float):
3295 return RealVal(a, ctx)
3296 if isinstance(a, str):
3297 return StringVal(a, ctx)
3298 if is_expr(a):
3299 return a
3300 if z3_debug():
3301 _z3_assert(False, "Python bool, int, long or float expected")
3302
3303
3304def IntSort(ctx=None):
3305 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3306
3307 >>> IntSort()
3308 Int
3309 >>> x = Const('x', IntSort())
3310 >>> is_int(x)
3311 True
3312 >>> x.sort() == IntSort()
3313 True
3314 >>> x.sort() == BoolSort()
3315 False
3316 """
3317 ctx = _get_ctx(ctx)
3318 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
3319
3320
3321def RealSort(ctx=None):
3322 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3323
3324 >>> RealSort()
3325 Real
3326 >>> x = Const('x', RealSort())
3327 >>> is_real(x)
3328 True
3329 >>> is_int(x)
3330 False
3331 >>> x.sort() == RealSort()
3332 True
3333 """
3334 ctx = _get_ctx(ctx)
3335 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
3336
3337
3339 if isinstance(val, float):
3340 return str(int(val))
3341 elif isinstance(val, bool):
3342 if val:
3343 return "1"
3344 else:
3345 return "0"
3346 else:
3347 return str(val)
3348
3349
3350def IntVal(val, ctx=None):
3351 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3352
3353 >>> IntVal(1)
3354 1
3355 >>> IntVal("100")
3356 100
3357 """
3358 ctx = _get_ctx(ctx)
3359 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
3360
3361
3362def RealVal(val, ctx=None):
3363 """Return a Z3 real value.
3364
3365 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3366 If `ctx=None`, then the global context is used.
3367
3368 >>> RealVal(1)
3369 1
3370 >>> RealVal(1).sort()
3371 Real
3372 >>> RealVal("3/5")
3373 3/5
3374 >>> RealVal("1.5")
3375 3/2
3376 """
3377 ctx = _get_ctx(ctx)
3378 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
3379
3380
3381def RatVal(a, b, ctx=None):
3382 """Return a Z3 rational a/b.
3383
3384 If `ctx=None`, then the global context is used.
3385
3386 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3387 Z3 can reason about such expressions symbolically.
3388
3389 >>> RatVal(3,5)
3390 3/5
3391 >>> RatVal(3,5).sort()
3392 Real
3393 """
3394 if z3_debug():
3395 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
3396 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
3397 # Division by 0 is intentionally allowed - Z3 handles it symbolically
3398 return simplify(RealVal(a, ctx) / RealVal(b, ctx))
3399
3400
3401def Q(a, b, ctx=None):
3402 """Return a Z3 rational a/b.
3403
3404 If `ctx=None`, then the global context is used.
3405
3406 >>> Q(3,5)
3407 3/5
3408 >>> Q(3,5).sort()
3409 Real
3410 """
3411 return simplify(RatVal(a, b, ctx=ctx))
3412
3413
3414def Int(name, ctx=None):
3415 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3416
3417 >>> x = Int('x')
3418 >>> is_int(x)
3419 True
3420 >>> is_int(x + 1)
3421 True
3422 """
3423 ctx = _get_ctx(ctx)
3424 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3425
3426
3427def Ints(names, ctx=None):
3428 """Return a tuple of Integer constants.
3429
3430 >>> x, y, z = Ints('x y z')
3431 >>> Sum(x, y, z)
3432 x + y + z
3433 """
3434 ctx = _get_ctx(ctx)
3435 if isinstance(names, str):
3436 names = names.split(" ")
3437 return [Int(name, ctx) for name in names]
3438
3439
3440def IntVector(prefix, sz, ctx=None):
3441 """Return a list of integer constants of size `sz`.
3442
3443 >>> X = IntVector('x', 3)
3444 >>> X
3445 [x__0, x__1, x__2]
3446 >>> Sum(X)
3447 x__0 + x__1 + x__2
3448 """
3449 ctx = _get_ctx(ctx)
3450 return [Int("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3451
3452
3453def FreshInt(prefix="x", ctx=None):
3454 """Return a fresh integer constant in the given context using the given prefix.
3455
3456 >>> x = FreshInt()
3457 >>> y = FreshInt()
3458 >>> eq(x, y)
3459 False
3460 >>> x.sort()
3461 Int
3462 """
3463 ctx = _get_ctx(ctx)
3464 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3465
3466
3467def Real(name, ctx=None):
3468 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3469
3470 >>> x = Real('x')
3471 >>> is_real(x)
3472 True
3473 >>> is_real(x + 1)
3474 True
3475 """
3476 ctx = _get_ctx(ctx)
3477 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3478
3479
3480def Reals(names, ctx=None):
3481 """Return a tuple of real constants.
3482
3483 >>> x, y, z = Reals('x y z')
3484 >>> Sum(x, y, z)
3485 x + y + z
3486 >>> Sum(x, y, z).sort()
3487 Real
3488 """
3489 ctx = _get_ctx(ctx)
3490 if isinstance(names, str):
3491 names = names.split(" ")
3492 return [Real(name, ctx) for name in names]
3493
3494
3495def RealVector(prefix, sz, ctx=None):
3496 """Return a list of real constants of size `sz`.
3497
3498 >>> X = RealVector('x', 3)
3499 >>> X
3500 [x__0, x__1, x__2]
3501 >>> Sum(X)
3502 x__0 + x__1 + x__2
3503 >>> Sum(X).sort()
3504 Real
3505 """
3506 ctx = _get_ctx(ctx)
3507 return [Real("%s__%s" % (prefix, i), ctx) for i in range(sz)]
3508
3509
3510def FreshReal(prefix="b", ctx=None):
3511 """Return a fresh real constant in the given context using the given prefix.
3512
3513 >>> x = FreshReal()
3514 >>> y = FreshReal()
3515 >>> eq(x, y)
3516 False
3517 >>> x.sort()
3518 Real
3519 """
3520 ctx = _get_ctx(ctx)
3521 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3522
3523
3524def ToReal(a):
3525 """ Return the Z3 expression ToReal(a).
3526
3527 >>> x = Int('x')
3528 >>> x.sort()
3529 Int
3530 >>> n = ToReal(x)
3531 >>> n
3532 ToReal(x)
3533 >>> n.sort()
3534 Real
3535 """
3536 ctx = a.ctx
3537 if isinstance(a, BoolRef):
3538 return If(a, RealVal(1, ctx), RealVal(0, ctx))
3539 if z3_debug():
3540 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3541 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3542
3543
3544def ToInt(a):
3545 """ Return the Z3 expression ToInt(a).
3546
3547 >>> x = Real('x')
3548 >>> x.sort()
3549 Real
3550 >>> n = ToInt(x)
3551 >>> n
3552 ToInt(x)
3553 >>> n.sort()
3554 Int
3555 """
3556 if z3_debug():
3557 _z3_assert(a.is_real(), "Z3 real expression expected.")
3558 ctx = a.ctx
3559 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3560
3561
3562def IsInt(a):
3563 """ Return the Z3 predicate IsInt(a).
3564
3565 >>> x = Real('x')
3566 >>> IsInt(x + "1/2")
3567 IsInt(x + 1/2)
3568 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3569 [x = 1/2]
3570 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3571 no solution
3572 """
3573 if z3_debug():
3574 _z3_assert(a.is_real(), "Z3 real expression expected.")
3575 ctx = a.ctx
3576 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3577
3578
3579def Sqrt(a, ctx=None):
3580 """ Return a Z3 expression which represents the square root of a.
3581
3582 >>> x = Real('x')
3583 >>> Sqrt(x)
3584 x**(1/2)
3585 """
3586 if not is_expr(a):
3587 ctx = _get_ctx(ctx)
3588 a = RealVal(a, ctx)
3589 return a ** "1/2"
3590
3591
3592def Cbrt(a, ctx=None):
3593 """ Return a Z3 expression which represents the cubic root of a.
3594
3595 >>> x = Real('x')
3596 >>> Cbrt(x)
3597 x**(1/3)
3598 """
3599 if not is_expr(a):
3600 ctx = _get_ctx(ctx)
3601 a = RealVal(a, ctx)
3602 return a ** "1/3"
3603
3604
3609
3610
3612 """Bit-vector sort."""
3613
3614 def size(self):
3615 """Return the size (number of bits) of the bit-vector sort `self`.
3616
3617 >>> b = BitVecSort(32)
3618 >>> b.size()
3619 32
3620 """
3621 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.astastast))
3622
3623 def subsort(self, other):
3624 return is_bv_sort(other) and self.size() < other.size()
3625
3626 def cast(self, val):
3627 """Try to cast `val` as a Bit-Vector.
3628
3629 >>> b = BitVecSort(32)
3630 >>> b.cast(10)
3631 10
3632 >>> b.cast(10).sexpr()
3633 '#x0000000a'
3634 """
3635 if is_expr(val):
3636 if z3_debug():
3637 _z3_assert(self.ctxctxctx == val.ctx, "Context mismatch")
3638 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3639 return val
3640 else:
3641 return BitVecVal(val, self)
3642
3643
3645 """Return True if `s` is a Z3 bit-vector sort.
3646
3647 >>> is_bv_sort(BitVecSort(32))
3648 True
3649 >>> is_bv_sort(IntSort())
3650 False
3651 """
3652 return isinstance(s, BitVecSortRef)
3653
3654
3656 """Bit-vector expressions."""
3657
3658 def sort(self):
3659 """Return the sort of the bit-vector expression `self`.
3660
3661 >>> x = BitVec('x', 32)
3662 >>> x.sort()
3663 BitVec(32)
3664 >>> x.sort() == BitVecSort(32)
3665 True
3666 """
3668
3669 def size(self):
3670 """Return the number of bits of the bit-vector expression `self`.
3671
3672 >>> x = BitVec('x', 32)
3673 >>> (x + 1).size()
3674 32
3675 >>> Concat(x, x).size()
3676 64
3677 """
3678 return self.sortsort().size()
3679
3680 def __add__(self, other):
3681 """Create the Z3 expression `self + other`.
3682
3683 >>> x = BitVec('x', 32)
3684 >>> y = BitVec('y', 32)
3685 >>> x + y
3686 x + y
3687 >>> (x + y).sort()
3688 BitVec(32)
3689 """
3690 a, b = _coerce_exprs(self, other)
3691 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3692
3693 def __radd__(self, other):
3694 """Create the Z3 expression `other + self`.
3695
3696 >>> x = BitVec('x', 32)
3697 >>> 10 + x
3698 10 + x
3699 """
3700 a, b = _coerce_exprs(self, other)
3701 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3702
3703 def __mul__(self, other):
3704 """Create the Z3 expression `self * other`.
3705
3706 >>> x = BitVec('x', 32)
3707 >>> y = BitVec('y', 32)
3708 >>> x * y
3709 x*y
3710 >>> (x * y).sort()
3711 BitVec(32)
3712 """
3713 a, b = _coerce_exprs(self, other)
3714 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3715
3716 def __rmul__(self, other):
3717 """Create the Z3 expression `other * self`.
3718
3719 >>> x = BitVec('x', 32)
3720 >>> 10 * x
3721 10*x
3722 """
3723 a, b = _coerce_exprs(self, other)
3724 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3725
3726 def __sub__(self, other):
3727 """Create the Z3 expression `self - other`.
3728
3729 >>> x = BitVec('x', 32)
3730 >>> y = BitVec('y', 32)
3731 >>> x - y
3732 x - y
3733 >>> (x - y).sort()
3734 BitVec(32)
3735 """
3736 a, b = _coerce_exprs(self, other)
3737 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3738
3739 def __rsub__(self, other):
3740 """Create the Z3 expression `other - self`.
3741
3742 >>> x = BitVec('x', 32)
3743 >>> 10 - x
3744 10 - x
3745 """
3746 a, b = _coerce_exprs(self, other)
3747 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3748
3749 def __or__(self, other):
3750 """Create the Z3 expression bitwise-or `self | other`.
3751
3752 >>> x = BitVec('x', 32)
3753 >>> y = BitVec('y', 32)
3754 >>> x | y
3755 x | y
3756 >>> (x | y).sort()
3757 BitVec(32)
3758 """
3759 a, b = _coerce_exprs(self, other)
3760 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3761
3762 def __ror__(self, other):
3763 """Create the Z3 expression bitwise-or `other | self`.
3764
3765 >>> x = BitVec('x', 32)
3766 >>> 10 | x
3767 10 | x
3768 """
3769 a, b = _coerce_exprs(self, other)
3770 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3771
3772 def __and__(self, other):
3773 """Create the Z3 expression bitwise-and `self & other`.
3774
3775 >>> x = BitVec('x', 32)
3776 >>> y = BitVec('y', 32)
3777 >>> x & y
3778 x & y
3779 >>> (x & y).sort()
3780 BitVec(32)
3781 """
3782 a, b = _coerce_exprs(self, other)
3783 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3784
3785 def __rand__(self, other):
3786 """Create the Z3 expression bitwise-or `other & self`.
3787
3788 >>> x = BitVec('x', 32)
3789 >>> 10 & x
3790 10 & x
3791 """
3792 a, b = _coerce_exprs(self, other)
3793 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3794
3795 def __xor__(self, other):
3796 """Create the Z3 expression bitwise-xor `self ^ other`.
3797
3798 >>> x = BitVec('x', 32)
3799 >>> y = BitVec('y', 32)
3800 >>> x ^ y
3801 x ^ y
3802 >>> (x ^ y).sort()
3803 BitVec(32)
3804 """
3805 a, b = _coerce_exprs(self, other)
3806 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3807
3808 def __rxor__(self, other):
3809 """Create the Z3 expression bitwise-xor `other ^ self`.
3810
3811 >>> x = BitVec('x', 32)
3812 >>> 10 ^ x
3813 10 ^ x
3814 """
3815 a, b = _coerce_exprs(self, other)
3816 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3817
3818 def __pos__(self):
3819 """Return `self`.
3820
3821 >>> x = BitVec('x', 32)
3822 >>> +x
3823 x
3824 """
3825 return self
3826
3827 def __neg__(self):
3828 """Return an expression representing `-self`.
3829
3830 >>> x = BitVec('x', 32)
3831 >>> -x
3832 -x
3833 >>> simplify(-(-x))
3834 x
3835 """
3836 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
3837
3838 def __invert__(self):
3839 """Create the Z3 expression bitwise-not `~self`.
3840
3841 >>> x = BitVec('x', 32)
3842 >>> ~x
3843 ~x
3844 >>> simplify(~(~x))
3845 x
3846 """
3847 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
3848
3849 def __div__(self, other):
3850 """Create the Z3 expression (signed) division `self / other`.
3851
3852 Use the function UDiv() for unsigned division.
3853
3854 >>> x = BitVec('x', 32)
3855 >>> y = BitVec('y', 32)
3856 >>> x / y
3857 x/y
3858 >>> (x / y).sort()
3859 BitVec(32)
3860 >>> (x / y).sexpr()
3861 '(bvsdiv x y)'
3862 >>> UDiv(x, y).sexpr()
3863 '(bvudiv x y)'
3864 """
3865 a, b = _coerce_exprs(self, other)
3866 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3867
3868 def __truediv__(self, other):
3869 """Create the Z3 expression (signed) division `self / other`."""
3870 return self.__div__(other)
3871
3872 def __rdiv__(self, other):
3873 """Create the Z3 expression (signed) division `other / self`.
3874
3875 Use the function UDiv() for unsigned division.
3876
3877 >>> x = BitVec('x', 32)
3878 >>> 10 / x
3879 10/x
3880 >>> (10 / x).sexpr()
3881 '(bvsdiv #x0000000a x)'
3882 >>> UDiv(10, x).sexpr()
3883 '(bvudiv #x0000000a x)'
3884 """
3885 a, b = _coerce_exprs(self, other)
3886 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3887
3888 def __rtruediv__(self, other):
3889 """Create the Z3 expression (signed) division `other / self`."""
3890 return self.__rdiv__(other)
3891
3892 def __mod__(self, other):
3893 """Create the Z3 expression (signed) mod `self % other`.
3894
3895 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3896
3897 >>> x = BitVec('x', 32)
3898 >>> y = BitVec('y', 32)
3899 >>> x % y
3900 x%y
3901 >>> (x % y).sort()
3902 BitVec(32)
3903 >>> (x % y).sexpr()
3904 '(bvsmod x y)'
3905 >>> URem(x, y).sexpr()
3906 '(bvurem x y)'
3907 >>> SRem(x, y).sexpr()
3908 '(bvsrem x y)'
3909 """
3910 a, b = _coerce_exprs(self, other)
3911 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3912
3913 def __rmod__(self, other):
3914 """Create the Z3 expression (signed) mod `other % self`.
3915
3916 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3917
3918 >>> x = BitVec('x', 32)
3919 >>> 10 % x
3920 10%x
3921 >>> (10 % x).sexpr()
3922 '(bvsmod #x0000000a x)'
3923 >>> URem(10, x).sexpr()
3924 '(bvurem #x0000000a x)'
3925 >>> SRem(10, x).sexpr()
3926 '(bvsrem #x0000000a x)'
3927 """
3928 a, b = _coerce_exprs(self, other)
3929 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
3930
3931 def __le__(self, other):
3932 """Create the Z3 expression (signed) `other <= self`.
3933
3934 Use the function ULE() for unsigned less than or equal to.
3935
3936 >>> x, y = BitVecs('x y', 32)
3937 >>> x <= y
3938 x <= y
3939 >>> (x <= y).sexpr()
3940 '(bvsle x y)'
3941 >>> ULE(x, y).sexpr()
3942 '(bvule x y)'
3943 """
3944 a, b = _coerce_exprs(self, other)
3945 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3946
3947 def __lt__(self, other):
3948 """Create the Z3 expression (signed) `other < self`.
3949
3950 Use the function ULT() for unsigned less than.
3951
3952 >>> x, y = BitVecs('x y', 32)
3953 >>> x < y
3954 x < y
3955 >>> (x < y).sexpr()
3956 '(bvslt x y)'
3957 >>> ULT(x, y).sexpr()
3958 '(bvult x y)'
3959 """
3960 a, b = _coerce_exprs(self, other)
3961 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3962
3963 def __gt__(self, other):
3964 """Create the Z3 expression (signed) `other > self`.
3965
3966 Use the function UGT() for unsigned greater than.
3967
3968 >>> x, y = BitVecs('x y', 32)
3969 >>> x > y
3970 x > y
3971 >>> (x > y).sexpr()
3972 '(bvsgt x y)'
3973 >>> UGT(x, y).sexpr()
3974 '(bvugt x y)'
3975 """
3976 a, b = _coerce_exprs(self, other)
3977 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3978
3979 def __ge__(self, other):
3980 """Create the Z3 expression (signed) `other >= self`.
3981
3982 Use the function UGE() for unsigned greater than or equal to.
3983
3984 >>> x, y = BitVecs('x y', 32)
3985 >>> x >= y
3986 x >= y
3987 >>> (x >= y).sexpr()
3988 '(bvsge x y)'
3989 >>> UGE(x, y).sexpr()
3990 '(bvuge x y)'
3991 """
3992 a, b = _coerce_exprs(self, other)
3993 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
3994
3995 def __rshift__(self, other):
3996 """Create the Z3 expression (arithmetical) right shift `self >> other`
3997
3998 Use the function LShR() for the right logical shift
3999
4000 >>> x, y = BitVecs('x y', 32)
4001 >>> x >> y
4002 x >> y
4003 >>> (x >> y).sexpr()
4004 '(bvashr x y)'
4005 >>> LShR(x, y).sexpr()
4006 '(bvlshr x y)'
4007 >>> BitVecVal(4, 3)
4008 4
4009 >>> BitVecVal(4, 3).as_signed_long()
4010 -4
4011 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4012 -2
4013 >>> simplify(BitVecVal(4, 3) >> 1)
4014 6
4015 >>> simplify(LShR(BitVecVal(4, 3), 1))
4016 2
4017 >>> simplify(BitVecVal(2, 3) >> 1)
4018 1
4019 >>> simplify(LShR(BitVecVal(2, 3), 1))
4020 1
4021 """
4022 a, b = _coerce_exprs(self, other)
4023 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4024
4025 def __lshift__(self, other):
4026 """Create the Z3 expression left shift `self << other`
4027
4028 >>> x, y = BitVecs('x y', 32)
4029 >>> x << y
4030 x << y
4031 >>> (x << y).sexpr()
4032 '(bvshl x y)'
4033 >>> simplify(BitVecVal(2, 3) << 1)
4034 4
4035 """
4036 a, b = _coerce_exprs(self, other)
4037 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctxctxctx)
4038
4039 def __rrshift__(self, other):
4040 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4041
4042 Use the function LShR() for the right logical shift
4043
4044 >>> x = BitVec('x', 32)
4045 >>> 10 >> x
4046 10 >> x
4047 >>> (10 >> x).sexpr()
4048 '(bvashr #x0000000a x)'
4049 """
4050 a, b = _coerce_exprs(self, other)
4051 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
4052
4053 def __rlshift__(self, other):
4054 """Create the Z3 expression left shift `other << self`.
4055
4056 Use the function LShR() for the right logical shift
4057
4058 >>> x = BitVec('x', 32)
4059 >>> 10 << x
4060 10 << x
4061 >>> (10 << x).sexpr()
4062 '(bvshl #x0000000a x)'
4063 """
4064 a, b = _coerce_exprs(self, other)
4065 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctxctxctx)
4066
4067
4069 """Bit-vector values."""
4070
4071 def as_long(self):
4072 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4073
4074 >>> v = BitVecVal(0xbadc0de, 32)
4075 >>> v
4076 195936478
4077 >>> print("0x%.8x" % v.as_long())
4078 0x0badc0de
4079 """
4080 return int(self.as_string())
4081
4083 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4084 The most significant bit is assumed to be the sign.
4085
4086 >>> BitVecVal(4, 3).as_signed_long()
4087 -4
4088 >>> BitVecVal(7, 3).as_signed_long()
4089 -1
4090 >>> BitVecVal(3, 3).as_signed_long()
4091 3
4092 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4093 -1
4094 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4095 -1
4096 """
4097 sz = self.size()
4098 val = self.as_long()
4099 if val >= 2**(sz - 1):
4100 val = val - 2**sz
4101 if val < -2**(sz - 1):
4102 val = val + 2**sz
4103 return int(val)
4104
4105 def as_string(self):
4106 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
4107
4110
4111 def py_value(self):
4112 """Return the Python value of a Z3 bit-vector numeral."""
4113 return self.as_long()
4114
4115
4116
4117def is_bv(a):
4118 """Return `True` if `a` is a Z3 bit-vector expression.
4119
4120 >>> b = BitVec('b', 32)
4121 >>> is_bv(b)
4122 True
4123 >>> is_bv(b + 10)
4124 True
4125 >>> is_bv(Int('x'))
4126 False
4127 """
4128 return isinstance(a, BitVecRef)
4129
4130
4132 """Return `True` if `a` is a Z3 bit-vector numeral value.
4133
4134 >>> b = BitVec('b', 32)
4135 >>> is_bv_value(b)
4136 False
4137 >>> b = BitVecVal(10, 32)
4138 >>> b
4139 10
4140 >>> is_bv_value(b)
4141 True
4142 """
4143 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
4144
4145
4146def BV2Int(a, is_signed=False):
4147 """Return the Z3 expression BV2Int(a).
4148
4149 >>> b = BitVec('b', 3)
4150 >>> BV2Int(b).sort()
4151 Int
4152 >>> x = Int('x')
4153 >>> x > BV2Int(b)
4154 x > BV2Int(b)
4155 >>> x > BV2Int(b, is_signed=False)
4156 x > BV2Int(b)
4157 >>> x > BV2Int(b, is_signed=True)
4158 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4159 >>> solve(x > BV2Int(b), b == 1, x < 3)
4160 [x = 2, b = 1]
4161 """
4162 if z3_debug():
4163 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4164 ctx = a.ctx
4165 # investigate problem with bv2int
4166 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
4167
4168
4169def Int2BV(a, num_bits):
4170 """Return the z3 expression Int2BV(a, num_bits).
4171 It is a bit-vector of width num_bits and represents the
4172 modulo of a by 2^num_bits
4173 """
4174 ctx = a.ctx
4175 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
4176
4177
4178def BitVecSort(sz, ctx=None):
4179 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4180
4181 >>> Byte = BitVecSort(8)
4182 >>> Word = BitVecSort(16)
4183 >>> Byte
4184 BitVec(8)
4185 >>> x = Const('x', Byte)
4186 >>> eq(x, BitVec('x', 8))
4187 True
4188 """
4189 ctx = _get_ctx(ctx)
4190 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
4191
4192
4193def BitVecVal(val, bv, ctx=None):
4194 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4195
4196 >>> v = BitVecVal(10, 32)
4197 >>> v
4198 10
4199 >>> print("0x%.8x" % v.as_long())
4200 0x0000000a
4201 """
4202 if is_bv_sort(bv):
4203 ctx = bv.ctx
4204 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
4205 else:
4206 ctx = _get_ctx(ctx)
4207 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
4208
4209
4210def BitVec(name, bv, ctx=None):
4211 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4212 If `ctx=None`, then the global context is used.
4213
4214 >>> x = BitVec('x', 16)
4215 >>> is_bv(x)
4216 True
4217 >>> x.size()
4218 16
4219 >>> x.sort()
4220 BitVec(16)
4221 >>> word = BitVecSort(16)
4222 >>> x2 = BitVec('x', word)
4223 >>> eq(x, x2)
4224 True
4225 """
4226 if isinstance(bv, BitVecSortRef):
4227 ctx = bv.ctx
4228 else:
4229 ctx = _get_ctx(ctx)
4230 bv = BitVecSort(bv, ctx)
4231 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
4232
4233
4234def BitVecs(names, bv, ctx=None):
4235 """Return a tuple of bit-vector constants of size bv.
4236
4237 >>> x, y, z = BitVecs('x y z', 16)
4238 >>> x.size()
4239 16
4240 >>> x.sort()
4241 BitVec(16)
4242 >>> Sum(x, y, z)
4243 0 + x + y + z
4244 >>> Product(x, y, z)
4245 1*x*y*z
4246 >>> simplify(Product(x, y, z))
4247 x*y*z
4248 """
4249 ctx = _get_ctx(ctx)
4250 if isinstance(names, str):
4251 names = names.split(" ")
4252 return [BitVec(name, bv, ctx) for name in names]
4253
4254
4255def Concat(*args):
4256 """Create a Z3 bit-vector concatenation expression.
4257
4258 >>> v = BitVecVal(1, 4)
4259 >>> Concat(v, v+1, v)
4260 Concat(Concat(1, 1 + 1), 1)
4261 >>> simplify(Concat(v, v+1, v))
4262 289
4263 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4264 121
4265 """
4266 args = _get_args(args)
4267 sz = len(args)
4268 if z3_debug():
4269 _z3_assert(sz >= 2, "At least two arguments expected.")
4270
4271 ctx = None
4272 for a in args:
4273 if is_expr(a):
4274 ctx = a.ctx
4275 break
4276 if is_seq(args[0]) or isinstance(args[0], str):
4277 args = [_coerce_seq(s, ctx) for s in args]
4278 if z3_debug():
4279 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
4280 v = (Ast * sz)()
4281 for i in range(sz):
4282 v[i] = args[i].as_ast()
4283 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
4284
4285 if is_re(args[0]):
4286 if z3_debug():
4287 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
4288 v = (Ast * sz)()
4289 for i in range(sz):
4290 v[i] = args[i].as_ast()
4291 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
4292
4293 if z3_debug():
4294 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
4295 r = args[0]
4296 for i in range(sz - 1):
4297 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i + 1].as_ast()), ctx)
4298 return r
4299
4300
4301def Extract(high, low, a):
4302 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4303
4304 Extract is overloaded to work with both bit-vectors and sequences:
4305
4306 **Bit-vector extraction**: Extract(high, low, bitvector)
4307 Extracts bits from position `high` down to position `low` (both inclusive).
4308 - high: int - the highest bit position to extract (0-indexed from right)
4309 - low: int - the lowest bit position to extract (0-indexed from right)
4310 - bitvector: BitVecRef - the bit-vector to extract from
4311 Returns a new bit-vector containing bits [high:low]
4312
4313 **Sequence extraction**: Extract(sequence, offset, length)
4314 Extracts a subsequence starting at the given offset with the specified length.
4315 The functions SubString and SubSeq are redirected to this form of Extract.
4316 - sequence: SeqRef or str - the sequence to extract from
4317 - offset: int - the starting position (0-indexed)
4318 - length: int - the number of elements to extract
4319 Returns a new sequence containing the extracted subsequence
4320
4321 >>> # Bit-vector extraction examples
4322 >>> x = BitVec('x', 8)
4323 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4324 Extract(6, 2, x)
4325 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4326 BitVec(5)
4327 >>> Extract(7, 0, x) # Extract all 8 bits
4328 Extract(7, 0, x)
4329 >>> Extract(3, 3, x) # Extract single bit at position 3
4330 Extract(3, 3, x)
4331
4332 >>> # Sequence extraction examples
4333 >>> s = StringVal("hello")
4334 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4335 str.substr("hello", 1, 3)
4336 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4337 "c"
4338 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4339 "ab"
4340 """
4341 if isinstance(high, str):
4342 high = StringVal(high)
4343 if is_seq(high):
4344 s = high
4345 offset, length = _coerce_exprs(low, a, s.ctx)
4346 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
4347 if z3_debug():
4348 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
4349 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0,
4350 "First and second arguments must be non negative integers")
4351 _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression")
4352 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
4353
4354
4356 if z3_debug():
4357 _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression")
4358
4359
4360def ULE(a, b):
4361 """Create the Z3 expression (unsigned) `other <= self`.
4362
4363 Use the operator <= for signed less than or equal to.
4364
4365 >>> x, y = BitVecs('x y', 32)
4366 >>> ULE(x, y)
4367 ULE(x, y)
4368 >>> (x <= y).sexpr()
4369 '(bvsle x y)'
4370 >>> ULE(x, y).sexpr()
4371 '(bvule x y)'
4372 """
4373 _check_bv_args(a, b)
4374 a, b = _coerce_exprs(a, b)
4375 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4376
4377
4378def ULT(a, b):
4379 """Create the Z3 expression (unsigned) `other < self`.
4380
4381 Use the operator < for signed less than.
4382
4383 >>> x, y = BitVecs('x y', 32)
4384 >>> ULT(x, y)
4385 ULT(x, y)
4386 >>> (x < y).sexpr()
4387 '(bvslt x y)'
4388 >>> ULT(x, y).sexpr()
4389 '(bvult x y)'
4390 """
4391 _check_bv_args(a, b)
4392 a, b = _coerce_exprs(a, b)
4393 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4394
4395
4396def UGE(a, b):
4397 """Create the Z3 expression (unsigned) `other >= self`.
4398
4399 Use the operator >= for signed greater than or equal to.
4400
4401 >>> x, y = BitVecs('x y', 32)
4402 >>> UGE(x, y)
4403 UGE(x, y)
4404 >>> (x >= y).sexpr()
4405 '(bvsge x y)'
4406 >>> UGE(x, y).sexpr()
4407 '(bvuge x y)'
4408 """
4409 _check_bv_args(a, b)
4410 a, b = _coerce_exprs(a, b)
4411 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4412
4413
4414def UGT(a, b):
4415 """Create the Z3 expression (unsigned) `other > self`.
4416
4417 Use the operator > for signed greater than.
4418
4419 >>> x, y = BitVecs('x y', 32)
4420 >>> UGT(x, y)
4421 UGT(x, y)
4422 >>> (x > y).sexpr()
4423 '(bvsgt x y)'
4424 >>> UGT(x, y).sexpr()
4425 '(bvugt x y)'
4426 """
4427 _check_bv_args(a, b)
4428 a, b = _coerce_exprs(a, b)
4429 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4430
4431
4432def UDiv(a, b):
4433 """Create the Z3 expression (unsigned) division `self / other`.
4434
4435 Use the operator / for signed division.
4436
4437 >>> x = BitVec('x', 32)
4438 >>> y = BitVec('y', 32)
4439 >>> UDiv(x, y)
4440 UDiv(x, y)
4441 >>> UDiv(x, y).sort()
4442 BitVec(32)
4443 >>> (x / y).sexpr()
4444 '(bvsdiv x y)'
4445 >>> UDiv(x, y).sexpr()
4446 '(bvudiv x y)'
4447 """
4448 _check_bv_args(a, b)
4449 a, b = _coerce_exprs(a, b)
4450 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4451
4452
4453def URem(a, b):
4454 """Create the Z3 expression (unsigned) remainder `self % other`.
4455
4456 Use the operator % for signed modulus, and SRem() for signed remainder.
4457
4458 >>> x = BitVec('x', 32)
4459 >>> y = BitVec('y', 32)
4460 >>> URem(x, y)
4461 URem(x, y)
4462 >>> URem(x, y).sort()
4463 BitVec(32)
4464 >>> (x % y).sexpr()
4465 '(bvsmod x y)'
4466 >>> URem(x, y).sexpr()
4467 '(bvurem x y)'
4468 """
4469 _check_bv_args(a, b)
4470 a, b = _coerce_exprs(a, b)
4471 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4472
4473
4474def SRem(a, b):
4475 """Create the Z3 expression signed remainder.
4476
4477 Use the operator % for signed modulus, and URem() for unsigned remainder.
4478
4479 >>> x = BitVec('x', 32)
4480 >>> y = BitVec('y', 32)
4481 >>> SRem(x, y)
4482 SRem(x, y)
4483 >>> SRem(x, y).sort()
4484 BitVec(32)
4485 >>> (x % y).sexpr()
4486 '(bvsmod x y)'
4487 >>> SRem(x, y).sexpr()
4488 '(bvsrem x y)'
4489 """
4490 _check_bv_args(a, b)
4491 a, b = _coerce_exprs(a, b)
4492 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4493
4494
4495def LShR(a, b):
4496 """Create the Z3 expression logical right shift.
4497
4498 Use the operator >> for the arithmetical right shift.
4499
4500 >>> x, y = BitVecs('x y', 32)
4501 >>> LShR(x, y)
4502 LShR(x, y)
4503 >>> (x >> y).sexpr()
4504 '(bvashr x y)'
4505 >>> LShR(x, y).sexpr()
4506 '(bvlshr x y)'
4507 >>> BitVecVal(4, 3)
4508 4
4509 >>> BitVecVal(4, 3).as_signed_long()
4510 -4
4511 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4512 -2
4513 >>> simplify(BitVecVal(4, 3) >> 1)
4514 6
4515 >>> simplify(LShR(BitVecVal(4, 3), 1))
4516 2
4517 >>> simplify(BitVecVal(2, 3) >> 1)
4518 1
4519 >>> simplify(LShR(BitVecVal(2, 3), 1))
4520 1
4521 """
4522 _check_bv_args(a, b)
4523 a, b = _coerce_exprs(a, b)
4524 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4525
4526
4527def RotateLeft(a, b):
4528 """Return an expression representing `a` rotated to the left `b` times.
4529
4530 >>> a, b = BitVecs('a b', 16)
4531 >>> RotateLeft(a, b)
4532 RotateLeft(a, b)
4533 >>> simplify(RotateLeft(a, 0))
4534 a
4535 >>> simplify(RotateLeft(a, 16))
4536 a
4537 """
4538 _check_bv_args(a, b)
4539 a, b = _coerce_exprs(a, b)
4540 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4541
4542
4543def RotateRight(a, b):
4544 """Return an expression representing `a` rotated to the right `b` times.
4545
4546 >>> a, b = BitVecs('a b', 16)
4547 >>> RotateRight(a, b)
4548 RotateRight(a, b)
4549 >>> simplify(RotateRight(a, 0))
4550 a
4551 >>> simplify(RotateRight(a, 16))
4552 a
4553 """
4554 _check_bv_args(a, b)
4555 a, b = _coerce_exprs(a, b)
4556 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4557
4558
4559def SignExt(n, a):
4560 """Return a bit-vector expression with `n` extra sign-bits.
4561
4562 >>> x = BitVec('x', 16)
4563 >>> n = SignExt(8, x)
4564 >>> n.size()
4565 24
4566 >>> n
4567 SignExt(8, x)
4568 >>> n.sort()
4569 BitVec(24)
4570 >>> v0 = BitVecVal(2, 2)
4571 >>> v0
4572 2
4573 >>> v0.size()
4574 2
4575 >>> v = simplify(SignExt(6, v0))
4576 >>> v
4577 254
4578 >>> v.size()
4579 8
4580 >>> print("%.x" % v.as_long())
4581 fe
4582 """
4583 if z3_debug():
4584 _z3_assert(_is_int(n), "First argument must be an integer")
4585 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4586 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4587
4588
4589def ZeroExt(n, a):
4590 """Return a bit-vector expression with `n` extra zero-bits.
4591
4592 >>> x = BitVec('x', 16)
4593 >>> n = ZeroExt(8, x)
4594 >>> n.size()
4595 24
4596 >>> n
4597 ZeroExt(8, x)
4598 >>> n.sort()
4599 BitVec(24)
4600 >>> v0 = BitVecVal(2, 2)
4601 >>> v0
4602 2
4603 >>> v0.size()
4604 2
4605 >>> v = simplify(ZeroExt(6, v0))
4606 >>> v
4607 2
4608 >>> v.size()
4609 8
4610 """
4611 if z3_debug():
4612 _z3_assert(_is_int(n), "First argument must be an integer")
4613 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4614 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4615
4616
4618 """Return an expression representing `n` copies of `a`.
4619
4620 >>> x = BitVec('x', 8)
4621 >>> n = RepeatBitVec(4, x)
4622 >>> n
4623 RepeatBitVec(4, x)
4624 >>> n.size()
4625 32
4626 >>> v0 = BitVecVal(10, 4)
4627 >>> print("%.x" % v0.as_long())
4628 a
4629 >>> v = simplify(RepeatBitVec(4, v0))
4630 >>> v.size()
4631 16
4632 >>> print("%.x" % v.as_long())
4633 aaaa
4634 """
4635 if z3_debug():
4636 _z3_assert(_is_int(n), "First argument must be an integer")
4637 _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression")
4638 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4639
4640
4642 """Return the reduction-and expression of `a`."""
4643 if z3_debug():
4644 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4645 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4646
4647
4648def BVRedOr(a):
4649 """Return the reduction-or expression of `a`."""
4650 if z3_debug():
4651 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4652 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4653
4654
4655def BvNand(a, b):
4656 """Return the bitwise NAND of `a` and `b`.
4657
4658 >>> x = BitVec('x', 8)
4659 >>> y = BitVec('y', 8)
4660 >>> BvNand(x, y)
4661 bvnand(x, y)
4662 """
4663 _check_bv_args(a, b)
4664 a, b = _coerce_exprs(a, b)
4665 return BitVecRef(Z3_mk_bvnand(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4666
4667
4668def BvNor(a, b):
4669 """Return the bitwise NOR of `a` and `b`.
4670
4671 >>> x = BitVec('x', 8)
4672 >>> y = BitVec('y', 8)
4673 >>> BvNor(x, y)
4674 bvnor(x, y)
4675 """
4676 _check_bv_args(a, b)
4677 a, b = _coerce_exprs(a, b)
4678 return BitVecRef(Z3_mk_bvnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4679
4680
4681def BvXnor(a, b):
4682 """Return the bitwise XNOR of `a` and `b`.
4683
4684 >>> x = BitVec('x', 8)
4685 >>> y = BitVec('y', 8)
4686 >>> BvXnor(x, y)
4687 bvxnor(x, y)
4688 """
4689 _check_bv_args(a, b)
4690 a, b = _coerce_exprs(a, b)
4691 return BitVecRef(Z3_mk_bvxnor(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4692
4693
4694def BVAddNoOverflow(a, b, signed):
4695 """A predicate the determines that bit-vector addition does not overflow"""
4696 _check_bv_args(a, b)
4697 a, b = _coerce_exprs(a, b)
4698 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4699
4700
4702 """A predicate the determines that signed bit-vector addition does not underflow"""
4703 _check_bv_args(a, b)
4704 a, b = _coerce_exprs(a, b)
4705 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4706
4707
4709 """A predicate the determines that bit-vector subtraction does not overflow"""
4710 _check_bv_args(a, b)
4711 a, b = _coerce_exprs(a, b)
4712 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4713
4714
4715def BVSubNoUnderflow(a, b, signed):
4716 """A predicate the determines that bit-vector subtraction does not underflow"""
4717 _check_bv_args(a, b)
4718 a, b = _coerce_exprs(a, b)
4719 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4720
4721
4723 """A predicate the determines that bit-vector signed division does not overflow"""
4724 _check_bv_args(a, b)
4725 a, b = _coerce_exprs(a, b)
4726 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4727
4728
4730 """A predicate the determines that bit-vector unary negation does not overflow"""
4731 if z3_debug():
4732 _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression")
4733 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4734
4735
4736def BVMulNoOverflow(a, b, signed):
4737 """A predicate the determines that bit-vector multiplication does not overflow"""
4738 _check_bv_args(a, b)
4739 a, b = _coerce_exprs(a, b)
4740 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4741
4742
4744 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4745 _check_bv_args(a, b)
4746 a, b = _coerce_exprs(a, b)
4747 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4748
4749
4750
4755
4757 """Array sorts."""
4758
4759 def domain(self):
4760 """Return the domain of the array sort `self`.
4761
4762 >>> A = ArraySort(IntSort(), BoolSort())
4763 >>> A.domain()
4764 Int
4765 """
4767
4768 def domain_n(self, i):
4769 """Return the domain of the array sort `self`.
4770 """
4772
4773 def range(self):
4774 """Return the range of the array sort `self`.
4775
4776 >>> A = ArraySort(IntSort(), BoolSort())
4777 >>> A.range()
4778 Bool
4779 """
4781
4782
4784 """Array expressions. """
4785
4786 def sort(self):
4787 """Return the array sort of the array expression `self`.
4788
4789 >>> a = Array('a', IntSort(), BoolSort())
4790 >>> a.sort()
4791 Array(Int, Bool)
4792 """
4794
4795 def domain(self):
4796 """Shorthand for `self.sort().domain()`.
4797
4798 >>> a = Array('a', IntSort(), BoolSort())
4799 >>> a.domain()
4800 Int
4801 """
4802 return self.sortsort().domain()
4803
4804 def domain_n(self, i):
4805 """Shorthand for self.sort().domain_n(i)`."""
4806 return self.sortsort().domain_n(i)
4807
4808 def range(self):
4809 """Shorthand for `self.sort().range()`.
4810
4811 >>> a = Array('a', IntSort(), BoolSort())
4812 >>> a.range()
4813 Bool
4814 """
4815 return self.sortsort().range()
4816
4817 def __getitem__(self, arg):
4818 """Return the Z3 expression `self[arg]`.
4819
4820 >>> a = Array('a', IntSort(), BoolSort())
4821 >>> i = Int('i')
4822 >>> a[i]
4823 a[i]
4824 >>> a[i].sexpr()
4825 '(select a i)'
4826 """
4827 return _array_select(self, arg)
4828
4829 def default(self):
4830 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctxctxctx)
4831
4832
4833def _array_select(ar, arg):
4834 if isinstance(arg, tuple):
4835 args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))]
4836 _args, sz = _to_ast_array(args)
4837 return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx)
4838 arg = ar.sort().domain().cast(arg)
4839 return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.ctx)
4840
4841
4843 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4844
4845
4846def is_array(a : Any) -> bool:
4847 """Return `True` if `a` is a Z3 array expression.
4848
4849 >>> a = Array('a', IntSort(), IntSort())
4850 >>> is_array(a)
4851 True
4852 >>> is_array(Store(a, 0, 1))
4853 True
4854 >>> is_array(a[0])
4855 False
4856 """
4857 return isinstance(a, ArrayRef)
4858
4859
4861 """Return `True` if `a` is a Z3 constant array.
4862
4863 >>> a = K(IntSort(), 10)
4864 >>> is_const_array(a)
4865 True
4866 >>> a = Array('a', IntSort(), IntSort())
4867 >>> is_const_array(a)
4868 False
4869 """
4870 return is_app_of(a, Z3_OP_CONST_ARRAY)
4871
4872
4873def is_K(a):
4874 """Return `True` if `a` is a Z3 constant array.
4875
4876 >>> a = K(IntSort(), 10)
4877 >>> is_K(a)
4878 True
4879 >>> a = Array('a', IntSort(), IntSort())
4880 >>> is_K(a)
4881 False
4882 """
4883 return is_app_of(a, Z3_OP_CONST_ARRAY)
4884
4885
4886def is_map(a):
4887 """Return `True` if `a` is a Z3 map array expression.
4888
4889 >>> f = Function('f', IntSort(), IntSort())
4890 >>> b = Array('b', IntSort(), IntSort())
4891 >>> a = Map(f, b)
4892 >>> a
4893 Map(f, b)
4894 >>> is_map(a)
4895 True
4896 >>> is_map(b)
4897 False
4898 """
4899 return is_app_of(a, Z3_OP_ARRAY_MAP)
4900
4901
4903 """Return `True` if `a` is a Z3 default array expression.
4904 >>> d = Default(K(IntSort(), 10))
4905 >>> is_default(d)
4906 True
4907 """
4908 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4909
4910
4912 """Return the function declaration associated with a Z3 map array expression.
4913
4914 >>> f = Function('f', IntSort(), IntSort())
4915 >>> b = Array('b', IntSort(), IntSort())
4916 >>> a = Map(f, b)
4917 >>> eq(f, get_map_func(a))
4918 True
4919 >>> get_map_func(a)
4920 f
4921 >>> get_map_func(a)(0)
4922 f(0)
4923 """
4924 if z3_debug():
4925 _z3_assert(is_map(a), "Z3 array map expression expected.")
4926 return FuncDeclRef(
4928 a.ctx_ref(),
4929 Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0),
4930 ),
4931 ctx=a.ctx,
4932 )
4933
4934
4935def ArraySort(*sig):
4936 """Return the Z3 array sort with the given domain and range sorts.
4937
4938 >>> A = ArraySort(IntSort(), BoolSort())
4939 >>> A
4940 Array(Int, Bool)
4941 >>> A.domain()
4942 Int
4943 >>> A.range()
4944 Bool
4945 >>> AA = ArraySort(IntSort(), A)
4946 >>> AA
4947 Array(Int, Array(Int, Bool))
4948 >>> ArraySort(IntSort(), BoolSort(), RealSort())
4949 Array(Int, Bool, Real)
4950 """
4951 sig = _get_args(sig)
4952 if z3_debug():
4953 _z3_assert(len(sig) > 1, "At least two arguments expected")
4954 arity = len(sig) - 1
4955 r = sig[arity]
4956 d = sig[0]
4957 if z3_debug():
4958 for s in sig:
4959 _z3_assert(is_sort(s), "Z3 sort expected")
4960 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4961 ctx = d.ctx
4962 if len(sig) == 2:
4963 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4964 dom = (Sort * arity)()
4965 for i in range(arity):
4966 dom[i] = sig[i].ast
4967 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4968
4969
4970def Array(name, *sorts):
4971 """Return an array constant named `name` with the given domain and range sorts.
4972
4973 >>> a = Array('a', IntSort(), IntSort())
4974 >>> a.sort()
4975 Array(Int, Int)
4976 >>> a[0]
4977 a[0]
4978 """
4979 s = ArraySort(sorts)
4980 ctx = s.ctx
4981 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4982
4983
4984def Update(a, *args):
4985 """Return a Z3 store array expression.
4986
4987 >>> a = Array('a', IntSort(), IntSort())
4988 >>> i, v = Ints('i v')
4989 >>> s = Update(a, i, v)
4990 >>> s.sort()
4991 Array(Int, Int)
4992 >>> prove(s[i] == v)
4993 proved
4994 >>> j = Int('j')
4995 >>> prove(Implies(i != j, s[j] == a[j]))
4996 proved
4997 """
4998 if z3_debug():
4999 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5000 args = _get_args(args)
5001 ctx = a.ctx
5002 if len(args) <= 1:
5003 raise Z3Exception("array update requires index and value arguments")
5004 if len(args) == 2:
5005 i = args[0]
5006 v = args[1]
5007 i = a.sort().domain().cast(i)
5008 v = a.sort().range().cast(v)
5009 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
5010 v = a.sort().range().cast(args[-1])
5011 idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)]
5012 _args, sz = _to_ast_array(idxs)
5013 return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, v.as_ast()), ctx)
5014
5015
5016def Default(a):
5017 """ Return a default value for array expression.
5018 >>> b = K(IntSort(), 1)
5019 >>> prove(Default(b) == 1)
5020 proved
5021 """
5022 if z3_debug():
5023 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5024 return a.default()
5025
5026
5027def Store(a, *args):
5028 """Return a Z3 store array expression.
5029
5030 >>> a = Array('a', IntSort(), IntSort())
5031 >>> i, v = Ints('i v')
5032 >>> s = Store(a, i, v)
5033 >>> s.sort()
5034 Array(Int, Int)
5035 >>> prove(s[i] == v)
5036 proved
5037 >>> j = Int('j')
5038 >>> prove(Implies(i != j, s[j] == a[j]))
5039 proved
5040 """
5041 return Update(a, args)
5042
5043
5044def Select(a, *args):
5045 """Return a Z3 select array expression.
5046
5047 >>> a = Array('a', IntSort(), IntSort())
5048 >>> i = Int('i')
5049 >>> Select(a, i)
5050 a[i]
5051 >>> eq(Select(a, i), a[i])
5052 True
5053 """
5054 args = _get_args(args)
5055 if z3_debug():
5056 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
5057 return a[args]
5058
5059
5060def Map(f, *args):
5061 """Return a Z3 map array expression.
5062
5063 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5064 >>> a1 = Array('a1', IntSort(), IntSort())
5065 >>> a2 = Array('a2', IntSort(), IntSort())
5066 >>> b = Map(f, a1, a2)
5067 >>> b
5068 Map(f, a1, a2)
5069 >>> prove(b[0] == f(a1[0], a2[0]))
5070 proved
5071 """
5072 args = _get_args(args)
5073 if z3_debug():
5074 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
5075 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
5076 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
5077 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
5078 _args, sz = _to_ast_array(args)
5079 ctx = f.ctx
5080 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
5081
5082
5083def K(dom, v):
5084 """Return a Z3 constant array expression.
5085
5086 >>> a = K(IntSort(), 10)
5087 >>> a
5088 K(Int, 10)
5089 >>> a.sort()
5090 Array(Int, Int)
5091 >>> i = Int('i')
5092 >>> a[i]
5093 K(Int, 10)[i]
5094 >>> simplify(a[i])
5095 10
5096 """
5097 if z3_debug():
5098 _z3_assert(is_sort(dom), "Z3 sort expected")
5099 ctx = dom.ctx
5100 if not is_expr(v):
5101 v = _py2expr(v, ctx)
5102 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
5103
5104
5105def Ext(a, b):
5106 """Return extensionality index for one-dimensional arrays.
5107 >> a, b = Consts('a b', SetSort(IntSort()))
5108 >> Ext(a, b)
5109 Ext(a, b)
5110 """
5111 ctx = a.ctx
5112 if z3_debug():
5113 _z3_assert(is_array_sort(a) and (is_array(b) or b.is_lambda()), "arguments must be arrays")
5114 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5115
5116
5117def AsArray(f):
5118 """Return a Z3 as-array expression for the given function declaration.
5119
5120 >>> f = Function('f', IntSort(), IntSort())
5121 >>> a = AsArray(f)
5122 >>> a.sort()
5123 Array(Int, Int)
5124 >>> is_as_array(a)
5125 True
5126 >>> get_as_array_func(a) == f
5127 True
5128 """
5129 if z3_debug():
5130 _z3_assert(isinstance(f, FuncDeclRef), "function declaration expected")
5131 ctx = f.ctx
5132 return ArrayRef(Z3_mk_as_array(ctx.ref(), f.ast), ctx)
5133
5134
5136 """Return `True` if `a` is a Z3 array select application.
5137
5138 >>> a = Array('a', IntSort(), IntSort())
5139 >>> is_select(a)
5140 False
5141 >>> i = Int('i')
5142 >>> is_select(a[i])
5143 True
5144 """
5145 return is_app_of(a, Z3_OP_SELECT)
5146
5147
5149 """Return `True` if `a` is a Z3 array store application.
5150
5151 >>> a = Array('a', IntSort(), IntSort())
5152 >>> is_store(a)
5153 False
5154 >>> is_store(Store(a, 0, 1))
5155 True
5156 """
5157 return is_app_of(a, Z3_OP_STORE)
5158
5159
5164
5165
5166def SetSort(s):
5167 """ Create a set sort over element sort s"""
5168 return ArraySort(s, BoolSort())
5169
5170
5172 """Create the empty set
5173 >>> EmptySet(IntSort())
5174 K(Int, False)
5175 """
5176 ctx = s.ctx
5177 if is_finite_set_sort(s):
5178 return FiniteSetEmpty(s)
5179 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
5180
5181
5182def FullSet(s):
5183 """Create the full set
5184 >>> FullSet(IntSort())
5185 K(Int, True)
5186 """
5187 ctx = s.ctx
5188 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
5189
5190
5191def SetUnion(*args):
5192 """ Take the union of sets
5193 >>> a = Const('a', SetSort(IntSort()))
5194 >>> b = Const('b', SetSort(IntSort()))
5195 >>> SetUnion(a, b)
5196 union(a, b)
5197 """
5198 args = _get_args(args)
5199 if len(args) > 0 and is_finite_set(args[0]):
5200 from functools import reduce
5201 return reduce(FiniteSetUnion, args)
5202 ctx = _ctx_from_ast_arg_list(args)
5203 _args, sz = _to_ast_array(args)
5204 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
5205
5206
5207def SetIntersect(*args):
5208 """ Take the union of sets
5209 >>> a = Const('a', SetSort(IntSort()))
5210 >>> b = Const('b', SetSort(IntSort()))
5211 >>> SetIntersect(a, b)
5212 intersection(a, b)
5213 """
5214 args = _get_args(args)
5215 ctx = _ctx_from_ast_arg_list(args)
5216 if len(args) > 0 and is_finite_set(args[0]):
5217 from functools import reduce
5218 return reduce(FiniteSetIntersect, args)
5219 _args, sz = _to_ast_array(args)
5220 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
5221
5222
5223def SetAdd(s, e):
5224 """ Add element e to set s
5225 >>> a = Const('a', SetSort(IntSort()))
5226 >>> SetAdd(a, 1)
5227 Store(a, 1, True)
5228 """
5229 ctx = _ctx_from_ast_arg_list([s, e])
5230 e = _py2expr(e, ctx)
5231 if is_finite_set(s):
5232 return FiniteSetSingleton(e) | s
5233 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5234
5235
5236def SetDel(s, e):
5237 """ Remove element e to set s
5238 >>> a = Const('a', SetSort(IntSort()))
5239 >>> SetDel(a, 1)
5240 Store(a, 1, False)
5241 """
5242 ctx = _ctx_from_ast_arg_list([s, e])
5243 e = _py2expr(e, ctx)
5244 if is_finite_set(s):
5245 return s - FiniteSetSingleton(e)
5246 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
5247
5248
5250 """ The complement of set s
5251 >>> a = Const('a', SetSort(IntSort()))
5252 >>> SetComplement(a)
5253 complement(a)
5254 """
5255 ctx = s.ctx
5256 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
5257
5258
5260 """ The set difference of a and b
5261 >>> a = Const('a', SetSort(IntSort()))
5262 >>> b = Const('b', SetSort(IntSort()))
5263 >>> SetDifference(a, b)
5264 setminus(a, b)
5265 """
5266 ctx = _ctx_from_ast_arg_list([a, b])
5267 if is_finite_set(a):
5268 return FiniteSetDifference(a, b)
5269 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5270
5271
5272def IsMember(e, s):
5273 """ Check if e is a member of set s
5274 >>> a = Const('a', SetSort(IntSort()))
5275 >>> IsMember(1, a)
5276 a[1]
5277 """
5278 ctx = _ctx_from_ast_arg_list([s, e])
5279 e = _py2expr(e, ctx)
5280 if is_finite_set(s):
5281 return FiniteSetIsMember(e, s)
5282 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
5283
5284
5285def IsSubset(a, b):
5286 """ Check if a is a subset of b
5287 >>> a = Const('a', SetSort(IntSort()))
5288 >>> b = Const('b', SetSort(IntSort()))
5289 >>> IsSubset(a, b)
5290 subset(a, b)
5291 """
5292 ctx = _ctx_from_ast_arg_list([a, b])
5293 if is_finite_set(a):
5294 return FiniteSetIsSubset(a, b)
5295 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
5296
5297
5298
5303
5304
5306 """Finite set sort."""
5307
5308 def element_sort(self):
5309 """Return the element sort of this finite set sort."""
5311
5312 def cast(self, val):
5313 """Try to cast val as a finite set expression."""
5314 if is_expr(val):
5315 if self.eq(val.sort()):
5316 return val
5317 else:
5318 _z3_assert(False, "Cannot cast to finite set sort")
5319 if isinstance(val, set):
5320 elem_sort = self.element_sort()
5321 result = FiniteSetEmpty(self)
5322 for e in val:
5323 result = FiniteSetUnion(result, Singleton(_py2expr(e, self.ctxctxctx, elem_sort)))
5324 return result
5325 _z3_assert(False, "Cannot cast to finite set sort")
5326
5327 def subsort(self, other):
5328 return False
5329
5330 def is_int(self):
5331 return False
5332
5333 def is_bool(self):
5334 return False
5335
5336 def is_datatype(self):
5337 return False
5338
5339 def is_array(self):
5340 return False
5341
5342 def is_bv(self):
5343 return False
5344
5345
5347 """Return True if a is a Z3 finite set expression.
5348 >>> s = FiniteSetSort(IntSort())
5349 >>> is_finite_set(FiniteSetEmpty(s))
5350 True
5351 >>> is_finite_set(IntVal(1))
5352 False
5353 """
5354 return isinstance(a, FiniteSetRef)
5355
5356
5358 """Return True if s is a Z3 finite set sort.
5359 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5360 True
5361 >>> is_finite_set_sort(IntSort())
5362 False
5363 """
5364 return isinstance(s, FiniteSetSortRef)
5365
5366
5368 """Finite set expression."""
5369
5370 def sort(self):
5372
5373 def __or__(self, other):
5374 """Return the union of self and other."""
5375 return FiniteSetUnion(self, other)
5376
5377 def __and__(self, other):
5378 """Return the intersection of self and other."""
5379 return FiniteSetIntersect(self, other)
5380
5381 def __sub__(self, other):
5382 """Return the set difference of self and other."""
5383 return FiniteSetDifference(self, other)
5384
5385
5386def FiniteSetSort(elem_sort):
5387 """Create a finite set sort over element sort elem_sort.
5388 >>> s = FiniteSetSort(IntSort())
5389 >>> s
5390 FiniteSet(Int)
5391 """
5392 return FiniteSetSortRef(Z3_mk_finite_set_sort(elem_sort.ctx_ref(), elem_sort.ast), elem_sort.ctx)
5393
5394
5395def FiniteSetEmpty(set_sort):
5396 """Create an empty finite set of the given sort.
5397 >>> s = FiniteSetSort(IntSort())
5398 >>> FiniteSetEmpty(s)
5399 set.empty
5400 """
5401 ctx = set_sort.ctx
5402 return FiniteSetRef(Z3_mk_finite_set_empty(ctx.ref(), set_sort.ast), ctx)
5403
5404
5405def Singleton(elem):
5406 """Create a singleton finite set containing elem.
5407 >>> Singleton(IntVal(1))
5408 set.singleton(1)
5409 """
5410 ctx = elem.ctx
5411 return FiniteSetRef(Z3_mk_finite_set_singleton(ctx.ref(), elem.as_ast()), ctx)
5412
5413
5414def FiniteSetUnion(s1, s2):
5415 """Create the union of two finite sets.
5416 >>> a = Const('a', FiniteSetSort(IntSort()))
5417 >>> b = Const('b', FiniteSetSort(IntSort()))
5418 >>> FiniteSetUnion(a, b)
5419 set.union(a, b)
5420 """
5421 ctx = _ctx_from_ast_arg_list([s1, s2])
5422 return FiniteSetRef(Z3_mk_finite_set_union(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5423
5424
5426 """Create the intersection of two finite sets.
5427 >>> a = Const('a', FiniteSetSort(IntSort()))
5428 >>> b = Const('b', FiniteSetSort(IntSort()))
5429 >>> FiniteSetIntersect(a, b)
5430 set.intersect(a, b)
5431 """
5432 ctx = _ctx_from_ast_arg_list([s1, s2])
5433 return FiniteSetRef(Z3_mk_finite_set_intersect(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5434
5435
5437 """Create the set difference of two finite sets.
5438 >>> a = Const('a', FiniteSetSort(IntSort()))
5439 >>> b = Const('b', FiniteSetSort(IntSort()))
5440 >>> FiniteSetDifference(a, b)
5441 set.difference(a, b)
5442 """
5443 ctx = _ctx_from_ast_arg_list([s1, s2])
5444 return FiniteSetRef(Z3_mk_finite_set_difference(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5445
5446
5447def FiniteSetMember(elem, set):
5448 """Check if elem is a member of the finite set.
5449 >>> a = Const('a', FiniteSetSort(IntSort()))
5450 >>> FiniteSetMember(IntVal(1), a)
5451 set.in(1, a)
5452 """
5453 ctx = _ctx_from_ast_arg_list([elem, set])
5454 return BoolRef(Z3_mk_finite_set_member(ctx.ref(), elem.as_ast(), set.as_ast()), ctx)
5455
5456def In(elem, set):
5457 return FiniteSetMember(elem, set)
5458
5460 """Get the size (cardinality) of a finite set.
5461 >>> a = Const('a', FiniteSetSort(IntSort()))
5462 >>> FiniteSetSize(a)
5463 set.size(a)
5464 """
5465 ctx = set.ctx
5466 return ArithRef(Z3_mk_finite_set_size(ctx.ref(), set.as_ast()), ctx)
5467
5468
5470 """Check if s1 is a subset of s2.
5471 >>> a = Const('a', FiniteSetSort(IntSort()))
5472 >>> b = Const('b', FiniteSetSort(IntSort()))
5473 >>> FiniteSetSubset(a, b)
5474 set.subset(a, b)
5475 """
5476 ctx = _ctx_from_ast_arg_list([s1, s2])
5477 return BoolRef(Z3_mk_finite_set_subset(ctx.ref(), s1.as_ast(), s2.as_ast()), ctx)
5478
5479
5480def FiniteSetMap(f, set):
5481 """Apply function f to all elements of the finite set.
5482 >>> f = Array('f', IntSort(), IntSort())
5483 >>> a = Const('a', FiniteSetSort(IntSort()))
5484 >>> FiniteSetMap(f, a)
5485 set.map(f, a)
5486 """
5487 if isinstance(f, FuncDeclRef):
5488 f = AsArray(f)
5489 ctx = _ctx_from_ast_arg_list([f, set])
5490 return FiniteSetRef(Z3_mk_finite_set_map(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5491
5492
5494 """Filter a finite set using predicate f.
5495 >>> f = Array('f', IntSort(), BoolSort())
5496 >>> a = Const('a', FiniteSetSort(IntSort()))
5497 >>> FiniteSetFilter(f, a)
5498 set.filter(f, a)
5499 """
5500 if isinstance(f, FuncDeclRef):
5501 f = AsArray(f)
5502 ctx = _ctx_from_ast_arg_list([f, set])
5503 return FiniteSetRef(Z3_mk_finite_set_filter(ctx.ref(), f.as_ast(), set.as_ast()), ctx)
5504
5505
5506def FiniteSetRange(low, high):
5507 """Create a finite set of integers in the range [low, high).
5508 >>> FiniteSetRange(IntVal(0), IntVal(5))
5509 set.range(0, 5)
5510 """
5511 ctx = _ctx_from_ast_arg_list([low, high])
5512 return FiniteSetRef(Z3_mk_finite_set_range(ctx.ref(), low.as_ast(), high.as_ast()), ctx)
5513
5514
5515
5520
5522 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5523 if not isinstance(acc, tuple):
5524 return False
5525 if len(acc) != 2:
5526 return False
5527 return isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
5528
5529
5531 """Helper class for declaring Z3 datatypes.
5532
5533 >>> List = Datatype('List')
5534 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5535 >>> List.declare('nil')
5536 >>> List = List.create()
5537 >>> # List is now a Z3 declaration
5538 >>> List.nil
5539 nil
5540 >>> List.cons(10, List.nil)
5541 cons(10, nil)
5542 >>> List.cons(10, List.nil).sort()
5543 List
5544 >>> cons = List.cons
5545 >>> nil = List.nil
5546 >>> car = List.car
5547 >>> cdr = List.cdr
5548 >>> n = cons(1, cons(0, nil))
5549 >>> n
5550 cons(1, cons(0, nil))
5551 >>> simplify(cdr(n))
5552 cons(0, nil)
5553 >>> simplify(car(n))
5554 1
5555 """
5556
5557 def __init__(self, name, ctx=None):
5558 self.ctx = _get_ctx(ctx)
5559 self.name = name
5561
5562 def __deepcopy__(self, memo={}):
5563 r = Datatype(self.name, self.ctx)
5564 r.constructors = copy.deepcopy(self.constructors)
5565 return r
5566
5567 def declare_core(self, name, rec_name, *args):
5568 if z3_debug():
5569 _z3_assert(isinstance(name, str), "String expected")
5570 _z3_assert(isinstance(rec_name, str), "String expected")
5571 _z3_assert(
5572 all([_valid_accessor(a) for a in args]),
5573 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5574 )
5575 self.constructors.append((name, rec_name, args))
5576
5577 def declare(self, name, *args):
5578 """Declare constructor named `name` with the given accessors `args`.
5579 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5580 or a reference to the datatypes being declared.
5581
5582 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5583 declares the constructor named `cons` that builds a new List using an integer and a List.
5584 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5585 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5586 we use the method create() to create the actual datatype in Z3.
5587
5588 >>> List = Datatype('List')
5589 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5590 >>> List.declare('nil')
5591 >>> List = List.create()
5592 """
5593 if z3_debug():
5594 _z3_assert(isinstance(name, str), "String expected")
5595 _z3_assert(name != "", "Constructor name cannot be empty")
5596 return self.declare_core(name, "is-" + name, *args)
5597
5598 def __repr__(self):
5599 return "Datatype(%s, %s)" % (self.name, self.constructors)
5600
5601 def create(self):
5602 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5603
5604 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5605
5606 >>> List = Datatype('List')
5607 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5608 >>> List.declare('nil')
5609 >>> List = List.create()
5610 >>> List.nil
5611 nil
5612 >>> List.cons(10, List.nil)
5613 cons(10, nil)
5614 """
5615 return CreateDatatypes([self])[0]
5616
5617 def create_polymorphic(self, type_params):
5618 """Create a polymorphic Z3 datatype with explicit type variables.
5619
5620 `type_params` is a list of type variables created with `DeclareTypeVar`.
5621 Constructor field sorts may reference these type variables.
5622 Self-recursive fields may reference this datatype directly.
5623
5624 >>> A = DeclareTypeVar('A')
5625 >>> Pair = Datatype('Pair')
5626 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5627 >>> Pair = Pair.create_polymorphic([A])
5628 """
5629 return CreatePolymorphicDatatype(self, type_params)
5630
5631
5633 """Auxiliary object used to create Z3 datatypes."""
5634
5635 def __init__(self, c, ctx):
5636 self.c = c
5637 self.ctx = ctx
5638
5639 def __del__(self):
5640 if self.ctx.ref() is not None and Z3_del_constructor is not None:
5641 Z3_del_constructor(self.ctx.ref(), self.c)
5642
5643
5645 """Auxiliary object used to create Z3 datatypes."""
5646
5647 def __init__(self, c, ctx):
5648 self.c = c
5649 self.ctx = ctx
5650
5651 def __del__(self):
5652 if self.ctx.ref() is not None and Z3_del_constructor_list is not None:
5653 Z3_del_constructor_list(self.ctx.ref(), self.c)
5654
5655
5657 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5658
5659 In the following example we define a Tree-List using two mutually recursive datatypes.
5660
5661 >>> TreeList = Datatype('TreeList')
5662 >>> Tree = Datatype('Tree')
5663 >>> # Tree has two constructors: leaf and node
5664 >>> Tree.declare('leaf', ('val', IntSort()))
5665 >>> # a node contains a list of trees
5666 >>> Tree.declare('node', ('children', TreeList))
5667 >>> TreeList.declare('nil')
5668 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5669 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5670 >>> Tree.val(Tree.leaf(10))
5671 val(leaf(10))
5672 >>> simplify(Tree.val(Tree.leaf(10)))
5673 10
5674 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5675 >>> n1
5676 node(cons(leaf(10), cons(leaf(20), nil)))
5677 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5678 >>> simplify(n2 == n1)
5679 False
5680 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5681 True
5682 """
5683 ds = _get_args(ds)
5684 if z3_debug():
5685 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
5686 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
5687 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
5688 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
5689 ctx = ds[0].ctx
5690 num = len(ds)
5691 names = (Symbol * num)()
5692 out = (Sort * num)()
5693 clists = (ConstructorList * num)()
5694 to_delete = []
5695 for i in range(num):
5696 d = ds[i]
5697 names[i] = to_symbol(d.name, ctx)
5698 num_cs = len(d.constructors)
5699 cs = (Constructor * num_cs)()
5700 for j in range(num_cs):
5701 c = d.constructors[j]
5702 cname = to_symbol(c[0], ctx)
5703 rname = to_symbol(c[1], ctx)
5704 fs = c[2]
5705 num_fs = len(fs)
5706 fnames = (Symbol * num_fs)()
5707 sorts = (Sort * num_fs)()
5708 refs = (ctypes.c_uint * num_fs)()
5709 for k in range(num_fs):
5710 fname = fs[k][0]
5711 ftype = fs[k][1]
5712 fnames[k] = to_symbol(fname, ctx)
5713 if isinstance(ftype, Datatype):
5714 if z3_debug():
5715 _z3_assert(
5716 ds.count(ftype) == 1,
5717 "One and only one occurrence of each datatype is expected",
5718 )
5719 sorts[k] = None
5720 refs[k] = ds.index(ftype)
5721 else:
5722 if z3_debug():
5723 _z3_assert(is_sort(ftype), "Z3 sort expected")
5724 sorts[k] = ftype.ast
5725 refs[k] = 0
5726 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5727 to_delete.append(ScopedConstructor(cs[j], ctx))
5728 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
5729 to_delete.append(ScopedConstructorList(clists[i], ctx))
5730 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
5731 result = []
5732 # Create a field for every constructor, recognizer and accessor
5733 for i in range(num):
5734 dref = DatatypeSortRef(out[i], ctx)
5735 num_cs = dref.num_constructors()
5736 for j in range(num_cs):
5737 cref = dref.constructor(j)
5738 cref_name = cref.name()
5739 cref_arity = cref.arity()
5740 if cref.arity() == 0:
5741 cref = cref()
5742 setattr(dref, cref_name, cref)
5743 rref = dref.recognizer(j)
5744 setattr(dref, "is_" + cref_name, rref)
5745 for k in range(cref_arity):
5746 aref = dref.accessor(j, k)
5747 setattr(dref, aref.name(), aref)
5748 result.append(dref)
5749 return tuple(result)
5750
5751
5752def CreatePolymorphicDatatype(d, type_params):
5753 """Create a single polymorphic Z3 datatype with explicit type parameters.
5754
5755 `d` is a `Datatype` helper object whose constructors have been declared.
5756 `type_params` is a list of type variables created with `DeclareTypeVar`.
5757 Constructor field sorts may reference these type variables, and self-recursive
5758 fields may reference `d` directly.
5759
5760 >>> A = DeclareTypeVar('A')
5761 >>> Pair = Datatype('Pair')
5762 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5763 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5764 """
5765 if z3_debug():
5766 _z3_assert(isinstance(d, Datatype), "Datatype expected")
5767 _z3_assert(d.constructors != [], "Non-empty Datatype expected")
5768 ctx = d.ctx
5769 name = to_symbol(d.name, ctx)
5770 num_params = len(type_params)
5771 params_arr = (Sort * num_params)()
5772 for i, p in enumerate(type_params):
5773 if z3_debug():
5774 _z3_assert(is_sort(p), "Z3 sort expected for type parameter")
5775 params_arr[i] = p.ast
5776 num_cs = len(d.constructors)
5777 cs = (Constructor * num_cs)()
5778 to_delete = []
5779 for j in range(num_cs):
5780 c = d.constructors[j]
5781 cname = to_symbol(c[0], ctx)
5782 rname = to_symbol(c[1], ctx)
5783 fs = c[2]
5784 num_fs = len(fs)
5785 fnames = (Symbol * num_fs)()
5786 sorts = (Sort * num_fs)()
5787 refs = (ctypes.c_uint * num_fs)()
5788 for k in range(num_fs):
5789 fname = fs[k][0]
5790 ftype = fs[k][1]
5791 fnames[k] = to_symbol(fname, ctx)
5792 if isinstance(ftype, Datatype):
5793 if z3_debug():
5794 _z3_assert(ftype is d, "Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5795 sorts[k] = None
5796 refs[k] = 0
5797 else:
5798 if z3_debug():
5799 _z3_assert(is_sort(ftype), "Z3 sort expected")
5800 sorts[k] = ftype.ast
5801 refs[k] = 0
5802 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
5803 to_delete.append(ScopedConstructor(cs[j], ctx))
5804 out = Z3_mk_polymorphic_datatype(ctx.ref(), name, num_params, params_arr, num_cs, cs)
5805 dref = DatatypeSortRef(out, ctx)
5806 num_cs_actual = dref.num_constructors()
5807 for j in range(num_cs_actual):
5808 cref = dref.constructor(j)
5809 cref_name = cref.name()
5810 cref_arity = cref.arity()
5811 if cref_arity == 0:
5812 cref = cref()
5813 setattr(dref, cref_name, cref)
5814 rref = dref.recognizer(j)
5815 setattr(dref, "is_" + cref_name, rref)
5816 for k in range(cref_arity):
5817 aref = dref.accessor(j, k)
5818 setattr(dref, aref.name(), aref)
5819 return dref
5820
5821
5823 """Datatype sorts."""
5824
5826 """Return the number of constructors in the given Z3 datatype.
5827
5828 >>> List = Datatype('List')
5829 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5830 >>> List.declare('nil')
5831 >>> List = List.create()
5832 >>> # List is now a Z3 declaration
5833 >>> List.num_constructors()
5834 2
5835 """
5837
5838 def constructor(self, idx):
5839 """Return a constructor of the datatype `self`.
5840
5841 >>> List = Datatype('List')
5842 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5843 >>> List.declare('nil')
5844 >>> List = List.create()
5845 >>> # List is now a Z3 declaration
5846 >>> List.num_constructors()
5847 2
5848 >>> List.constructor(0)
5849 cons
5850 >>> List.constructor(1)
5851 nil
5852 """
5853 if z3_debug():
5854 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
5856
5857 def recognizer(self, idx):
5858 """In Z3, each constructor has an associated recognizer predicate.
5859
5860 If the constructor is named `name`, then the recognizer `is_name`.
5861
5862 >>> List = Datatype('List')
5863 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5864 >>> List.declare('nil')
5865 >>> List = List.create()
5866 >>> # List is now a Z3 declaration
5867 >>> List.num_constructors()
5868 2
5869 >>> List.recognizer(0)
5870 is(cons)
5871 >>> List.recognizer(1)
5872 is(nil)
5873 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5874 False
5875 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5876 True
5877 >>> l = Const('l', List)
5878 >>> simplify(List.is_cons(l))
5879 is(cons, l)
5880 """
5881 if z3_debug():
5882 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
5884
5885 def accessor(self, i, j):
5886 """In Z3, each constructor has 0 or more accessor.
5887 The number of accessors is equal to the arity of the constructor.
5888
5889 >>> List = Datatype('List')
5890 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5891 >>> List.declare('nil')
5892 >>> List = List.create()
5893 >>> List.num_constructors()
5894 2
5895 >>> List.constructor(0)
5896 cons
5897 >>> num_accs = List.constructor(0).arity()
5898 >>> num_accs
5899 2
5900 >>> List.accessor(0, 0)
5901 car
5902 >>> List.accessor(0, 1)
5903 cdr
5904 >>> List.constructor(1)
5905 nil
5906 >>> num_accs = List.constructor(1).arity()
5907 >>> num_accs
5908 0
5909 """
5910 if z3_debug():
5911 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
5912 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
5913 return FuncDeclRef(
5915 ctx=self.ctxctxctx,
5916 )
5917
5918
5920 """Datatype expressions."""
5921
5922 def sort(self):
5923 """Return the datatype sort of the datatype expression `self`."""
5925
5926 def update_field(self, field_accessor, new_value):
5927 """Return a new datatype expression with the specified field updated.
5928
5929 Args:
5930 field_accessor: The accessor function declaration for the field to update
5931 new_value: The new value for the field
5932
5933 Returns:
5934 A new datatype expression with the field updated, other fields unchanged
5935
5936 Example:
5937 >>> Person = Datatype('Person')
5938 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
5939 >>> Person = Person.create()
5940 >>> person_age = Person.accessor(0, 1) # age accessor
5941 >>> p = Const('p', Person)
5942 >>> p2 = p.update_field(person_age, IntVal(30))
5943 """
5944 if z3_debug():
5945 _z3_assert(is_func_decl(field_accessor), "Z3 function declaration expected")
5946 _z3_assert(is_expr(new_value), "Z3 expression expected")
5947 return _to_expr_ref(
5948 Z3_datatype_update_field(self.ctx_ref(), field_accessor.ast, self.as_astas_ast(), new_value.as_ast()),
5949 self.ctxctxctx
5950 )
5951
5952def DatatypeSort(name, params=None, ctx=None):
5953 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
5954
5955 Args:
5956 name: name of the datatype sort
5957 params: optional list/tuple of sort parameters for parametric datatypes
5958 ctx: Z3 context (optional)
5959
5960 Example:
5961 >>> # Non-parametric datatype
5962 >>> TreeRef = DatatypeSort('Tree')
5963 >>> # Parametric datatype with one parameter
5964 >>> ListIntRef = DatatypeSort('List', [IntSort()])
5965 >>> # Parametric datatype with multiple parameters
5966 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
5967 """
5968 ctx = _get_ctx(ctx)
5969 if params is None or len(params) == 0:
5970 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), 0, (Sort * 0)()), ctx)
5971 else:
5972 _params = (Sort * len(params))()
5973 for i in range(len(params)):
5974 _params[i] = params[i].ast
5975 return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx), len(params), _params), ctx)
5976
5977def TupleSort(name, sorts, ctx=None):
5978 """Create a named tuple sort base on a set of underlying sorts
5979 Example:
5980 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5981 """
5982 tuple = Datatype(name, ctx)
5983 projects = [("project%d" % i, sorts[i]) for i in range(len(sorts))]
5984 tuple.declare(name, *projects)
5985 tuple = tuple.create()
5986 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
5987
5988
5989def DisjointSum(name, sorts, ctx=None):
5990 """Create a named tagged union sort base on a set of underlying sorts
5991 Example:
5992 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5993 """
5994 sum = Datatype(name, ctx)
5995 for i in range(len(sorts)):
5996 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
5997 sum = sum.create()
5998 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
5999
6000
6001def EnumSort(name, values, ctx=None):
6002 """Return a new enumeration sort named `name` containing the given values.
6003
6004 The result is a pair (sort, list of constants).
6005 Example:
6006 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6007 """
6008 if z3_debug():
6009 _z3_assert(isinstance(name, str), "Name must be a string")
6010 _z3_assert(all([isinstance(v, str) for v in values]), "Enumeration sort values must be strings")
6011 _z3_assert(len(values) > 0, "At least one value expected")
6012 ctx = _get_ctx(ctx)
6013 num = len(values)
6014 _val_names = (Symbol * num)()
6015 for i in range(num):
6016 _val_names[i] = to_symbol(values[i], ctx)
6017 _values = (FuncDecl * num)()
6018 _testers = (FuncDecl * num)()
6019 name = to_symbol(name, ctx)
6020 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
6021 V = []
6022 for i in range(num):
6023 V.append(FuncDeclRef(_values[i], ctx))
6024 V = [a() for a in V]
6025 return S, V
6026
6027
6032
6033
6035 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6036
6037 Consider using the function `args2params` to create instances of this object.
6038 """
6039
6040 def __init__(self, ctx=None, params=None):
6041 self.ctx = _get_ctx(ctx)
6042 if params is None:
6043 self.params = Z3_mk_params(self.ctx.ref())
6044 else:
6045 self.params = params
6046 Z3_params_inc_ref(self.ctx.ref(), self.params)
6047
6048 def __deepcopy__(self, memo={}):
6049 return ParamsRef(self.ctx, self.params)
6050
6051 def __del__(self):
6052 if self.ctx.ref() is not None and Z3_params_dec_ref is not None:
6053 Z3_params_dec_ref(self.ctx.ref(), self.params)
6054
6055 def set(self, name, val):
6056 """Set parameter name with value val."""
6057 if z3_debug():
6058 _z3_assert(isinstance(name, str), "parameter name must be a string")
6059 name_sym = to_symbol(name, self.ctx)
6060 if isinstance(val, bool):
6061 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
6062 elif _is_int(val):
6063 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
6064 elif isinstance(val, float):
6065 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
6066 elif isinstance(val, str):
6067 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
6068 else:
6069 if z3_debug():
6070 _z3_assert(False, "invalid parameter value")
6071
6072 def __repr__(self):
6073 return Z3_params_to_string(self.ctx.ref(), self.params)
6074
6075 def validate(self, ds):
6076 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
6077 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
6078
6079
6080def args2params(arguments, keywords, ctx=None):
6081 """Convert python arguments into a Z3_params object.
6082 A ':' is added to the keywords, and '_' is replaced with '-'
6083
6084 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6085 (params model true relevancy 2 elim_and true)
6086 """
6087 if z3_debug():
6088 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
6089 prev = None
6090 r = ParamsRef(ctx)
6091 for a in arguments:
6092 if prev is None:
6093 prev = a
6094 else:
6095 r.set(prev, a)
6096 prev = None
6097 for k in keywords:
6098 v = keywords[k]
6099 r.set(k, v)
6100 return r
6101
6102
6104 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6105 """
6106
6107 def __init__(self, descr, ctx=None):
6108 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
6109 self.ctx = _get_ctx(ctx)
6110 self.descr = descr
6111 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
6112
6113 def __deepcopy__(self, memo={}):
6114 return ParamsDescrsRef(self.descr, self.ctx)
6115
6116 def __del__(self):
6117 if self.ctx.ref() is not None and Z3_param_descrs_dec_ref is not None:
6118 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
6119
6120 def size(self):
6121 """Return the size of in the parameter description `self`.
6122 """
6123 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
6124
6125 def __len__(self):
6126 """Return the size of in the parameter description `self`.
6127 """
6128 return self.size()
6129
6130 def get_name(self, i):
6131 """Return the i-th parameter name in the parameter description `self`.
6132 """
6133 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
6134
6135 def get_kind(self, n):
6136 """Return the kind of the parameter named `n`.
6137 """
6138 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6139
6140 def get_documentation(self, n):
6141 """Return the documentation string of the parameter named `n`.
6142 """
6143 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
6144
6145 def __getitem__(self, arg):
6146 if _is_int(arg):
6147 return self.get_name(arg)
6148 else:
6149 return self.get_kind(arg)
6150
6151 def __repr__(self):
6152 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
6153
6154
6159
6160
6162 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6163
6164 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6165 A goal has a solution if one of its subgoals has a solution.
6166 A goal is unsatisfiable if all subgoals are unsatisfiable.
6167 """
6168
6169 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6170 if z3_debug():
6171 _z3_assert(goal is None or ctx is not None,
6172 "If goal is different from None, then ctx must be also different from None")
6173 self.ctx = _get_ctx(ctx)
6174 self.goal = goal
6175 if self.goal is None:
6176 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
6177 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
6178
6179 def __del__(self):
6180 if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_ref is not None:
6181 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
6182
6183 def depth(self):
6184 """Return the depth of the goal `self`.
6185 The depth corresponds to the number of tactics applied to `self`.
6186
6187 >>> x, y = Ints('x y')
6188 >>> g = Goal()
6189 >>> g.add(x == 0, y >= x + 1)
6190 >>> g.depth()
6191 0
6192 >>> r = Then('simplify', 'solve-eqs')(g)
6193 >>> # r has 1 subgoal
6194 >>> len(r)
6195 1
6196 >>> r[0].depth()
6197 2
6198 """
6199 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
6200
6201 def inconsistent(self):
6202 """Return `True` if `self` contains the `False` constraints.
6203
6204 >>> x, y = Ints('x y')
6205 >>> g = Goal()
6206 >>> g.inconsistent()
6207 False
6208 >>> g.add(x == 0, x == 1)
6209 >>> g
6210 [x == 0, x == 1]
6211 >>> g.inconsistent()
6212 False
6213 >>> g2 = Tactic('propagate-values')(g)[0]
6214 >>> g2.inconsistent()
6215 True
6216 """
6217 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
6218
6219 def prec(self):
6220 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6221
6222 >>> g = Goal()
6223 >>> g.prec() == Z3_GOAL_PRECISE
6224 True
6225 >>> x, y = Ints('x y')
6226 >>> g.add(x == y + 1)
6227 >>> g.prec() == Z3_GOAL_PRECISE
6228 True
6229 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6230 >>> g2 = t(g)[0]
6231 >>> g2
6232 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6233 >>> g2.prec() == Z3_GOAL_PRECISE
6234 False
6235 >>> g2.prec() == Z3_GOAL_UNDER
6236 True
6237 """
6238 return Z3_goal_precision(self.ctx.ref(), self.goal)
6239
6240 def precision(self):
6241 """Alias for `prec()`.
6242
6243 >>> g = Goal()
6244 >>> g.precision() == Z3_GOAL_PRECISE
6245 True
6246 """
6247 return self.prec()
6248
6249 def size(self):
6250 """Return the number of constraints in the goal `self`.
6251
6252 >>> g = Goal()
6253 >>> g.size()
6254 0
6255 >>> x, y = Ints('x y')
6256 >>> g.add(x == 0, y > x)
6257 >>> g.size()
6258 2
6259 """
6260 return int(Z3_goal_size(self.ctx.ref(), self.goal))
6261
6262 def __len__(self):
6263 """Return the number of constraints in the goal `self`.
6264
6265 >>> g = Goal()
6266 >>> len(g)
6267 0
6268 >>> x, y = Ints('x y')
6269 >>> g.add(x == 0, y > x)
6270 >>> len(g)
6271 2
6272 """
6273 return self.size()
6274
6275 def get(self, i):
6276 """Return a constraint in the goal `self`.
6277
6278 >>> g = Goal()
6279 >>> x, y = Ints('x y')
6280 >>> g.add(x == 0, y > x)
6281 >>> g.get(0)
6282 x == 0
6283 >>> g.get(1)
6284 y > x
6285 """
6286 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
6287
6288 def __getitem__(self, arg):
6289 """Return a constraint in the goal `self`.
6290
6291 >>> g = Goal()
6292 >>> x, y = Ints('x y')
6293 >>> g.add(x == 0, y > x)
6294 >>> g[0]
6295 x == 0
6296 >>> g[1]
6297 y > x
6298 """
6299 if arg < 0:
6300 arg += len(self)
6301 if arg < 0 or arg >= len(self):
6302 raise IndexError
6303 return self.get(arg)
6304
6305 def assert_exprs(self, *args):
6306 """Assert constraints into the goal.
6307
6308 >>> x = Int('x')
6309 >>> g = Goal()
6310 >>> g.assert_exprs(x > 0, x < 2)
6311 >>> g
6312 [x > 0, x < 2]
6313 """
6314 args = _get_args(args)
6315 s = BoolSort(self.ctx)
6316 for arg in args:
6317 arg = s.cast(arg)
6318 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
6319
6320 def append(self, *args):
6321 """Add constraints.
6322
6323 >>> x = Int('x')
6324 >>> g = Goal()
6325 >>> g.append(x > 0, x < 2)
6326 >>> g
6327 [x > 0, x < 2]
6328 """
6329 self.assert_exprs(*args)
6330
6331 def insert(self, *args):
6332 """Add constraints.
6333
6334 >>> x = Int('x')
6335 >>> g = Goal()
6336 >>> g.insert(x > 0, x < 2)
6337 >>> g
6338 [x > 0, x < 2]
6339 """
6340 self.assert_exprs(*args)
6341
6342 def add(self, *args):
6343 """Add constraints.
6344
6345 >>> x = Int('x')
6346 >>> g = Goal()
6347 >>> g.add(x > 0, x < 2)
6348 >>> g
6349 [x > 0, x < 2]
6350 """
6351 self.assert_exprs(*args)
6352
6353 def convert_model(self, model):
6354 """Retrieve model from a satisfiable goal
6355 >>> a, b = Ints('a b')
6356 >>> g = Goal()
6357 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6358 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6359 >>> r = t(g)
6360 >>> r[0]
6361 [Or(b == 0, b == 1), Not(0 <= b)]
6362 >>> r[1]
6363 [Or(b == 0, b == 1), Not(1 <= b)]
6364 >>> # Remark: the subgoal r[0] is unsatisfiable
6365 >>> # Creating a solver for solving the second subgoal
6366 >>> s = Solver()
6367 >>> s.add(r[1])
6368 >>> s.check()
6369 sat
6370 >>> s.model()
6371 [b = 0]
6372 >>> # Model s.model() does not assign a value to `a`
6373 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6374 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6375 >>> r[1].convert_model(s.model())
6376 [b = 0, a = 1]
6377 """
6378 if z3_debug():
6379 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
6380 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
6381
6382 def __repr__(self):
6383 return obj_to_string(self)
6384
6385 def sexpr(self):
6386 """Return a textual representation of the s-expression representing the goal."""
6387 return Z3_goal_to_string(self.ctx.ref(), self.goal)
6388
6389 def dimacs(self, include_names=True):
6390 """Return a textual representation of the goal in DIMACS format."""
6391 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names)
6392
6393 def translate(self, target):
6394 """Copy goal `self` to context `target`.
6395
6396 >>> x = Int('x')
6397 >>> g = Goal()
6398 >>> g.add(x > 10)
6399 >>> g
6400 [x > 10]
6401 >>> c2 = Context()
6402 >>> g2 = g.translate(c2)
6403 >>> g2
6404 [x > 10]
6405 >>> g.ctx == main_ctx()
6406 True
6407 >>> g2.ctx == c2
6408 True
6409 >>> g2.ctx == main_ctx()
6410 False
6411 """
6412 if z3_debug():
6413 _z3_assert(isinstance(target, Context), "target must be a context")
6414 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
6415
6416 def __copy__(self):
6417 return self.translate(self.ctx)
6418
6419 def __deepcopy__(self, memo={}):
6420 return self.translate(self.ctx)
6421
6422 def simplify(self, *arguments, **keywords):
6423 """Return a new simplified goal.
6424
6425 This method is essentially invoking the simplify tactic.
6426
6427 >>> g = Goal()
6428 >>> x = Int('x')
6429 >>> g.add(x + 1 >= 2)
6430 >>> g
6431 [x + 1 >= 2]
6432 >>> g2 = g.simplify()
6433 >>> g2
6434 [x >= 1]
6435 >>> # g was not modified
6436 >>> g
6437 [x + 1 >= 2]
6438 """
6439 t = Tactic("simplify")
6440 return t.apply(self, *arguments, **keywords)[0]
6441
6442 def as_expr(self):
6443 """Return goal `self` as a single Z3 expression.
6444
6445 >>> x = Int('x')
6446 >>> g = Goal()
6447 >>> g.as_expr()
6448 True
6449 >>> g.add(x > 1)
6450 >>> g.as_expr()
6451 x > 1
6452 >>> g.add(x < 10)
6453 >>> g.as_expr()
6454 And(x > 1, x < 10)
6455 """
6456 sz = len(self)
6457 if sz == 0:
6458 return BoolVal(True, self.ctx)
6459 elif sz == 1:
6460 return self.get(0)
6461 else:
6462 return And([self.get(i) for i in range(len(self))], self.ctx)
6463
6464
6469
6470
6472 """A collection (vector) of ASTs."""
6473
6474 def __init__(self, v=None, ctx=None):
6475 self.vector = None
6476 if v is None:
6477 self.ctx = _get_ctx(ctx)
6478 self.vector = Z3_mk_ast_vector(self.ctx.ref())
6479 else:
6480 self.vector = v
6481 assert ctx is not None
6482 self.ctx = ctx
6483 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
6484
6485 def __del__(self):
6486 if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_ref is not None:
6487 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
6488
6489 def __len__(self):
6490 """Return the size of the vector `self`.
6491
6492 >>> A = AstVector()
6493 >>> len(A)
6494 0
6495 >>> A.push(Int('x'))
6496 >>> A.push(Int('x'))
6497 >>> len(A)
6498 2
6499 """
6500 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
6501
6502 def __getitem__(self, i):
6503 """Return the AST at position `i`.
6504
6505 >>> A = AstVector()
6506 >>> A.push(Int('x') + 1)
6507 >>> A.push(Int('y'))
6508 >>> A[0]
6509 x + 1
6510 >>> A[1]
6511 y
6512 """
6513
6514 if isinstance(i, int):
6515 if i < 0:
6516 i += self.__len__()
6517
6518 if i >= self.__len__():
6519 raise IndexError
6520 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
6521
6522 elif isinstance(i, slice):
6523 result = []
6524 for ii in range(*i.indices(self.__len__())):
6525 result.append(_to_ast_ref(
6526 Z3_ast_vector_get(self.ctx.ref(), self.vector, ii),
6527 self.ctx,
6528 ))
6529 return result
6530
6531 def __setitem__(self, i, v):
6532 """Update AST at position `i`.
6533
6534 >>> A = AstVector()
6535 >>> A.push(Int('x') + 1)
6536 >>> A.push(Int('y'))
6537 >>> A[0]
6538 x + 1
6539 >>> A[0] = Int('x')
6540 >>> A[0]
6541 x
6542 """
6543 if i < 0:
6544 i += self.__len__()
6545 if i < 0 or i >= self.__len__():
6546 raise IndexError
6547 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
6548
6549 def push(self, v):
6550 """Add `v` in the end of the vector.
6551
6552 >>> A = AstVector()
6553 >>> len(A)
6554 0
6555 >>> A.push(Int('x'))
6556 >>> len(A)
6557 1
6558 """
6559 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
6560
6561 def resize(self, sz):
6562 """Resize the vector to `sz` elements.
6563
6564 >>> A = AstVector()
6565 >>> A.resize(10)
6566 >>> len(A)
6567 10
6568 >>> for i in range(10): A[i] = Int('x')
6569 >>> A[5]
6570 x
6571 """
6572 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
6573
6574 def __contains__(self, item):
6575 """Return `True` if the vector contains `item`.
6576
6577 >>> x = Int('x')
6578 >>> A = AstVector()
6579 >>> x in A
6580 False
6581 >>> A.push(x)
6582 >>> x in A
6583 True
6584 >>> (x+1) in A
6585 False
6586 >>> A.push(x+1)
6587 >>> (x+1) in A
6588 True
6589 >>> A
6590 [x, x + 1]
6591 """
6592 for elem in self:
6593 if elem.eq(item):
6594 return True
6595 return False
6596
6597 def translate(self, other_ctx):
6598 """Copy vector `self` to context `other_ctx`.
6599
6600 >>> x = Int('x')
6601 >>> A = AstVector()
6602 >>> A.push(x)
6603 >>> c2 = Context()
6604 >>> B = A.translate(c2)
6605 >>> B
6606 [x]
6607 """
6608 return AstVector(
6609 Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()),
6610 ctx=other_ctx,
6611 )
6612
6613 def __copy__(self):
6614 return self.translate(self.ctx)
6615
6616 def __deepcopy__(self, memo={}):
6617 return self.translate(self.ctx)
6618
6619 def __repr__(self):
6620 return obj_to_string(self)
6621
6622 def sexpr(self):
6623 """Return a textual representation of the s-expression representing the vector."""
6624 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
6625
6626
6631
6632
6634 """A mapping from ASTs to ASTs."""
6635
6636 def __init__(self, m=None, ctx=None):
6637 self.map = None
6638 if m is None:
6639 self.ctx = _get_ctx(ctx)
6640 self.map = Z3_mk_ast_map(self.ctx.ref())
6641 else:
6642 self.map = m
6643 assert ctx is not None
6644 self.ctx = ctx
6645 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
6646
6647 def __deepcopy__(self, memo={}):
6648 return AstMap(self.map, self.ctx)
6649
6650 def __del__(self):
6651 if self.map is not None and self.ctx.ref() is not None and Z3_ast_map_dec_ref is not None:
6652 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
6653
6654 def __len__(self):
6655 """Return the size of the map.
6656
6657 >>> M = AstMap()
6658 >>> len(M)
6659 0
6660 >>> x = Int('x')
6661 >>> M[x] = IntVal(1)
6662 >>> len(M)
6663 1
6664 """
6665 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
6666
6667 def __contains__(self, key):
6668 """Return `True` if the map contains key `key`.
6669
6670 >>> M = AstMap()
6671 >>> x = Int('x')
6672 >>> M[x] = x + 1
6673 >>> x in M
6674 True
6675 >>> x+1 in M
6676 False
6677 """
6678 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
6679
6680 def __getitem__(self, key):
6681 """Retrieve the value associated with key `key`.
6682
6683 >>> M = AstMap()
6684 >>> x = Int('x')
6685 >>> M[x] = x + 1
6686 >>> M[x]
6687 x + 1
6688 """
6689 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
6690
6691 def __setitem__(self, k, v):
6692 """Add/Update key `k` with value `v`.
6693
6694 >>> M = AstMap()
6695 >>> x = Int('x')
6696 >>> M[x] = x + 1
6697 >>> len(M)
6698 1
6699 >>> M[x]
6700 x + 1
6701 >>> M[x] = IntVal(1)
6702 >>> M[x]
6703 1
6704 """
6705 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
6706
6707 def __repr__(self):
6708 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
6709
6710 def erase(self, k):
6711 """Remove the entry associated with key `k`.
6712
6713 >>> M = AstMap()
6714 >>> x = Int('x')
6715 >>> M[x] = x + 1
6716 >>> len(M)
6717 1
6718 >>> M.erase(x)
6719 >>> len(M)
6720 0
6721 """
6722 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
6723
6724 def reset(self):
6725 """Remove all entries from the map.
6726
6727 >>> M = AstMap()
6728 >>> x = Int('x')
6729 >>> M[x] = x + 1
6730 >>> M[x+x] = IntVal(1)
6731 >>> len(M)
6732 2
6733 >>> M.reset()
6734 >>> len(M)
6735 0
6736 """
6737 Z3_ast_map_reset(self.ctx.ref(), self.map)
6738
6739 def keys(self):
6740 """Return an AstVector containing all keys in the map.
6741
6742 >>> M = AstMap()
6743 >>> x = Int('x')
6744 >>> M[x] = x + 1
6745 >>> M[x+x] = IntVal(1)
6746 >>> M.keys()
6747 [x + x, x]
6748 """
6749 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
6750
6751
6756
6757
6759 """Store the value of the interpretation of a function in a particular point."""
6760
6761 def __init__(self, entry, ctx):
6762 self.entry = entry
6763 self.ctx = ctx
6764 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
6765
6766 def __deepcopy__(self, memo={}):
6767 return FuncEntry(self.entry, self.ctx)
6768
6769 def __del__(self):
6770 if self.ctx.ref() is not None and Z3_func_entry_dec_ref is not None:
6771 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
6772
6773 def num_args(self):
6774 """Return the number of arguments in the given entry.
6775
6776 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6777 >>> s = Solver()
6778 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6779 >>> s.check()
6780 sat
6781 >>> m = s.model()
6782 >>> f_i = m[f]
6783 >>> f_i.num_entries()
6784 1
6785 >>> e = f_i.entry(0)
6786 >>> e.num_args()
6787 2
6788 """
6789 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
6790
6791 def arg_value(self, idx):
6792 """Return the value of argument `idx`.
6793
6794 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6795 >>> s = Solver()
6796 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6797 >>> s.check()
6798 sat
6799 >>> m = s.model()
6800 >>> f_i = m[f]
6801 >>> f_i.num_entries()
6802 1
6803 >>> e = f_i.entry(0)
6804 >>> e
6805 [1, 2, 20]
6806 >>> e.num_args()
6807 2
6808 >>> e.arg_value(0)
6809 1
6810 >>> e.arg_value(1)
6811 2
6812 >>> try:
6813 ... e.arg_value(2)
6814 ... except IndexError:
6815 ... print("index error")
6816 index error
6817 """
6818 if idx >= self.num_args():
6819 raise IndexError
6820 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
6821
6822 def value(self):
6823 """Return the value of the function at point `self`.
6824
6825 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6826 >>> s = Solver()
6827 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6828 >>> s.check()
6829 sat
6830 >>> m = s.model()
6831 >>> f_i = m[f]
6832 >>> f_i.num_entries()
6833 1
6834 >>> e = f_i.entry(0)
6835 >>> e
6836 [1, 2, 20]
6837 >>> e.num_args()
6838 2
6839 >>> e.value()
6840 20
6841 """
6842 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
6843
6844 def as_list(self):
6845 """Return entry `self` as a Python list.
6846 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6847 >>> s = Solver()
6848 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6849 >>> s.check()
6850 sat
6851 >>> m = s.model()
6852 >>> f_i = m[f]
6853 >>> f_i.num_entries()
6854 1
6855 >>> e = f_i.entry(0)
6856 >>> e.as_list()
6857 [1, 2, 20]
6858 """
6859 args = [self.arg_value(i) for i in range(self.num_args())]
6860 args.append(self.value())
6861 return args
6862
6863 def __repr__(self):
6864 return repr(self.as_list())
6865
6866
6868 """Stores the interpretation of a function in a Z3 model."""
6869
6870 def __init__(self, f, ctx):
6871 self.f = f
6872 self.ctx = ctx
6873 if self.f is not None:
6874 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
6875
6876 def __del__(self):
6877 if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_ref is not None:
6878 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
6879
6880 def else_value(self):
6881 """
6882 Return the `else` value for a function interpretation.
6883 Return None if Z3 did not specify the `else` value for
6884 this object.
6885
6886 >>> f = Function('f', IntSort(), IntSort())
6887 >>> s = Solver()
6888 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6889 >>> s.check()
6890 sat
6891 >>> m = s.model()
6892 >>> m[f]
6893 [2 -> 0, else -> 1]
6894 >>> m[f].else_value()
6895 1
6896 """
6897 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
6898 if r:
6899 return _to_expr_ref(r, self.ctx)
6900 else:
6901 return None
6902
6903 def num_entries(self):
6904 """Return the number of entries/points in the function interpretation `self`.
6905
6906 >>> f = Function('f', IntSort(), IntSort())
6907 >>> s = Solver()
6908 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6909 >>> s.check()
6910 sat
6911 >>> m = s.model()
6912 >>> m[f]
6913 [2 -> 0, else -> 1]
6914 >>> m[f].num_entries()
6915 1
6916 """
6917 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
6918
6919 def arity(self):
6920 """Return the number of arguments for each entry in the function interpretation `self`.
6921
6922 >>> f = Function('f', IntSort(), IntSort())
6923 >>> s = Solver()
6924 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6925 >>> s.check()
6926 sat
6927 >>> m = s.model()
6928 >>> m[f].arity()
6929 1
6930 """
6931 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
6932
6933 def entry(self, idx):
6934 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6935
6936 >>> f = Function('f', IntSort(), IntSort())
6937 >>> s = Solver()
6938 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6939 >>> s.check()
6940 sat
6941 >>> m = s.model()
6942 >>> m[f]
6943 [2 -> 0, else -> 1]
6944 >>> m[f].num_entries()
6945 1
6946 >>> m[f].entry(0)
6947 [2, 0]
6948 """
6949 if idx >= self.num_entries():
6950 raise IndexError
6951 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
6952
6953 def translate(self, other_ctx):
6954 """Copy model 'self' to context 'other_ctx'.
6955 """
6956 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
6957
6958 def __copy__(self):
6959 return self.translate(self.ctx)
6960
6961 def __deepcopy__(self, memo={}):
6962 return self.translate(self.ctx)
6963
6964 def as_list(self):
6965 """Return the function interpretation as a Python list.
6966 >>> f = Function('f', IntSort(), IntSort())
6967 >>> s = Solver()
6968 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6969 >>> s.check()
6970 sat
6971 >>> m = s.model()
6972 >>> m[f]
6973 [2 -> 0, else -> 1]
6974 >>> m[f].as_list()
6975 [[2, 0], 1]
6976 """
6977 r = [self.entry(i).as_list() for i in range(self.num_entries())]
6978 r.append(self.else_value())
6979 return r
6980
6981 def __repr__(self):
6982 return obj_to_string(self)
6983
6984
6986 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6987
6988 def __init__(self, m, ctx):
6989 assert ctx is not None
6990 self.model = m
6991 self.ctx = ctx
6992 Z3_model_inc_ref(self.ctx.ref(), self.model)
6993
6994 def __del__(self):
6995 if self.ctx.ref() is not None and Z3_model_dec_ref is not None:
6996 Z3_model_dec_ref(self.ctx.ref(), self.model)
6997
6998 def __repr__(self):
6999 return obj_to_string(self)
7000
7001 def sexpr(self):
7002 """Return a textual representation of the s-expression representing the model."""
7003 return Z3_model_to_string(self.ctx.ref(), self.model)
7004
7005 def eval(self, t, model_completion=False):
7006 """Evaluate the expression `t` in the model `self`.
7007 If `model_completion` is enabled, then a default interpretation is automatically added
7008 for symbols that do not have an interpretation in the model `self`.
7009
7010 >>> x = Int('x')
7011 >>> s = Solver()
7012 >>> s.add(x > 0, x < 2)
7013 >>> s.check()
7014 sat
7015 >>> m = s.model()
7016 >>> m.eval(x + 1)
7017 2
7018 >>> m.eval(x == 1)
7019 True
7020 >>> y = Int('y')
7021 >>> m.eval(y + x)
7022 1 + y
7023 >>> m.eval(y)
7024 y
7025 >>> m.eval(y, model_completion=True)
7026 0
7027 >>> # Now, m contains an interpretation for y
7028 >>> m.eval(y + x)
7029 1
7030 """
7031 r = (Ast * 1)()
7032 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
7033 return _to_expr_ref(r[0], self.ctx)
7034 raise Z3Exception("failed to evaluate expression in the model")
7035
7036 def evaluate(self, t, model_completion=False):
7037 """Alias for `eval`.
7038
7039 >>> x = Int('x')
7040 >>> s = Solver()
7041 >>> s.add(x > 0, x < 2)
7042 >>> s.check()
7043 sat
7044 >>> m = s.model()
7045 >>> m.evaluate(x + 1)
7046 2
7047 >>> m.evaluate(x == 1)
7048 True
7049 >>> y = Int('y')
7050 >>> m.evaluate(y + x)
7051 1 + y
7052 >>> m.evaluate(y)
7053 y
7054 >>> m.evaluate(y, model_completion=True)
7055 0
7056 >>> # Now, m contains an interpretation for y
7057 >>> m.evaluate(y + x)
7058 1
7059 """
7060 return self.eval(t, model_completion)
7061
7062 def __len__(self):
7063 """Return the number of constant and function declarations in the model `self`.
7064
7065 >>> f = Function('f', IntSort(), IntSort())
7066 >>> x = Int('x')
7067 >>> s = Solver()
7068 >>> s.add(x > 0, f(x) != x)
7069 >>> s.check()
7070 sat
7071 >>> m = s.model()
7072 >>> len(m)
7073 2
7074 """
7075 num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model))
7076 num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
7077 return num_consts + num_funcs
7078
7079 def get_interp(self, decl):
7080 """Return the interpretation for a given declaration or constant.
7081
7082 >>> f = Function('f', IntSort(), IntSort())
7083 >>> x = Int('x')
7084 >>> s = Solver()
7085 >>> s.add(x > 0, x < 2, f(x) == 0)
7086 >>> s.check()
7087 sat
7088 >>> m = s.model()
7089 >>> m[x]
7090 1
7091 >>> m[f]
7092 [else -> 0]
7093 """
7094 if z3_debug():
7095 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
7096 if is_const(decl):
7097 decl = decl.decl()
7098 try:
7099 if decl.arity() == 0:
7100 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
7101 if _r.value is None:
7102 return None
7103 r = _to_expr_ref(_r, self.ctx)
7104 if is_as_array(r):
7105 fi = self.get_interp(get_as_array_func(r))
7106 if fi is None:
7107 return fi
7108 e = fi.else_value()
7109 if e is None:
7110 return fi
7111 if fi.arity() != 1:
7112 return fi
7113 srt = decl.range()
7114 dom = srt.domain()
7115 e = K(dom, e)
7116 i = 0
7117 sz = fi.num_entries()
7118 n = fi.arity()
7119 while i < sz:
7120 fe = fi.entry(i)
7121 e = Store(e, fe.arg_value(0), fe.value())
7122 i += 1
7123 return e
7124 else:
7125 return r
7126 else:
7127 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
7128 except Z3Exception:
7129 return None
7130
7131 def num_sorts(self):
7132 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7133
7134 >>> A = DeclareSort('A')
7135 >>> a, b = Consts('a b', A)
7136 >>> s = Solver()
7137 >>> s.add(a != b)
7138 >>> s.check()
7139 sat
7140 >>> m = s.model()
7141 >>> m.num_sorts()
7142 1
7143 """
7144 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
7145
7146 def get_sort(self, idx):
7147 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7148
7149 >>> A = DeclareSort('A')
7150 >>> B = DeclareSort('B')
7151 >>> a1, a2 = Consts('a1 a2', A)
7152 >>> b1, b2 = Consts('b1 b2', B)
7153 >>> s = Solver()
7154 >>> s.add(a1 != a2, b1 != b2)
7155 >>> s.check()
7156 sat
7157 >>> m = s.model()
7158 >>> m.num_sorts()
7159 2
7160 >>> m.get_sort(0)
7161 A
7162 >>> m.get_sort(1)
7163 B
7164 """
7165 if idx >= self.num_sorts():
7166 raise IndexError
7167 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
7168
7169 def sorts(self):
7170 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7171
7172 >>> A = DeclareSort('A')
7173 >>> B = DeclareSort('B')
7174 >>> a1, a2 = Consts('a1 a2', A)
7175 >>> b1, b2 = Consts('b1 b2', B)
7176 >>> s = Solver()
7177 >>> s.add(a1 != a2, b1 != b2)
7178 >>> s.check()
7179 sat
7180 >>> m = s.model()
7181 >>> m.sorts()
7182 [A, B]
7183 """
7184 return [self.get_sort(i) for i in range(self.num_sorts())]
7185
7186 def get_universe(self, s):
7187 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7188
7189 >>> A = DeclareSort('A')
7190 >>> a, b = Consts('a b', A)
7191 >>> s = Solver()
7192 >>> s.add(a != b)
7193 >>> s.check()
7194 sat
7195 >>> m = s.model()
7196 >>> m.get_universe(A)
7197 [A!val!0, A!val!1]
7198 """
7199 if z3_debug():
7200 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
7201 try:
7202 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
7203 except Z3Exception:
7204 return None
7205
7206 def __getitem__(self, idx):
7207 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7208 If `idx` is a declaration, then the actual interpretation is returned.
7209
7210 The elements can be retrieved using position or the actual declaration.
7211
7212 >>> f = Function('f', IntSort(), IntSort())
7213 >>> x = Int('x')
7214 >>> s = Solver()
7215 >>> s.add(x > 0, x < 2, f(x) == 0)
7216 >>> s.check()
7217 sat
7218 >>> m = s.model()
7219 >>> len(m)
7220 2
7221 >>> m[0]
7222 x
7223 >>> m[1]
7224 f
7225 >>> m[x]
7226 1
7227 >>> m[f]
7228 [else -> 0]
7229 >>> for d in m: print("%s -> %s" % (d, m[d]))
7230 x -> 1
7231 f -> [else -> 0]
7232 """
7233 if _is_int(idx):
7234 if idx < 0:
7235 idx += len(self)
7236 if idx < 0 or idx >= len(self):
7237 raise IndexError
7238 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
7239 if (idx < num_consts):
7240 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
7241 else:
7242 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
7243 if isinstance(idx, FuncDeclRef):
7244 return self.get_interp(idx)
7245 if is_const(idx):
7246 return self.get_interp(idx.decl())
7247 if isinstance(idx, SortRef):
7248 return self.get_universe(idx)
7249 if z3_debug():
7250 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7251 return None
7252
7253 def decls(self):
7254 """Return a list with all symbols that have an interpretation in the model `self`.
7255 >>> f = Function('f', IntSort(), IntSort())
7256 >>> x = Int('x')
7257 >>> s = Solver()
7258 >>> s.add(x > 0, x < 2, f(x) == 0)
7259 >>> s.check()
7260 sat
7261 >>> m = s.model()
7262 >>> m.decls()
7263 [x, f]
7264 """
7265 r = []
7266 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
7267 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
7268 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
7269 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
7270 return r
7271
7272 def update_value(self, x, value):
7273 """Update the interpretation of a constant"""
7274 if is_expr(x):
7275 x = x.decl()
7276 if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp):
7277 fi1 = value.f
7278 fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast);
7279 fi2 = FuncInterp(fi2, x.ctx)
7280 for i in range(value.num_entries()):
7281 e = value.entry(i)
7282 n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry)
7283 v = AstVector()
7284 for j in range(n):
7285 v.push(e.arg_value(j))
7286 val = Z3_func_entry_get_value(x.ctx_ref(), e.entry)
7287 Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val)
7288 return
7289 if not is_func_decl(x) or x.arity() != 0:
7290 raise Z3Exception("Expecting 0-ary function or constant expression")
7291 value = _py2expr(value)
7292 Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast)
7293
7294 def translate(self, target):
7295 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7296 """
7297 if z3_debug():
7298 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
7299 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
7300 return ModelRef(model, target)
7301
7302 def project(self, vars, fml):
7303 """Perform model-based projection on fml with respect to vars.
7304 Assume that the model satisfies fml. Then compute a projection fml_p, such
7305 that vars do not occur free in fml_p, fml_p is true in the model and
7306 fml_p => exists vars . fml
7307 """
7308 ctx = self.ctx.ref()
7309 _vars = (Ast * len(vars))()
7310 for i in range(len(vars)):
7311 _vars[i] = vars[i].as_ast()
7312 return _to_expr_ref(Z3_qe_model_project(ctx, self.model, len(vars), _vars, fml.ast), self.ctx)
7313
7314 def project_with_witness(self, vars, fml):
7315 """Perform model-based projection, but also include realizer terms for the projected variables"""
7316 ctx = self.ctx.ref()
7317 _vars = (Ast * len(vars))()
7318 for i in range(len(vars)):
7319 _vars[i] = vars[i].as_ast()
7320 defs = AstMap()
7321 result = Z3_qe_model_project_with_witness(ctx, self.model, len(vars), _vars, fml.ast, defs.map)
7322 result = _to_expr_ref(result, self.ctx)
7323 return result, defs
7324
7325
7326 def __copy__(self):
7327 return self.translate(self.ctx)
7328
7329 def __deepcopy__(self, memo={}):
7330 return self.translate(self.ctx)
7331
7332
7333def Model(ctx=None, eval = {}):
7334 ctx = _get_ctx(ctx)
7335 mdl = ModelRef(Z3_mk_model(ctx.ref()), ctx)
7336 for k, v in eval.items():
7337 mdl.update_value(k, v)
7338 return mdl
7339
7340
7342 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7343 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7344
7345
7347 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7348 if z3_debug():
7349 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
7350 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
7351
7352
7357
7358
7360 """Statistics for `Solver.check()`."""
7361
7362 def __init__(self, stats, ctx):
7363 self.stats = stats
7364 self.ctx = ctx
7365 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
7366
7367 def __deepcopy__(self, memo={}):
7368 return Statistics(self.stats, self.ctx)
7369
7370 def __del__(self):
7371 if self.ctx.ref() is not None and Z3_stats_dec_ref is not None:
7372 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
7373
7374 def __repr__(self):
7375 if in_html_mode():
7376 out = io.StringIO()
7377 even = True
7378 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
7379 for k, v in self:
7380 if even:
7381 out.write(u('<tr style="background-color:#CFCFCF">'))
7382 even = False
7383 else:
7384 out.write(u("<tr>"))
7385 even = True
7386 out.write(u("<td>%s</td><td>%s</td></tr>" % (k, v)))
7387 out.write(u("</table>"))
7388 return out.getvalue()
7389 else:
7390 return Z3_stats_to_string(self.ctx.ref(), self.stats)
7391
7392 def __len__(self):
7393 """Return the number of statistical counters.
7394
7395 >>> x = Int('x')
7396 >>> s = Then('simplify', 'nlsat').solver()
7397 >>> s.add(x > 0)
7398 >>> s.check()
7399 sat
7400 >>> st = s.statistics()
7401 >>> len(st) > 0
7402 True
7403 """
7404 return int(Z3_stats_size(self.ctx.ref(), self.stats))
7405
7406 def __getitem__(self, idx):
7407 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7408
7409 >>> x = Int('x')
7410 >>> s = Then('simplify', 'nlsat').solver()
7411 >>> s.add(x > 0)
7412 >>> s.check()
7413 sat
7414 >>> st = s.statistics()
7415 >>> len(st) > 0
7416 True
7417 >>> st[0]
7418 ('nlsat propagations', 2)
7419 >>> st[1]
7420 ('nlsat restarts', 1)
7421 """
7422 if idx >= len(self):
7423 raise IndexError
7424 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7425 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7426 else:
7427 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7428 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
7429
7430 def keys(self):
7431 """Return the list of statistical counters.
7432
7433 >>> x = Int('x')
7434 >>> s = Then('simplify', 'nlsat').solver()
7435 >>> s.add(x > 0)
7436 >>> s.check()
7437 sat
7438 >>> st = s.statistics()
7439 """
7440 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
7441
7442 def get_key_value(self, key):
7443 """Return the value of a particular statistical counter.
7444
7445 >>> x = Int('x')
7446 >>> s = Then('simplify', 'nlsat').solver()
7447 >>> s.add(x > 0)
7448 >>> s.check()
7449 sat
7450 >>> st = s.statistics()
7451 >>> st.get_key_value('nlsat propagations')
7452 2
7453 """
7454 for idx in range(len(self)):
7455 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
7456 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
7457 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
7458 else:
7459 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
7460 raise Z3Exception("unknown key")
7461
7462 def __getattr__(self, name):
7463 """Access the value of statistical using attributes.
7464
7465 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7466 we should use '_' (e.g., 'nlsat_propagations').
7467
7468 >>> x = Int('x')
7469 >>> s = Then('simplify', 'nlsat').solver()
7470 >>> s.add(x > 0)
7471 >>> s.check()
7472 sat
7473 >>> st = s.statistics()
7474 >>> st.nlsat_propagations
7475 2
7476 >>> st.nlsat_stages
7477 2
7478 """
7479 key = name.replace("_", " ")
7480 try:
7481 return self.get_key_value(key)
7482 except Z3Exception:
7483 raise AttributeError
7484
7485
7490
7491
7493 """Represents the result of a satisfiability check: sat, unsat, unknown.
7494
7495 >>> s = Solver()
7496 >>> s.check()
7497 sat
7498 >>> r = s.check()
7499 >>> isinstance(r, CheckSatResult)
7500 True
7501 """
7502
7503 def __init__(self, r):
7504 self.r = r
7505
7506 def __deepcopy__(self, memo={}):
7507 return CheckSatResult(self.r)
7508
7509 def __eq__(self, other):
7510 return isinstance(other, CheckSatResult) and self.r == other.r
7511
7512 def __ne__(self, other):
7513 return not self.__eq__(other)
7514
7515 def __repr__(self):
7516 if in_html_mode():
7517 if self.r == Z3_L_TRUE:
7518 return "<b>sat</b>"
7519 elif self.r == Z3_L_FALSE:
7520 return "<b>unsat</b>"
7521 else:
7522 return "<b>unknown</b>"
7523 else:
7524 if self.r == Z3_L_TRUE:
7525 return "sat"
7526 elif self.r == Z3_L_FALSE:
7527 return "unsat"
7528 else:
7529 return "unknown"
7530
7531 def _repr_html_(self):
7532 in_html = in_html_mode()
7533 set_html_mode(True)
7534 res = repr(self)
7535 set_html_mode(in_html)
7536 return res
7537
7538
7539sat = CheckSatResult(Z3_L_TRUE)
7540unsat = CheckSatResult(Z3_L_FALSE)
7541unknown = CheckSatResult(Z3_L_UNDEF)
7542
7543
7545 """
7546 Solver API provides methods for implementing the main SMT 2.0 commands:
7547 push, pop, check, get-model, etc.
7548 """
7549
7550 def __init__(self, solver=None, ctx=None, logFile=None):
7551 assert solver is None or ctx is not None
7552 self.ctx = _get_ctx(ctx)
7553 self.backtrack_level = 4000000000
7554 self.solver = None
7555 if solver is None:
7556 self.solver = Z3_mk_solver(self.ctx.ref())
7557 else:
7558 self.solver = solver
7559 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
7560 if logFile is not None:
7561 self.set("smtlib2_log", logFile)
7562
7563 def __del__(self):
7564 if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_ref is not None:
7565 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
7566
7567 def __enter__(self):
7568 self.push()
7569 return self
7570
7571 def __exit__(self, *exc_info):
7572 self.pop()
7573
7574 def set(self, *args, **keys):
7575 """Set a configuration option.
7576 The method `help()` return a string containing all available options.
7577
7578 >>> s = Solver()
7579 >>> # The option MBQI can be set using three different approaches.
7580 >>> s.set(mbqi=True)
7581 >>> s.set('MBQI', True)
7582 >>> s.set(':mbqi', True)
7583 """
7584 p = args2params(args, keys, self.ctx)
7585 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
7586
7587 def push(self):
7588 """Create a backtracking point.
7589
7590 >>> x = Int('x')
7591 >>> s = Solver()
7592 >>> s.add(x > 0)
7593 >>> s
7594 [x > 0]
7595 >>> s.push()
7596 >>> s.add(x < 1)
7597 >>> s
7598 [x > 0, x < 1]
7599 >>> s.check()
7600 unsat
7601 >>> s.pop()
7602 >>> s.check()
7603 sat
7604 >>> s
7605 [x > 0]
7606 """
7607 Z3_solver_push(self.ctx.ref(), self.solver)
7608
7609 def pop(self, num=1):
7610 """Backtrack \\c num backtracking points.
7611
7612 >>> x = Int('x')
7613 >>> s = Solver()
7614 >>> s.add(x > 0)
7615 >>> s
7616 [x > 0]
7617 >>> s.push()
7618 >>> s.add(x < 1)
7619 >>> s
7620 [x > 0, x < 1]
7621 >>> s.check()
7622 unsat
7623 >>> s.pop()
7624 >>> s.check()
7625 sat
7626 >>> s
7627 [x > 0]
7628 """
7629 Z3_solver_pop(self.ctx.ref(), self.solver, num)
7630
7631 def num_scopes(self):
7632 """Return the current number of backtracking points.
7633
7634 >>> s = Solver()
7635 >>> s.num_scopes()
7636 0
7637 >>> s.push()
7638 >>> s.num_scopes()
7639 1
7640 >>> s.push()
7641 >>> s.num_scopes()
7642 2
7643 >>> s.pop()
7644 >>> s.num_scopes()
7645 1
7646 """
7647 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
7648
7649 def reset(self):
7650 """Remove all asserted constraints and backtracking points created using `push()`.
7651
7652 >>> x = Int('x')
7653 >>> s = Solver()
7654 >>> s.add(x > 0)
7655 >>> s
7656 [x > 0]
7657 >>> s.reset()
7658 >>> s
7659 []
7660 """
7661 Z3_solver_reset(self.ctx.ref(), self.solver)
7662
7663 def assert_exprs(self, *args):
7664 """Assert constraints into the solver.
7665
7666 >>> x = Int('x')
7667 >>> s = Solver()
7668 >>> s.assert_exprs(x > 0, x < 2)
7669 >>> s
7670 [x > 0, x < 2]
7671 """
7672 args = _get_args(args)
7673 s = BoolSort(self.ctx)
7674 for arg in args:
7675 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7676 for f in arg:
7677 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
7678 else:
7679 arg = s.cast(arg)
7680 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
7681
7682 def add(self, *args):
7683 """Assert constraints into the solver.
7684
7685 >>> x = Int('x')
7686 >>> s = Solver()
7687 >>> s.add(x > 0, x < 2)
7688 >>> s
7689 [x > 0, x < 2]
7690 """
7691 self.assert_exprs(*args)
7692
7693 def __iadd__(self, fml):
7694 self.add(fml)
7695 return self
7696
7697 def append(self, *args):
7698 """Assert constraints into the solver.
7699
7700 >>> x = Int('x')
7701 >>> s = Solver()
7702 >>> s.append(x > 0, x < 2)
7703 >>> s
7704 [x > 0, x < 2]
7705 """
7706 self.assert_exprs(*args)
7707
7708 def insert(self, *args):
7709 """Assert constraints into the solver.
7710
7711 >>> x = Int('x')
7712 >>> s = Solver()
7713 >>> s.insert(x > 0, x < 2)
7714 >>> s
7715 [x > 0, x < 2]
7716 """
7717 self.assert_exprs(*args)
7718
7719 def assert_and_track(self, a, p):
7720 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7721
7722 If `p` is a string, it will be automatically converted into a Boolean constant.
7723
7724 >>> x = Int('x')
7725 >>> p3 = Bool('p3')
7726 >>> s = Solver()
7727 >>> s.set(unsat_core=True)
7728 >>> s.assert_and_track(x > 0, 'p1')
7729 >>> s.assert_and_track(x != 1, 'p2')
7730 >>> s.assert_and_track(x < 0, p3)
7731 >>> print(s.check())
7732 unsat
7733 >>> c = s.unsat_core()
7734 >>> len(c)
7735 2
7736 >>> Bool('p1') in c
7737 True
7738 >>> Bool('p2') in c
7739 False
7740 >>> p3 in c
7741 True
7742 """
7743 if isinstance(p, str):
7744 p = Bool(p, self.ctx)
7745 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7746 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7747 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
7748
7749 def check(self, *assumptions):
7750 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7751
7752 >>> x = Int('x')
7753 >>> s = Solver()
7754 >>> s.check()
7755 sat
7756 >>> s.add(x > 0, x < 2)
7757 >>> s.check()
7758 sat
7759 >>> s.model().eval(x)
7760 1
7761 >>> s.add(x < 1)
7762 >>> s.check()
7763 unsat
7764 >>> s.reset()
7765 >>> s.add(2**x == 4)
7766 >>> s.check()
7767 sat
7768 """
7769 s = BoolSort(self.ctx)
7770 assumptions = _get_args(assumptions)
7771 num = len(assumptions)
7772 _assumptions = (Ast * num)()
7773 for i in range(num):
7774 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7775 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
7776 return CheckSatResult(r)
7777
7778 def model(self):
7779 """Return a model for the last `check()`.
7780
7781 This function raises an exception if
7782 a model is not available (e.g., last `check()` returned unsat).
7783
7784 >>> s = Solver()
7785 >>> a = Int('a')
7786 >>> s.add(a + 2 == 0)
7787 >>> s.check()
7788 sat
7789 >>> s.model()
7790 [a = -2]
7791 """
7792 try:
7793 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
7794 except Z3Exception:
7795 raise Z3Exception("model is not available")
7796
7797 def import_model_converter(self, other):
7798 """Import model converter from other into the current solver"""
7799 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7800
7801 def interrupt(self):
7802 """Interrupt the execution of the solver object.
7803 Remarks: This ensures that the interrupt applies only
7804 to the given solver object and it applies only if it is running.
7805 """
7806 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7807
7808 def unsat_core(self):
7809 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7810
7811 These are the assumptions Z3 used in the unsatisfiability proof.
7812 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7813 They may be also used to "retract" assumptions. Note that, assumptions are not really
7814 "soft constraints", but they can be used to implement them.
7815
7816 >>> p1, p2, p3 = Bools('p1 p2 p3')
7817 >>> x, y = Ints('x y')
7818 >>> s = Solver()
7819 >>> s.add(Implies(p1, x > 0))
7820 >>> s.add(Implies(p2, y > x))
7821 >>> s.add(Implies(p2, y < 1))
7822 >>> s.add(Implies(p3, y > -3))
7823 >>> s.check(p1, p2, p3)
7824 unsat
7825 >>> core = s.unsat_core()
7826 >>> len(core)
7827 2
7828 >>> p1 in core
7829 True
7830 >>> p2 in core
7831 True
7832 >>> p3 in core
7833 False
7834 >>> # "Retracting" p2
7835 >>> s.check(p1, p3)
7836 sat
7837 """
7838 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7839
7840 def consequences(self, assumptions, variables):
7841 """Determine fixed values for the variables based on the solver state and assumptions.
7842 >>> s = Solver()
7843 >>> a, b, c, d = Bools('a b c d')
7844 >>> s.add(Implies(a,b), Implies(b, c))
7845 >>> s.consequences([a],[b,c,d])
7846 (sat, [Implies(a, b), Implies(a, c)])
7847 >>> s.consequences([Not(c),d],[a,b,c,d])
7848 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7849 """
7850 if isinstance(assumptions, list):
7851 _asms = AstVector(None, self.ctx)
7852 for a in assumptions:
7853 _asms.push(a)
7854 assumptions = _asms
7855 if isinstance(variables, list):
7856 _vars = AstVector(None, self.ctx)
7857 for a in variables:
7858 _vars.push(a)
7859 variables = _vars
7860 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7861 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7862 consequences = AstVector(None, self.ctx)
7863 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7864 variables.vector, consequences.vector)
7865 sz = len(consequences)
7866 consequences = [consequences[i] for i in range(sz)]
7867 return CheckSatResult(r), consequences
7868
7869 def from_file(self, filename):
7870 """Parse assertions from a file"""
7871 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7872
7873 def from_string(self, s):
7874 """Parse assertions from a string"""
7875 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7876
7877 def cube(self, vars=None):
7878 """Get set of cubes
7879 The method takes an optional set of variables that restrict which
7880 variables may be used as a starting point for cubing.
7881 If vars is not None, then the first case split is based on a variable in
7882 this set.
7883 """
7884 self.cube_vs = AstVector(None, self.ctx)
7885 if vars is not None:
7886 for v in vars:
7887 self.cube_vs.push(v)
7888 while True:
7889 lvl = self.backtrack_level
7890 self.backtrack_level = 4000000000
7891 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7892 if (len(r) == 1 and is_false(r[0])):
7893 return
7894 yield r
7895 if (len(r) == 0):
7896 return
7897
7898 def cube_vars(self):
7899 """Access the set of variables that were touched by the most recently generated cube.
7900 This set of variables can be used as a starting point for additional cubes.
7901 The idea is that variables that appear in clauses that are reduced by the most recent
7902 cube are likely more useful to cube on."""
7903 return self.cube_vs
7904
7905 def congruence_root(self, t):
7906 """Retrieve congruence closure root of the term t relative to the current search state
7907 The function primarily works for SimpleSolver. Terms and variables that are
7908 eliminated during pre-processing are not visible to the congruence closure.
7909 """
7910 t = _py2expr(t, self.ctx)
7911 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
7912
7913 def congruence_next(self, t):
7914 """Retrieve congruence closure sibling of the term t relative to the current search state
7915 The function primarily works for SimpleSolver. Terms and variables that are
7916 eliminated during pre-processing are not visible to the congruence closure.
7917 """
7918 t = _py2expr(t, self.ctx)
7919 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
7920
7921 def congruence_explain(self, a, b):
7922 """Explain congruence of a and b relative to the current search state"""
7923 a = _py2expr(a, self.ctx)
7924 b = _py2expr(b, self.ctx)
7925 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
7926
7927
7928 def solve_for(self, ts):
7929 """Retrieve a solution for t relative to linear equations maintained in the current state."""
7930 vars = AstVector(ctx=self.ctx);
7931 terms = AstVector(ctx=self.ctx);
7932 guards = AstVector(ctx=self.ctx);
7933 for t in ts:
7934 t = _py2expr(t, self.ctx)
7935 vars.push(t)
7936 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
7937 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
7938
7939
7940 def proof(self):
7941 """Return a proof for the last `check()`. Proof construction must be enabled."""
7942 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7943
7944 def assertions(self):
7945 """Return an AST vector containing all added constraints.
7946
7947 >>> s = Solver()
7948 >>> s.assertions()
7949 []
7950 >>> a = Int('a')
7951 >>> s.add(a > 0)
7952 >>> s.add(a < 10)
7953 >>> s.assertions()
7954 [a > 0, a < 10]
7955 """
7956 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7957
7958 def units(self):
7959 """Return an AST vector containing all currently inferred units.
7960 """
7961 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7962
7963 def non_units(self):
7964 """Return an AST vector containing all atomic formulas in solver state that are not units.
7965 """
7966 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7967
7968 def trail_levels(self):
7969 """Return trail and decision levels of the solver state after a check() call.
7970 """
7971 trail = self.trail()
7972 levels = (ctypes.c_uint * len(trail))()
7973 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7974 return trail, levels
7975
7976 def set_initial_value(self, var, value):
7977 """initialize the solver's state by setting the initial value of var to value
7978 """
7979 s = var.sort()
7980 value = s.cast(value)
7981 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
7982
7983 def trail(self):
7984 """Return trail of the solver state after a check() call.
7985 """
7986 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7987
7988 def statistics(self):
7989 """Return statistics for the last `check()`.
7990
7991 >>> s = SimpleSolver()
7992 >>> x = Int('x')
7993 >>> s.add(x > 0)
7994 >>> s.check()
7995 sat
7996 >>> st = s.statistics()
7997 >>> st.get_key_value('final checks')
7998 1
7999 >>> len(st) > 0
8000 True
8001 >>> st[0] != 0
8002 True
8003 """
8004 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8005
8006 def reason_unknown(self):
8007 """Return a string describing why the last `check()` returned `unknown`.
8008
8009 >>> x = Int('x')
8010 >>> s = SimpleSolver()
8011 >>> s.add(x == 2**x)
8012 >>> s.check()
8013 unknown
8014 >>> s.reason_unknown()
8015 '(incomplete (theory arithmetic))'
8016 """
8017 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8018
8019 def help(self):
8020 """Display a string describing all available options."""
8021 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8022
8023 def param_descrs(self):
8024 """Return the parameter description set."""
8025 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8026
8027 def __repr__(self):
8028 """Return a formatted string with all added constraints."""
8029 return obj_to_string(self)
8030
8031 def translate(self, target):
8032 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8033
8034 >>> c1 = Context()
8035 >>> c2 = Context()
8036 >>> s1 = Solver(ctx=c1)
8037 >>> s2 = s1.translate(c2)
8038 """
8039 if z3_debug():
8040 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8041 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8042 return Solver(solver, target)
8043
8044 def __copy__(self):
8045 return self.translate(self.ctx)
8046
8047 def __deepcopy__(self, memo={}):
8048 return self.translate(self.ctx)
8049
8050 def sexpr(self):
8051 """Return a formatted string (in Lisp-like format) with all added constraints.
8052 """
8053 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8054
8055 def dimacs(self, include_names=True):
8056 """Return a textual representation of the solver in DIMACS format."""
8057 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8058
8059 def to_smt2(self):
8060 """return SMTLIB2 formatted benchmark for solver's assertions"""
8061 es = self.assertions()
8062 sz = len(es)
8063 sz1 = sz
8064 if sz1 > 0:
8065 sz1 -= 1
8066 v = (Ast * sz1)()
8067 for i in range(sz1):
8068 v[i] = es[i].as_ast()
8069 if sz > 0:
8070 e = es[sz1].as_ast()
8071 else:
8072 e = BoolVal(True, self.ctx).as_ast()
8073 return Z3_benchmark_to_smtlib_string(
8074 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8075 )
8076
8077 def solutions(self, t):
8078 """Returns an iterator over solutions that satisfy the constraints.
8079
8080 The parameter `t` is an expression whose values should be returned.
8081
8082 >>> s = Solver()
8083 >>> x, y, z = Ints("x y z")
8084 >>> s.add(x * x == 4)
8085 >>> print(list(s.solutions(x)))
8086 [-2, 2]
8087 >>> s.reset()
8088 >>> s.add(x >= 0, x < 10)
8089 >>> print(list(s.solutions(x)))
8090 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8091 >>> s.reset()
8092 >>> s.add(x >= 0, y < 10, y == 2*x)
8093 >>> print(list(s.solutions([x, y])))
8094 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8095 """
8096 s = Solver()
8097 s.add(self.assertions())
8098 t = _get_args(t)
8099 if isinstance(t, (list, tuple)):
8100 while s.check() == sat:
8101 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8102 yield result
8103 s.add(Or(t_ != result_ for t_, result_ in zip(t, result)))
8104 else:
8105 while s.check() == sat:
8106 result = s.model().eval(t, model_completion=True)
8107 yield result
8108 s.add(t != result)
8109
8110
8111def SolverFor(logic, ctx=None, logFile=None):
8112 """Create a solver customized for the given logic.
8113
8114 The parameter `logic` is a string. It should be contains
8115 the name of a SMT-LIB logic.
8116 See http://www.smtlib.org/ for the name of all available logics.
8117
8118 >>> s = SolverFor("QF_LIA")
8119 >>> x = Int('x')
8120 >>> s.add(x > 0)
8121 >>> s.add(x < 2)
8122 >>> s.check()
8123 sat
8124 >>> s.model()
8125 [x = 1]
8126 """
8127 ctx = _get_ctx(ctx)
8128 logic = to_symbol(logic)
8129 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8130
8131
8132def SimpleSolver(ctx=None, logFile=None):
8133 """Return a simple general purpose solver with limited amount of preprocessing.
8134
8135 >>> s = SimpleSolver()
8136 >>> x = Int('x')
8137 >>> s.add(x > 0)
8138 >>> s.check()
8139 sat
8140 """
8141 ctx = _get_ctx(ctx)
8142 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8143
8144#########################################
8145#
8146# Fixedpoint
8147#
8148#########################################
8149
8150
8151class Fixedpoint(Z3PPObject):
8152 """Fixedpoint API provides methods for solving with recursive predicates"""
8153
8154 def __init__(self, fixedpoint=None, ctx=None):
8155 assert fixedpoint is None or ctx is not None
8156 self.ctx = _get_ctx(ctx)
8157 self.fixedpoint = None
8158 if fixedpoint is None:
8159 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8160 else:
8161 self.fixedpoint = fixedpoint
8162 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8163 self.vars = []
8164
8165 def __deepcopy__(self, memo={}):
8166 return FixedPoint(self.fixedpoint, self.ctx)
8167
8168 def __del__(self):
8169 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8170 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8171
8172 def set(self, *args, **keys):
8173 """Set a configuration option. The method `help()` return a string containing all available options.
8174 """
8175 p = args2params(args, keys, self.ctx)
8176 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8177
8178 def help(self):
8179 """Display a string describing all available options."""
8180 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8181
8182 def param_descrs(self):
8183 """Return the parameter description set."""
8184 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8185
8186 def assert_exprs(self, *args):
8187 """Assert constraints as background axioms for the fixedpoint solver."""
8188 args = _get_args(args)
8189 s = BoolSort(self.ctx)
8190 for arg in args:
8191 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8192 for f in arg:
8193 f = self.abstract(f)
8194 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8195 else:
8196 arg = s.cast(arg)
8197 arg = self.abstract(arg)
8198 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8199
8200 def add(self, *args):
8201 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8202 self.assert_exprs(*args)
8203
8204 def __iadd__(self, fml):
8205 self.add(fml)
8206 return self
8207
8208 def append(self, *args):
8209 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8210 self.assert_exprs(*args)
8211
8212 def insert(self, *args):
8213 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8214 self.assert_exprs(*args)
8215
8216 def add_rule(self, head, body=None, name=None):
8217 """Assert rules defining recursive predicates to the fixedpoint solver.
8218 >>> a = Bool('a')
8219 >>> b = Bool('b')
8220 >>> s = Fixedpoint()
8221 >>> s.register_relation(a.decl())
8222 >>> s.register_relation(b.decl())
8223 >>> s.fact(a)
8224 >>> s.rule(b, a)
8225 >>> s.query(b)
8226 sat
8227 """
8228 if name is None:
8229 name = ""
8230 name = to_symbol(name, self.ctx)
8231 if body is None:
8232 head = self.abstract(head)
8233 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8234 else:
8235 body = _get_args(body)
8236 f = self.abstract(Implies(And(body, self.ctx), head))
8237 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8238
8239 def rule(self, head, body=None, name=None):
8240 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8241 self.add_rule(head, body, name)
8242
8243 def fact(self, head, name=None):
8244 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8245 self.add_rule(head, None, name)
8246
8247 def query(self, *query):
8248 """Query the fixedpoint engine whether formula is derivable.
8249 You can also pass an tuple or list of recursive predicates.
8250 """
8251 query = _get_args(query)
8252 sz = len(query)
8253 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8254 _decls = (FuncDecl * sz)()
8255 i = 0
8256 for q in query:
8257 _decls[i] = q.ast
8258 i = i + 1
8259 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8260 else:
8261 if sz == 1:
8262 query = query[0]
8263 else:
8264 query = And(query, self.ctx)
8265 query = self.abstract(query, False)
8266 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8267 return CheckSatResult(r)
8268
8269 def query_from_lvl(self, lvl, *query):
8270 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8271 """
8272 query = _get_args(query)
8273 sz = len(query)
8274 if sz >= 1 and isinstance(query[0], FuncDecl):
8275 _z3_assert(False, "unsupported")
8276 else:
8277 if sz == 1:
8278 query = query[0]
8279 else:
8280 query = And(query)
8281 query = self.abstract(query, False)
8282 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8283 return CheckSatResult(r)
8284
8285 def update_rule(self, head, body, name):
8286 """update rule"""
8287 if name is None:
8288 name = ""
8289 name = to_symbol(name, self.ctx)
8290 body = _get_args(body)
8291 f = self.abstract(Implies(And(body, self.ctx), head))
8292 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8293
8294 def get_answer(self):
8295 """Retrieve answer from last query call."""
8296 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8297 return _to_expr_ref(r, self.ctx)
8298
8299 def get_ground_sat_answer(self):
8300 """Retrieve a ground cex from last query call."""
8301 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8302 return _to_expr_ref(r, self.ctx)
8303
8304 def get_rules_along_trace(self):
8305 """retrieve rules along the counterexample trace"""
8306 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8307
8308 def get_rule_names_along_trace(self):
8309 """retrieve rule names along the counterexample trace"""
8310 # this is a hack as I don't know how to return a list of symbols from C++;
8311 # obtain names as a single string separated by semicolons
8312 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8313 # split into individual names
8314 return names.split(";")
8315
8316 def get_num_levels(self, predicate):
8317 """Retrieve number of levels used for predicate in PDR engine"""
8318 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8319
8320 def get_cover_delta(self, level, predicate):
8321 """Retrieve properties known about predicate for the level'th unfolding.
8322 -1 is treated as the limit (infinity)
8323 """
8324 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8325 return _to_expr_ref(r, self.ctx)
8326
8327 def add_cover(self, level, predicate, property):
8328 """Add property to predicate for the level'th unfolding.
8329 -1 is treated as infinity (infinity)
8330 """
8331 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8332
8333 def register_relation(self, *relations):
8334 """Register relation as recursive"""
8335 relations = _get_args(relations)
8336 for f in relations:
8337 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8338
8339 def set_predicate_representation(self, f, *representations):
8340 """Control how relation is represented"""
8341 representations = _get_args(representations)
8342 representations = [to_symbol(s) for s in representations]
8343 sz = len(representations)
8344 args = (Symbol * sz)()
8345 for i in range(sz):
8346 args[i] = representations[i]
8347 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8348
8349 def parse_string(self, s):
8350 """Parse rules and queries from a string"""
8351 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8352
8353 def parse_file(self, f):
8354 """Parse rules and queries from a file"""
8355 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8356
8357 def get_rules(self):
8358 """retrieve rules that have been added to fixedpoint context"""
8359 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8360
8361 def get_assertions(self):
8362 """retrieve assertions that have been added to fixedpoint context"""
8363 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8364
8365 def __repr__(self):
8366 """Return a formatted string with all added rules and constraints."""
8367 return self.sexpr()
8368
8369 def sexpr(self):
8370 """Return a formatted string (in Lisp-like format) with all added constraints.
8371 We say the string is in s-expression format.
8372 """
8373 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8374
8375 def to_string(self, queries):
8376 """Return a formatted string (in Lisp-like format) with all added constraints.
8377 We say the string is in s-expression format.
8378 Include also queries.
8379 """
8380 args, len = _to_ast_array(queries)
8381 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8382
8383 def statistics(self):
8384 """Return statistics for the last `query()`.
8385 """
8386 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8387
8388 def reason_unknown(self):
8389 """Return a string describing why the last `query()` returned `unknown`.
8390 """
8391 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8392
8393 def declare_var(self, *vars):
8394 """Add variable or several variables.
8395 The added variable or variables will be bound in the rules
8396 and queries
8397 """
8398 vars = _get_args(vars)
8399 for v in vars:
8400 self.vars += [v]
8401
8402 def abstract(self, fml, is_forall=True):
8403 if self.vars == []:
8404 return fml
8405 if is_forall:
8406 return ForAll(self.vars, fml)
8407 else:
8408 return Exists(self.vars, fml)
8409
8410
8411#########################################
8412#
8413# Finite domains
8414#
8415#########################################
8416
8417class FiniteDomainSortRef(SortRef):
8418 """Finite domain sort."""
8419
8420 def size(self):
8421 """Return the size of the finite domain sort"""
8422 r = (ctypes.c_ulonglong * 1)()
8423 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8424 return r[0]
8425 else:
8426 raise Z3Exception("Failed to retrieve finite domain sort size")
8427
8428
8429def FiniteDomainSort(name, sz, ctx=None):
8430 """Create a named finite domain sort of a given size sz"""
8431 if not isinstance(name, Symbol):
8432 name = to_symbol(name)
8433 ctx = _get_ctx(ctx)
8434 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8435
8436
8437def is_finite_domain_sort(s):
8438 """Return True if `s` is a Z3 finite-domain sort.
8439
8440 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8441 True
8442 >>> is_finite_domain_sort(IntSort())
8443 False
8444 """
8445 return isinstance(s, FiniteDomainSortRef)
8446
8447
8448class FiniteDomainRef(ExprRef):
8449 """Finite-domain expressions."""
8450
8451 def sort(self):
8452 """Return the sort of the finite-domain expression `self`."""
8453 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8454
8455 def as_string(self):
8456 """Return a Z3 floating point expression as a Python string."""
8457 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8458
8459
8460def is_finite_domain(a):
8461 """Return `True` if `a` is a Z3 finite-domain expression.
8462
8463 >>> s = FiniteDomainSort('S', 100)
8464 >>> b = Const('b', s)
8465 >>> is_finite_domain(b)
8466 True
8467 >>> is_finite_domain(Int('x'))
8468 False
8469 """
8470 return isinstance(a, FiniteDomainRef)
8471
8472
8473class FiniteDomainNumRef(FiniteDomainRef):
8474 """Integer values."""
8475
8476 def as_long(self):
8477 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8478
8479 >>> s = FiniteDomainSort('S', 100)
8480 >>> v = FiniteDomainVal(3, s)
8481 >>> v
8482 3
8483 >>> v.as_long() + 1
8484 4
8485 """
8486 return int(self.as_string())
8487
8488 def as_string(self):
8489 """Return a Z3 finite-domain numeral as a Python string.
8490
8491 >>> s = FiniteDomainSort('S', 100)
8492 >>> v = FiniteDomainVal(42, s)
8493 >>> v.as_string()
8494 '42'
8495 """
8496 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8497
8498
8499def FiniteDomainVal(val, sort, ctx=None):
8500 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8501
8502 >>> s = FiniteDomainSort('S', 256)
8503 >>> FiniteDomainVal(255, s)
8504 255
8505 >>> FiniteDomainVal('100', s)
8506 100
8507 """
8508 if z3_debug():
8509 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8510 ctx = sort.ctx
8511 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8512
8513
8514def is_finite_domain_value(a):
8515 """Return `True` if `a` is a Z3 finite-domain value.
8516
8517 >>> s = FiniteDomainSort('S', 100)
8518 >>> b = Const('b', s)
8519 >>> is_finite_domain_value(b)
8520 False
8521 >>> b = FiniteDomainVal(10, s)
8522 >>> b
8523 10
8524 >>> is_finite_domain_value(b)
8525 True
8526 """
8527 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8528
8529
8530#########################################
8531#
8532# Optimize
8533#
8534#########################################
8535
8536class OptimizeObjective:
8537 def __init__(self, opt, value, is_max):
8538 self._opt = opt
8539 self._value = value
8540 self._is_max = is_max
8541
8542 def lower(self):
8543 opt = self._opt
8544 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8545
8546 def upper(self):
8547 opt = self._opt
8548 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8549
8550 def lower_values(self):
8551 opt = self._opt
8552 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8553
8554 def upper_values(self):
8555 opt = self._opt
8556 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8557
8558 def value(self):
8559 if self._is_max:
8560 return self.upper()
8561 else:
8562 return self.lower()
8563
8564 def __str__(self):
8565 return "%s:%s" % (self._value, self._is_max)
8566
8567
8568_on_models = {}
8569
8570
8571def _global_on_model(ctx):
8572 (fn, mdl) = _on_models[ctx]
8573 fn(mdl)
8574
8575
8576_on_model_eh = on_model_eh_type(_global_on_model)
8577
8578
8579class Optimize(Z3PPObject):
8580 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8581
8582 def __init__(self, optimize=None, ctx=None):
8583 self.ctx = _get_ctx(ctx)
8584 if optimize is None:
8585 self.optimize = Z3_mk_optimize(self.ctx.ref())
8586 else:
8587 self.optimize = optimize
8588 self._on_models_id = None
8589 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8590
8591 def __copy__(self):
8592 return self.translate(self.ctx)
8593
8594 def __deepcopy__(self, memo={}):
8595 return self.translate(self.ctx)
8596
8597 def __del__(self):
8598 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8599 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8600 if self._on_models_id is not None:
8601 del _on_models[self._on_models_id]
8602
8603 def __enter__(self):
8604 self.push()
8605 return self
8606
8607 def __exit__(self, *exc_info):
8608 self.pop()
8609
8610 def set(self, *args, **keys):
8611 """Set a configuration option.
8612 The method `help()` return a string containing all available options.
8613 """
8614 p = args2params(args, keys, self.ctx)
8615 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8616
8617 def help(self):
8618 """Display a string describing all available options."""
8619 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8620
8621 def param_descrs(self):
8622 """Return the parameter description set."""
8623 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8624
8625 def assert_exprs(self, *args):
8626 """Assert constraints as background axioms for the optimize solver."""
8627 args = _get_args(args)
8628 s = BoolSort(self.ctx)
8629 for arg in args:
8630 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8631 for f in arg:
8632 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8633 else:
8634 arg = s.cast(arg)
8635 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8636
8637 def add(self, *args):
8638 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8639 self.assert_exprs(*args)
8640
8641 def __iadd__(self, fml):
8642 self.add(fml)
8643 return self
8644
8645 def assert_and_track(self, a, p):
8646 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8647
8648 If `p` is a string, it will be automatically converted into a Boolean constant.
8649
8650 >>> x = Int('x')
8651 >>> p3 = Bool('p3')
8652 >>> s = Optimize()
8653 >>> s.assert_and_track(x > 0, 'p1')
8654 >>> s.assert_and_track(x != 1, 'p2')
8655 >>> s.assert_and_track(x < 0, p3)
8656 >>> print(s.check())
8657 unsat
8658 >>> c = s.unsat_core()
8659 >>> len(c)
8660 2
8661 >>> Bool('p1') in c
8662 True
8663 >>> Bool('p2') in c
8664 False
8665 >>> p3 in c
8666 True
8667 """
8668 if isinstance(p, str):
8669 p = Bool(p, self.ctx)
8670 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8671 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8672 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8673
8674 def add_soft(self, arg, weight="1", id=None):
8675 """Add soft constraint with optional weight and optional identifier.
8676 If no weight is supplied, then the penalty for violating the soft constraint
8677 is 1.
8678 Soft constraints are grouped by identifiers. Soft constraints that are
8679 added without identifiers are grouped by default.
8680 """
8681 if _is_int(weight):
8682 weight = "%d" % weight
8683 elif isinstance(weight, float):
8684 weight = "%f" % weight
8685 if not isinstance(weight, str):
8686 raise Z3Exception("weight should be a string or an integer")
8687 if id is None:
8688 id = ""
8689 id = to_symbol(id, self.ctx)
8690
8691 def asoft(a):
8692 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8693 return OptimizeObjective(self, v, False)
8694 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8695 return [asoft(a) for a in arg]
8696 return asoft(arg)
8697
8698 def set_initial_value(self, var, value):
8699 """initialize the solver's state by setting the initial value of var to value
8700 """
8701 s = var.sort()
8702 value = s.cast(value)
8703 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8704
8705 def maximize(self, arg):
8706 """Add objective function to maximize."""
8707 return OptimizeObjective(
8708 self,
8709 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8710 is_max=True,
8711 )
8712
8713 def minimize(self, arg):
8714 """Add objective function to minimize."""
8715 return OptimizeObjective(
8716 self,
8717 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8718 is_max=False,
8719 )
8720
8721 def push(self):
8722 """create a backtracking point for added rules, facts and assertions"""
8723 Z3_optimize_push(self.ctx.ref(), self.optimize)
8724
8725 def pop(self):
8726 """restore to previously created backtracking point"""
8727 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8728
8729 def check(self, *assumptions):
8730 """Check consistency and produce optimal values."""
8731 assumptions = _get_args(assumptions)
8732 num = len(assumptions)
8733 _assumptions = (Ast * num)()
8734 for i in range(num):
8735 _assumptions[i] = assumptions[i].as_ast()
8736 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8737
8738 def reason_unknown(self):
8739 """Return a string that describes why the last `check()` returned `unknown`."""
8740 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8741
8742 def model(self):
8743 """Return a model for the last check()."""
8744 try:
8745 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8746 except Z3Exception:
8747 raise Z3Exception("model is not available")
8748
8749 def unsat_core(self):
8750 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8751
8752 def lower(self, obj):
8753 if not isinstance(obj, OptimizeObjective):
8754 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8755 return obj.lower()
8756
8757 def upper(self, obj):
8758 if not isinstance(obj, OptimizeObjective):
8759 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8760 return obj.upper()
8761
8762 def lower_values(self, obj):
8763 if not isinstance(obj, OptimizeObjective):
8764 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8765 return obj.lower_values()
8766
8767 def upper_values(self, obj):
8768 if not isinstance(obj, OptimizeObjective):
8769 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8770 return obj.upper_values()
8771
8772 def from_file(self, filename):
8773 """Parse assertions and objectives from a file"""
8774 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8775
8776 def from_string(self, s):
8777 """Parse assertions and objectives from a string"""
8778 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8779
8780 def assertions(self):
8781 """Return an AST vector containing all added constraints."""
8782 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8783
8784 def objectives(self):
8785 """returns set of objective functions"""
8786 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8787
8788 def __repr__(self):
8789 """Return a formatted string with all added rules and constraints."""
8790 return self.sexpr()
8791
8792 def sexpr(self):
8793 """Return a formatted string (in Lisp-like format) with all added constraints.
8794 We say the string is in s-expression format.
8795 """
8796 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8797
8798 def statistics(self):
8799 """Return statistics for the last check`.
8800 """
8801 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8802
8803 def translate(self, target):
8804 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8805
8806 >>> c1 = Context()
8807 >>> c2 = Context()
8808 >>> o1 = Optimize(ctx=c1)
8809 >>> o2 = o1.translate(c2)
8810 """
8811 if z3_debug():
8812 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8813 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8814 return Optimize(opt, target)
8815
8816 def set_on_model(self, on_model):
8817 """Register a callback that is invoked with every incremental improvement to
8818 objective values. The callback takes a model as argument.
8819 The life-time of the model is limited to the callback so the
8820 model has to be (deep) copied if it is to be used after the callback
8821 """
8822 id = len(_on_models) + 41
8823 mdl = Model(self.ctx)
8824 _on_models[id] = (on_model, mdl)
8825 self._on_models_id = id
8826 Z3_optimize_register_model_eh(
8827 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8828 )
8829
8830
8831#########################################
8832#
8833# ApplyResult
8834#
8835#########################################
8836class ApplyResult(Z3PPObject):
8837 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8838 It also contains model and proof converters.
8839 """
8840
8841 def __init__(self, result, ctx):
8842 self.result = result
8843 self.ctx = ctx
8844 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8845
8846 def __deepcopy__(self, memo={}):
8847 return ApplyResult(self.result, self.ctx)
8848
8849 def __del__(self):
8850 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8851 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8852
8853 def __len__(self):
8854 """Return the number of subgoals in `self`.
8855
8856 >>> a, b = Ints('a b')
8857 >>> g = Goal()
8858 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8859 >>> t = Tactic('split-clause')
8860 >>> r = t(g)
8861 >>> len(r)
8862 2
8863 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8864 >>> len(t(g))
8865 4
8866 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8867 >>> len(t(g))
8868 1
8869 """
8870 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8871
8872 def __getitem__(self, idx):
8873 """Return one of the subgoals stored in ApplyResult object `self`.
8874
8875 >>> a, b = Ints('a b')
8876 >>> g = Goal()
8877 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8878 >>> t = Tactic('split-clause')
8879 >>> r = t(g)
8880 >>> r[0]
8881 [a == 0, Or(b == 0, b == 1), a > b]
8882 >>> r[1]
8883 [a == 1, Or(b == 0, b == 1), a > b]
8884 """
8885 if idx < 0:
8886 idx += len(self)
8887 if idx < 0 or idx >= len(self):
8888 raise IndexError
8889 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8890
8891 def __repr__(self):
8892 return obj_to_string(self)
8893
8894 def sexpr(self):
8895 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8896 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8897
8898 def as_expr(self):
8899 """Return a Z3 expression consisting of all subgoals.
8900
8901 >>> x = Int('x')
8902 >>> g = Goal()
8903 >>> g.add(x > 1)
8904 >>> g.add(Or(x == 2, x == 3))
8905 >>> r = Tactic('simplify')(g)
8906 >>> r
8907 [[Not(x <= 1), Or(x == 2, x == 3)]]
8908 >>> r.as_expr()
8909 And(Not(x <= 1), Or(x == 2, x == 3))
8910 >>> r = Tactic('split-clause')(g)
8911 >>> r
8912 [[x > 1, x == 2], [x > 1, x == 3]]
8913 >>> r.as_expr()
8914 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8915 """
8916 sz = len(self)
8917 if sz == 0:
8918 return BoolVal(False, self.ctx)
8919 elif sz == 1:
8920 return self[0].as_expr()
8921 else:
8922 return Or([self[i].as_expr() for i in range(len(self))])
8923
8924#########################################
8925#
8926# Simplifiers
8927#
8928#########################################
8929
8930def num_simplifiers(ctx=None):
8931 """Return the number of simplifiers supported by the given context."""
8932 return Z3_get_num_simplifiers(_get_ctx(ctx).ref())
8933
8934
8935def simplifier_name(i, ctx=None):
8936 """Return the name of the i-th simplifier supported by the given context."""
8937 return Z3_get_simplifier_name(_get_ctx(ctx).ref(), i)
8938
8939
8940def simplifier_description(name, ctx=None):
8941 """Return the description of the simplifier identified by name."""
8942 return Z3_simplifier_get_descr(_get_ctx(ctx).ref(), name)
8943
8944
8945class Simplifier:
8946 """Simplifiers act as pre-processing utilities for solvers.
8947 Build a custom simplifier and add it to a solver"""
8948
8949 def __init__(self, simplifier, ctx=None):
8950 self.ctx = _get_ctx(ctx)
8951 self.simplifier = None
8952 if isinstance(simplifier, SimplifierObj):
8953 self.simplifier = simplifier
8954 elif isinstance(simplifier, list):
8955 simps = [Simplifier(s, ctx) for s in simplifier]
8956 self.simplifier = simps[0].simplifier
8957 for i in range(1, len(simps)):
8958 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
8959 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8960 return
8961 else:
8962 if z3_debug():
8963 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
8964 try:
8965 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
8966 except Z3Exception:
8967 raise Z3Exception("unknown simplifier '%s'" % simplifier)
8968 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8969
8970 def __deepcopy__(self, memo={}):
8971 return Simplifier(self.simplifier, self.ctx)
8972
8973 def __del__(self):
8974 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
8975 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
8976
8977 def using_params(self, *args, **keys):
8978 """Return a simplifier that uses the given configuration options"""
8979 p = args2params(args, keys, self.ctx)
8980 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
8981
8982 def add(self, solver):
8983 """Return a solver that applies the simplification pre-processing specified by the simplifier"""
8984 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
8985
8986 def help(self):
8987 """Display a string containing a description of the available options for the `self` simplifier."""
8988 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
8989
8990 def param_descrs(self):
8991 """Return the parameter description set."""
8992 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
8993
8994
8995#########################################
8996#
8997# Tactics
8998#
8999#########################################
9000
9001
9002class Tactic:
9003 """Tactics transform, solver and/or simplify sets of constraints (Goal).
9004 A Tactic can be converted into a Solver using the method solver().
9005
9006 Several combinators are available for creating new tactics using the built-in ones:
9007 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
9008 """
9009
9010 def __init__(self, tactic, ctx=None):
9011 self.ctx = _get_ctx(ctx)
9012 self.tactic = None
9013 if isinstance(tactic, TacticObj):
9014 self.tactic = tactic
9015 else:
9016 if z3_debug():
9017 _z3_assert(isinstance(tactic, str), "tactic name expected")
9018 try:
9019 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9020 except Z3Exception:
9021 raise Z3Exception("unknown tactic '%s'" % tactic)
9022 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9023
9024 def __deepcopy__(self, memo={}):
9025 return Tactic(self.tactic, self.ctx)
9026
9027 def __del__(self):
9028 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9029 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9030
9031 def solver(self, logFile=None):
9032 """Create a solver using the tactic `self`.
9033
9034 The solver supports the methods `push()` and `pop()`, but it
9035 will always solve each `check()` from scratch.
9036
9037 >>> t = Then('simplify', 'nlsat')
9038 >>> s = t.solver()
9039 >>> x = Real('x')
9040 >>> s.add(x**2 == 2, x > 0)
9041 >>> s.check()
9042 sat
9043 >>> s.model()
9044 [x = 1.4142135623?]
9045 """
9046 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9047
9048 def apply(self, goal, *arguments, **keywords):
9049 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9050
9051 >>> x, y = Ints('x y')
9052 >>> t = Tactic('solve-eqs')
9053 >>> t.apply(And(x == 0, y >= x + 1))
9054 [[y >= 1]]
9055 """
9056 if z3_debug():
9057 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9058 goal = _to_goal(goal)
9059 if len(arguments) > 0 or len(keywords) > 0:
9060 p = args2params(arguments, keywords, self.ctx)
9061 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9062 else:
9063 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9064
9065 def __call__(self, goal, *arguments, **keywords):
9066 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9067
9068 >>> x, y = Ints('x y')
9069 >>> t = Tactic('solve-eqs')
9070 >>> t(And(x == 0, y >= x + 1))
9071 [[y >= 1]]
9072 """
9073 return self.apply(goal, *arguments, **keywords)
9074
9075 def help(self):
9076 """Display a string containing a description of the available options for the `self` tactic."""
9077 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9078
9079 def param_descrs(self):
9080 """Return the parameter description set."""
9081 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9082
9083
9084def _to_goal(a):
9085 if isinstance(a, BoolRef):
9086 goal = Goal(ctx=a.ctx)
9087 goal.add(a)
9088 return goal
9089 else:
9090 return a
9091
9092
9093def _to_tactic(t, ctx=None):
9094 if isinstance(t, Tactic):
9095 return t
9096 else:
9097 return Tactic(t, ctx)
9098
9099
9100def _and_then(t1, t2, ctx=None):
9101 t1 = _to_tactic(t1, ctx)
9102 t2 = _to_tactic(t2, ctx)
9103 if z3_debug():
9104 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9105 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9106
9107
9108def _or_else(t1, t2, ctx=None):
9109 t1 = _to_tactic(t1, ctx)
9110 t2 = _to_tactic(t2, ctx)
9111 if z3_debug():
9112 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9113 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9114
9115
9116def AndThen(*ts, **ks):
9117 """Return a tactic that applies the tactics in `*ts` in sequence.
9118
9119 >>> x, y = Ints('x y')
9120 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9121 >>> t(And(x == 0, y > x + 1))
9122 [[Not(y <= 1)]]
9123 >>> t(And(x == 0, y > x + 1)).as_expr()
9124 Not(y <= 1)
9125 """
9126 if z3_debug():
9127 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9128 ctx = ks.get("ctx", None)
9129 num = len(ts)
9130 r = ts[0]
9131 for i in range(num - 1):
9132 r = _and_then(r, ts[i + 1], ctx)
9133 return r
9134
9135
9136def Then(*ts, **ks):
9137 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9138
9139 >>> x, y = Ints('x y')
9140 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9141 >>> t(And(x == 0, y > x + 1))
9142 [[Not(y <= 1)]]
9143 >>> t(And(x == 0, y > x + 1)).as_expr()
9144 Not(y <= 1)
9145 """
9146 return AndThen(*ts, **ks)
9147
9148
9149def OrElse(*ts, **ks):
9150 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9151
9152 >>> x = Int('x')
9153 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9154 >>> # Tactic split-clause fails if there is no clause in the given goal.
9155 >>> t(x == 0)
9156 [[x == 0]]
9157 >>> t(Or(x == 0, x == 1))
9158 [[x == 0], [x == 1]]
9159 """
9160 if z3_debug():
9161 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9162 ctx = ks.get("ctx", None)
9163 num = len(ts)
9164 r = ts[0]
9165 for i in range(num - 1):
9166 r = _or_else(r, ts[i + 1], ctx)
9167 return r
9168
9169
9170def ParOr(*ts, **ks):
9171 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9172
9173 >>> x = Int('x')
9174 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9175 >>> t(x + 1 == 2)
9176 [[x == 1]]
9177 """
9178 if z3_debug():
9179 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9180 ctx = _get_ctx(ks.get("ctx", None))
9181 ts = [_to_tactic(t, ctx) for t in ts]
9182 sz = len(ts)
9183 _args = (TacticObj * sz)()
9184 for i in range(sz):
9185 _args[i] = ts[i].tactic
9186 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9187
9188
9189def ParThen(t1, t2, ctx=None):
9190 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9191 The subgoals are processed in parallel.
9192
9193 >>> x, y = Ints('x y')
9194 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9195 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9196 [[x == 1, y == 2], [x == 2, y == 3]]
9197 """
9198 t1 = _to_tactic(t1, ctx)
9199 t2 = _to_tactic(t2, ctx)
9200 if z3_debug():
9201 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9202 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9203
9204
9205def ParAndThen(t1, t2, ctx=None):
9206 """Alias for ParThen(t1, t2, ctx)."""
9207 return ParThen(t1, t2, ctx)
9208
9209
9210def With(t, *args, **keys):
9211 """Return a tactic that applies tactic `t` using the given configuration options.
9212
9213 >>> x, y = Ints('x y')
9214 >>> t = With(Tactic('simplify'), som=True)
9215 >>> t((x + 1)*(y + 2) == 0)
9216 [[2*x + y + x*y == -2]]
9217 """
9218 ctx = keys.pop("ctx", None)
9219 t = _to_tactic(t, ctx)
9220 p = args2params(args, keys, t.ctx)
9221 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9222
9223
9224def WithParams(t, p):
9225 """Return a tactic that applies tactic `t` using the given configuration options.
9226
9227 >>> x, y = Ints('x y')
9228 >>> p = ParamsRef()
9229 >>> p.set("som", True)
9230 >>> t = WithParams(Tactic('simplify'), p)
9231 >>> t((x + 1)*(y + 2) == 0)
9232 [[2*x + y + x*y == -2]]
9233 """
9234 t = _to_tactic(t, None)
9235 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9236
9237
9238def Repeat(t, max=4294967295, ctx=None):
9239 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9240 or the maximum number of iterations `max` is reached.
9241
9242 >>> x, y = Ints('x y')
9243 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9244 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9245 >>> r = t(c)
9246 >>> for subgoal in r: print(subgoal)
9247 [x == 0, y == 0, x > y]
9248 [x == 0, y == 1, x > y]
9249 [x == 1, y == 0, x > y]
9250 [x == 1, y == 1, x > y]
9251 >>> t = Then(t, Tactic('propagate-values'))
9252 >>> t(c)
9253 [[x == 1, y == 0]]
9254 """
9255 t = _to_tactic(t, ctx)
9256 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9257
9258
9259def TryFor(t, ms, ctx=None):
9260 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9261
9262 If `t` does not terminate in `ms` milliseconds, then it fails.
9263 """
9264 t = _to_tactic(t, ctx)
9265 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9266
9267
9268def tactics(ctx=None):
9269 """Return a list of all available tactics in Z3.
9270
9271 >>> l = tactics()
9272 >>> l.count('simplify') == 1
9273 True
9274 """
9275 ctx = _get_ctx(ctx)
9276 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9277
9278
9279def tactic_description(name, ctx=None):
9280 """Return a short description for the tactic named `name`.
9281
9282 >>> d = tactic_description('simplify')
9283 """
9284 ctx = _get_ctx(ctx)
9285 return Z3_tactic_get_descr(ctx.ref(), name)
9286
9287
9288def describe_tactics():
9289 """Display a (tabular) description of all available tactics in Z3."""
9290 if in_html_mode():
9291 even = True
9292 print('<table border="1" cellpadding="2" cellspacing="0">')
9293 for t in tactics():
9294 if even:
9295 print('<tr style="background-color:#CFCFCF">')
9296 even = False
9297 else:
9298 print("<tr>")
9299 even = True
9300 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9301 print("</table>")
9302 else:
9303 for t in tactics():
9304 print("%s : %s" % (t, tactic_description(t)))
9305
9306
9307class Probe:
9308 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9309 to decide which solver and/or preprocessing step will be used.
9310 """
9311
9312 def __init__(self, probe, ctx=None):
9313 self.ctx = _get_ctx(ctx)
9314 self.probe = None
9315 if isinstance(probe, ProbeObj):
9316 self.probe = probe
9317 elif isinstance(probe, float):
9318 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9319 elif _is_int(probe):
9320 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9321 elif isinstance(probe, bool):
9322 if probe:
9323 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9324 else:
9325 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9326 else:
9327 if z3_debug():
9328 _z3_assert(isinstance(probe, str), "probe name expected")
9329 try:
9330 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9331 except Z3Exception:
9332 raise Z3Exception("unknown probe '%s'" % probe)
9333 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9334
9335 def __deepcopy__(self, memo={}):
9336 return Probe(self.probe, self.ctx)
9337
9338 def __del__(self):
9339 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9340 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9341
9342 def __lt__(self, other):
9343 """Return a probe that evaluates to "true" when the value returned by `self`
9344 is less than the value returned by `other`.
9345
9346 >>> p = Probe('size') < 10
9347 >>> x = Int('x')
9348 >>> g = Goal()
9349 >>> g.add(x > 0)
9350 >>> g.add(x < 10)
9351 >>> p(g)
9352 1.0
9353 """
9354 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9355
9356 def __gt__(self, other):
9357 """Return a probe that evaluates to "true" when the value returned by `self`
9358 is greater than the value returned by `other`.
9359
9360 >>> p = Probe('size') > 10
9361 >>> x = Int('x')
9362 >>> g = Goal()
9363 >>> g.add(x > 0)
9364 >>> g.add(x < 10)
9365 >>> p(g)
9366 0.0
9367 """
9368 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9369
9370 def __le__(self, other):
9371 """Return a probe that evaluates to "true" when the value returned by `self`
9372 is less than or equal to the value returned by `other`.
9373
9374 >>> p = Probe('size') <= 2
9375 >>> x = Int('x')
9376 >>> g = Goal()
9377 >>> g.add(x > 0)
9378 >>> g.add(x < 10)
9379 >>> p(g)
9380 1.0
9381 """
9382 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9383
9384 def __ge__(self, other):
9385 """Return a probe that evaluates to "true" when the value returned by `self`
9386 is greater than or equal to the value returned by `other`.
9387
9388 >>> p = Probe('size') >= 2
9389 >>> x = Int('x')
9390 >>> g = Goal()
9391 >>> g.add(x > 0)
9392 >>> g.add(x < 10)
9393 >>> p(g)
9394 1.0
9395 """
9396 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9397
9398 def __eq__(self, other):
9399 """Return a probe that evaluates to "true" when the value returned by `self`
9400 is equal to the value returned by `other`.
9401
9402 >>> p = Probe('size') == 2
9403 >>> x = Int('x')
9404 >>> g = Goal()
9405 >>> g.add(x > 0)
9406 >>> g.add(x < 10)
9407 >>> p(g)
9408 1.0
9409 """
9410 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9411
9412 def __ne__(self, other):
9413 """Return a probe that evaluates to "true" when the value returned by `self`
9414 is not equal to the value returned by `other`.
9415
9416 >>> p = Probe('size') != 2
9417 >>> x = Int('x')
9418 >>> g = Goal()
9419 >>> g.add(x > 0)
9420 >>> g.add(x < 10)
9421 >>> p(g)
9422 0.0
9423 """
9424 p = self.__eq__(other)
9425 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9426
9427 def __call__(self, goal):
9428 """Evaluate the probe `self` in the given goal.
9429
9430 >>> p = Probe('size')
9431 >>> x = Int('x')
9432 >>> g = Goal()
9433 >>> g.add(x > 0)
9434 >>> g.add(x < 10)
9435 >>> p(g)
9436 2.0
9437 >>> g.add(x < 20)
9438 >>> p(g)
9439 3.0
9440 >>> p = Probe('num-consts')
9441 >>> p(g)
9442 1.0
9443 >>> p = Probe('is-propositional')
9444 >>> p(g)
9445 0.0
9446 >>> p = Probe('is-qflia')
9447 >>> p(g)
9448 1.0
9449 """
9450 if z3_debug():
9451 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9452 goal = _to_goal(goal)
9453 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9454
9455
9456def is_probe(p):
9457 """Return `True` if `p` is a Z3 probe.
9458
9459 >>> is_probe(Int('x'))
9460 False
9461 >>> is_probe(Probe('memory'))
9462 True
9463 """
9464 return isinstance(p, Probe)
9465
9466
9467def _to_probe(p, ctx=None):
9468 if is_probe(p):
9469 return p
9470 else:
9471 return Probe(p, ctx)
9472
9473
9474def probes(ctx=None):
9475 """Return a list of all available probes in Z3.
9476
9477 >>> l = probes()
9478 >>> l.count('memory') == 1
9479 True
9480 """
9481 ctx = _get_ctx(ctx)
9482 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9483
9484
9485def probe_description(name, ctx=None):
9486 """Return a short description for the probe named `name`.
9487
9488 >>> d = probe_description('memory')
9489 """
9490 ctx = _get_ctx(ctx)
9491 return Z3_probe_get_descr(ctx.ref(), name)
9492
9493
9494def describe_probes():
9495 """Display a (tabular) description of all available probes in Z3."""
9496 if in_html_mode():
9497 even = True
9498 print('<table border="1" cellpadding="2" cellspacing="0">')
9499 for p in probes():
9500 if even:
9501 print('<tr style="background-color:#CFCFCF">')
9502 even = False
9503 else:
9504 print("<tr>")
9505 even = True
9506 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9507 print("</table>")
9508 else:
9509 for p in probes():
9510 print("%s : %s" % (p, probe_description(p)))
9511
9512
9513def _probe_nary(f, args, ctx):
9514 if z3_debug():
9515 _z3_assert(len(args) > 0, "At least one argument expected")
9516 num = len(args)
9517 r = _to_probe(args[0], ctx)
9518 for i in range(num - 1):
9519 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9520 return r
9521
9522
9523def _probe_and(args, ctx):
9524 return _probe_nary(Z3_probe_and, args, ctx)
9525
9526
9527def _probe_or(args, ctx):
9528 return _probe_nary(Z3_probe_or, args, ctx)
9529
9530
9531def FailIf(p, ctx=None):
9532 """Return a tactic that fails if the probe `p` evaluates to true.
9533 Otherwise, it returns the input goal unmodified.
9534
9535 In the following example, the tactic applies 'simplify' if and only if there are
9536 more than 2 constraints in the goal.
9537
9538 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9539 >>> x, y = Ints('x y')
9540 >>> g = Goal()
9541 >>> g.add(x > 0)
9542 >>> g.add(y > 0)
9543 >>> t(g)
9544 [[x > 0, y > 0]]
9545 >>> g.add(x == y + 1)
9546 >>> t(g)
9547 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9548 """
9549 p = _to_probe(p, ctx)
9550 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9551
9552
9553def When(p, t, ctx=None):
9554 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9555 Otherwise, it returns the input goal unmodified.
9556
9557 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9558 >>> x, y = Ints('x y')
9559 >>> g = Goal()
9560 >>> g.add(x > 0)
9561 >>> g.add(y > 0)
9562 >>> t(g)
9563 [[x > 0, y > 0]]
9564 >>> g.add(x == y + 1)
9565 >>> t(g)
9566 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9567 """
9568 p = _to_probe(p, ctx)
9569 t = _to_tactic(t, ctx)
9570 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9571
9572
9573def Cond(p, t1, t2, ctx=None):
9574 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9575
9576 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9577 """
9578 p = _to_probe(p, ctx)
9579 t1 = _to_tactic(t1, ctx)
9580 t2 = _to_tactic(t2, ctx)
9581 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9582
9583#########################################
9584#
9585# Utils
9586#
9587#########################################
9588
9589
9590def simplify(a, *arguments, **keywords):
9591 """Simplify the expression `a` using the given options.
9592
9593 This function has many options. Use `help_simplify` to obtain the complete list.
9594
9595 >>> x = Int('x')
9596 >>> y = Int('y')
9597 >>> simplify(x + 1 + y + x + 1)
9598 2 + 2*x + y
9599 >>> simplify((x + 1)*(y + 1), som=True)
9600 1 + x + y + x*y
9601 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9602 And(Not(x == y), Not(x == 1), Not(y == 1))
9603 >>> simplify(And(x == 0, y == 1), elim_and=True)
9604 Not(Or(Not(x == 0), Not(y == 1)))
9605 """
9606 if z3_debug():
9607 _z3_assert(is_expr(a), "Z3 expression expected")
9608 if len(arguments) > 0 or len(keywords) > 0:
9609 p = args2params(arguments, keywords, a.ctx)
9610 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9611 else:
9612 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9613
9614
9615def help_simplify():
9616 """Return a string describing all options available for Z3 `simplify` procedure."""
9617 print(Z3_simplify_get_help(main_ctx().ref()))
9618
9619
9620def simplify_param_descrs():
9621 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9622 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9623
9624
9625def substitute(t, *m):
9626 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9627 Every occurrence in t of from is replaced with to.
9628
9629 >>> x = Int('x')
9630 >>> y = Int('y')
9631 >>> substitute(x + 1, (x, y + 1))
9632 y + 1 + 1
9633 >>> f = Function('f', IntSort(), IntSort())
9634 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9635 1 + 1
9636 """
9637 if isinstance(m, tuple):
9638 m1 = _get_args(m)
9639 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9640 m = m1
9641 if z3_debug():
9642 _z3_assert(is_expr(t), "Z3 expression expected")
9643 _z3_assert(
9644 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9645 "Z3 invalid substitution, expression pairs expected.")
9646 _z3_assert(
9647 all([p[0].sort().eq(p[1].sort()) for p in m]),
9648 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9649 num = len(m)
9650 _from = (Ast * num)()
9651 _to = (Ast * num)()
9652 for i in range(num):
9653 _from[i] = m[i][0].as_ast()
9654 _to[i] = m[i][1].as_ast()
9655 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9656
9657
9658def substitute_vars(t, *m):
9659 """Substitute the free variables in t with the expression in m.
9660
9661 >>> v0 = Var(0, IntSort())
9662 >>> v1 = Var(1, IntSort())
9663 >>> x = Int('x')
9664 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9665 >>> # replace v0 with x+1 and v1 with x
9666 >>> substitute_vars(f(v0, v1), x + 1, x)
9667 f(x + 1, x)
9668 """
9669 if z3_debug():
9670 _z3_assert(is_expr(t), "Z3 expression expected")
9671 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9672 num = len(m)
9673 _to = (Ast * num)()
9674 for i in range(num):
9675 _to[i] = m[i].as_ast()
9676 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9677
9678def substitute_funs(t, *m):
9679 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9680 Every occurrence in to of the function from is replaced with the expression to.
9681 The expression to can have free variables, that refer to the arguments of from.
9682 For examples, see
9683 """
9684 if isinstance(m, tuple):
9685 m1 = _get_args(m)
9686 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9687 m = m1
9688 if z3_debug():
9689 _z3_assert(is_expr(t), "Z3 expression expected")
9690 _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.")
9691 num = len(m)
9692 _from = (FuncDecl * num)()
9693 _to = (Ast * num)()
9694 for i in range(num):
9695 _from[i] = m[i][0].as_func_decl()
9696 _to[i] = m[i][1].as_ast()
9697 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9698
9699
9700def Sum(*args):
9701 """Create the sum of the Z3 expressions.
9702
9703 >>> a, b, c = Ints('a b c')
9704 >>> Sum(a, b, c)
9705 a + b + c
9706 >>> Sum([a, b, c])
9707 a + b + c
9708 >>> A = IntVector('a', 5)
9709 >>> Sum(A)
9710 a__0 + a__1 + a__2 + a__3 + a__4
9711 """
9712 args = _get_args(args)
9713 if len(args) == 0:
9714 return 0
9715 ctx = _ctx_from_ast_arg_list(args)
9716 if ctx is None:
9717 return _reduce(lambda a, b: a + b, args, 0)
9718 args = _coerce_expr_list(args, ctx)
9719 if is_bv(args[0]):
9720 return _reduce(lambda a, b: a + b, args, 0)
9721 else:
9722 _args, sz = _to_ast_array(args)
9723 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9724
9725
9726def Product(*args):
9727 """Create the product of the Z3 expressions.
9728
9729 >>> a, b, c = Ints('a b c')
9730 >>> Product(a, b, c)
9731 a*b*c
9732 >>> Product([a, b, c])
9733 a*b*c
9734 >>> A = IntVector('a', 5)
9735 >>> Product(A)
9736 a__0*a__1*a__2*a__3*a__4
9737 """
9738 args = _get_args(args)
9739 if len(args) == 0:
9740 return 1
9741 ctx = _ctx_from_ast_arg_list(args)
9742 if ctx is None:
9743 return _reduce(lambda a, b: a * b, args, 1)
9744 args = _coerce_expr_list(args, ctx)
9745 if is_bv(args[0]):
9746 return _reduce(lambda a, b: a * b, args, 1)
9747 else:
9748 _args, sz = _to_ast_array(args)
9749 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9750
9751def Abs(arg):
9752 """Create the absolute value of an arithmetic expression"""
9753 return If(arg > 0, arg, -arg)
9754
9755
9756def AtMost(*args):
9757 """Create an at-most Pseudo-Boolean k constraint.
9758
9759 >>> a, b, c = Bools('a b c')
9760 >>> f = AtMost(a, b, c, 2)
9761 """
9762 args = _get_args(args)
9763 if z3_debug():
9764 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9765 ctx = _ctx_from_ast_arg_list(args)
9766 if z3_debug():
9767 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9768 args1 = _coerce_expr_list(args[:-1], ctx)
9769 k = args[-1]
9770 _args, sz = _to_ast_array(args1)
9771 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9772
9773
9774def AtLeast(*args):
9775 """Create an at-least Pseudo-Boolean k constraint.
9776
9777 >>> a, b, c = Bools('a b c')
9778 >>> f = AtLeast(a, b, c, 2)
9779 """
9780 args = _get_args(args)
9781 if z3_debug():
9782 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9783 ctx = _ctx_from_ast_arg_list(args)
9784 if z3_debug():
9785 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9786 args1 = _coerce_expr_list(args[:-1], ctx)
9787 k = args[-1]
9788 _args, sz = _to_ast_array(args1)
9789 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9790
9791
9792def _reorder_pb_arg(arg):
9793 a, b = arg
9794 if not _is_int(b) and _is_int(a):
9795 return b, a
9796 return arg
9797
9798
9799def _pb_args_coeffs(args, default_ctx=None):
9800 args = _get_args_ast_list(args)
9801 if len(args) == 0:
9802 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9803 args = [_reorder_pb_arg(arg) for arg in args]
9804 args, coeffs = zip(*args)
9805 if z3_debug():
9806 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9807 ctx = _ctx_from_ast_arg_list(args)
9808 if z3_debug():
9809 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9810 args = _coerce_expr_list(args, ctx)
9811 _args, sz = _to_ast_array(args)
9812 _coeffs = (ctypes.c_int * len(coeffs))()
9813 for i in range(len(coeffs)):
9814 _z3_check_cint_overflow(coeffs[i], "coefficient")
9815 _coeffs[i] = coeffs[i]
9816 return ctx, sz, _args, _coeffs, args
9817
9818
9819def PbLe(args, k):
9820 """Create a Pseudo-Boolean inequality k constraint.
9821
9822 >>> a, b, c = Bools('a b c')
9823 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9824 """
9825 _z3_check_cint_overflow(k, "k")
9826 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9827 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9828
9829
9830def PbGe(args, k):
9831 """Create a Pseudo-Boolean inequality k constraint.
9832
9833 >>> a, b, c = Bools('a b c')
9834 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9835 """
9836 _z3_check_cint_overflow(k, "k")
9837 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9838 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9839
9840
9841def PbEq(args, k, ctx=None):
9842 """Create a Pseudo-Boolean equality k constraint.
9843
9844 >>> a, b, c = Bools('a b c')
9845 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9846 """
9847 _z3_check_cint_overflow(k, "k")
9848 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9849 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9850
9851
9852def solve(*args, **keywords):
9853 """Solve the constraints `*args`.
9854
9855 This is a simple function for creating demonstrations. It creates a solver,
9856 configure it using the options in `keywords`, adds the constraints
9857 in `args`, and invokes check.
9858
9859 >>> a = Int('a')
9860 >>> solve(a > 0, a < 2)
9861 [a = 1]
9862 """
9863 show = keywords.pop("show", False)
9864 s = Solver()
9865 s.set(**keywords)
9866 s.add(*args)
9867 if show:
9868 print(s)
9869 r = s.check()
9870 if r == unsat:
9871 print("no solution")
9872 elif r == unknown:
9873 print("failed to solve")
9874 try:
9875 print(s.model())
9876 except Z3Exception:
9877 return
9878 else:
9879 print(s.model())
9880
9881
9882def solve_using(s, *args, **keywords):
9883 """Solve the constraints `*args` using solver `s`.
9884
9885 This is a simple function for creating demonstrations. It is similar to `solve`,
9886 but it uses the given solver `s`.
9887 It configures solver `s` using the options in `keywords`, adds the constraints
9888 in `args`, and invokes check.
9889 """
9890 show = keywords.pop("show", False)
9891 if z3_debug():
9892 _z3_assert(isinstance(s, Solver), "Solver object expected")
9893 s.set(**keywords)
9894 s.add(*args)
9895 if show:
9896 print("Problem:")
9897 print(s)
9898 r = s.check()
9899 if r == unsat:
9900 print("no solution")
9901 elif r == unknown:
9902 print("failed to solve")
9903 try:
9904 print(s.model())
9905 except Z3Exception:
9906 return
9907 else:
9908 if show:
9909 print("Solution:")
9910 print(s.model())
9911
9912
9913def prove(claim, show=False, **keywords):
9914 """Try to prove the given claim.
9915
9916 This is a simple function for creating demonstrations. It tries to prove
9917 `claim` by showing the negation is unsatisfiable.
9918
9919 >>> p, q = Bools('p q')
9920 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9921 proved
9922 """
9923 if z3_debug():
9924 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9925 s = Solver()
9926 s.set(**keywords)
9927 s.add(Not(claim))
9928 if show:
9929 print(s)
9930 r = s.check()
9931 if r == unsat:
9932 print("proved")
9933 elif r == unknown:
9934 print("failed to prove")
9935 print(s.model())
9936 else:
9937 print("counterexample")
9938 print(s.model())
9939
9940
9941def _solve_html(*args, **keywords):
9942 """Version of function `solve` that renders HTML output."""
9943 show = keywords.pop("show", False)
9944 s = Solver()
9945 s.set(**keywords)
9946 s.add(*args)
9947 if show:
9948 print("<b>Problem:</b>")
9949 print(s)
9950 r = s.check()
9951 if r == unsat:
9952 print("<b>no solution</b>")
9953 elif r == unknown:
9954 print("<b>failed to solve</b>")
9955 try:
9956 print(s.model())
9957 except Z3Exception:
9958 return
9959 else:
9960 if show:
9961 print("<b>Solution:</b>")
9962 print(s.model())
9963
9964
9965def _solve_using_html(s, *args, **keywords):
9966 """Version of function `solve_using` that renders HTML."""
9967 show = keywords.pop("show", False)
9968 if z3_debug():
9969 _z3_assert(isinstance(s, Solver), "Solver object expected")
9970 s.set(**keywords)
9971 s.add(*args)
9972 if show:
9973 print("<b>Problem:</b>")
9974 print(s)
9975 r = s.check()
9976 if r == unsat:
9977 print("<b>no solution</b>")
9978 elif r == unknown:
9979 print("<b>failed to solve</b>")
9980 try:
9981 print(s.model())
9982 except Z3Exception:
9983 return
9984 else:
9985 if show:
9986 print("<b>Solution:</b>")
9987 print(s.model())
9988
9989
9990def _prove_html(claim, show=False, **keywords):
9991 """Version of function `prove` that renders HTML."""
9992 if z3_debug():
9993 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9994 s = Solver()
9995 s.set(**keywords)
9996 s.add(Not(claim))
9997 if show:
9998 print(s)
9999 r = s.check()
10000 if r == unsat:
10001 print("<b>proved</b>")
10002 elif r == unknown:
10003 print("<b>failed to prove</b>")
10004 print(s.model())
10005 else:
10006 print("<b>counterexample</b>")
10007 print(s.model())
10008
10009
10010def _dict2sarray(sorts, ctx):
10011 sz = len(sorts)
10012 _names = (Symbol * sz)()
10013 _sorts = (Sort * sz)()
10014 i = 0
10015 for k in sorts:
10016 v = sorts[k]
10017 if z3_debug():
10018 _z3_assert(isinstance(k, str), "String expected")
10019 _z3_assert(is_sort(v), "Z3 sort expected")
10020 _names[i] = to_symbol(k, ctx)
10021 _sorts[i] = v.ast
10022 i = i + 1
10023 return sz, _names, _sorts
10024
10025
10026def _dict2darray(decls, ctx):
10027 sz = len(decls)
10028 _names = (Symbol * sz)()
10029 _decls = (FuncDecl * sz)()
10030 i = 0
10031 for k in decls:
10032 v = decls[k]
10033 if z3_debug():
10034 _z3_assert(isinstance(k, str), "String expected")
10035 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10036 _names[i] = to_symbol(k, ctx)
10037 if is_const(v):
10038 _decls[i] = v.decl().ast
10039 else:
10040 _decls[i] = v.ast
10041 i = i + 1
10042 return sz, _names, _decls
10043
10044class ParserContext:
10045 def __init__(self, ctx= None):
10046 self.ctx = _get_ctx(ctx)
10047 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10048 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10049
10050 def __del__(self):
10051 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10052 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10053 self.pctx = None
10054
10055 def add_sort(self, sort):
10056 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10057
10058 def add_decl(self, decl):
10059 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10060
10061 def from_string(self, s):
10062 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10063
10064def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10065 """Parse a string in SMT 2.0 format using the given sorts and decls.
10066
10067 The arguments sorts and decls are Python dictionaries used to initialize
10068 the symbol table used for the SMT 2.0 parser.
10069
10070 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10071 [x > 0, x < 10]
10072 >>> x, y = Ints('x y')
10073 >>> f = Function('f', IntSort(), IntSort())
10074 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10075 [x + f(y) > 0]
10076 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10077 [a > 0]
10078 """
10079 ctx = _get_ctx(ctx)
10080 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10081 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10082 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10083
10084
10085def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10086 """Parse a file in SMT 2.0 format using the given sorts and decls.
10087
10088 This function is similar to parse_smt2_string().
10089 """
10090 ctx = _get_ctx(ctx)
10091 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10092 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10093 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10094
10095
10096#########################################
10097#
10098# Floating-Point Arithmetic
10099#
10100#########################################
10101
10102
10103# Global default rounding mode
10104_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10105_dflt_fpsort_ebits = 11
10106_dflt_fpsort_sbits = 53
10107
10108
10109def get_default_rounding_mode(ctx=None):
10110 """Retrieves the global default rounding mode."""
10111 global _dflt_rounding_mode
10112 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10113 return RTZ(ctx)
10114 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10115 return RTN(ctx)
10116 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10117 return RTP(ctx)
10118 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10119 return RNE(ctx)
10120 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10121 return RNA(ctx)
10122
10123
10124_ROUNDING_MODES = frozenset({
10125 Z3_OP_FPA_RM_TOWARD_ZERO,
10126 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10127 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10128 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10129 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10130})
10131
10132
10133def set_default_rounding_mode(rm, ctx=None):
10134 global _dflt_rounding_mode
10135 if is_fprm_value(rm):
10136 _dflt_rounding_mode = rm.kind()
10137 else:
10138 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10139 _dflt_rounding_mode = rm
10140
10141
10142def get_default_fp_sort(ctx=None):
10143 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10144
10145
10146def set_default_fp_sort(ebits, sbits, ctx=None):
10147 global _dflt_fpsort_ebits
10148 global _dflt_fpsort_sbits
10149 _dflt_fpsort_ebits = ebits
10150 _dflt_fpsort_sbits = sbits
10151
10152
10153def _dflt_rm(ctx=None):
10154 return get_default_rounding_mode(ctx)
10155
10156
10157def _dflt_fps(ctx=None):
10158 return get_default_fp_sort(ctx)
10159
10160
10161def _coerce_fp_expr_list(alist, ctx):
10162 first_fp_sort = None
10163 for a in alist:
10164 if is_fp(a):
10165 if first_fp_sort is None:
10166 first_fp_sort = a.sort()
10167 elif first_fp_sort == a.sort():
10168 pass # OK, same as before
10169 else:
10170 # we saw at least 2 different float sorts; something will
10171 # throw a sort mismatch later, for now assume None.
10172 first_fp_sort = None
10173 break
10174
10175 r = []
10176 for i in range(len(alist)):
10177 a = alist[i]
10178 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10179 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10180 r.append(FPVal(a, None, first_fp_sort, ctx))
10181 else:
10182 r.append(a)
10183 return _coerce_expr_list(r, ctx)
10184
10185
10186# FP Sorts
10187
10188class FPSortRef(SortRef):
10189 """Floating-point sort."""
10190
10191 def ebits(self):
10192 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10193 >>> b = FPSort(8, 24)
10194 >>> b.ebits()
10195 8
10196 """
10197 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10198
10199 def sbits(self):
10200 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10201 >>> b = FPSort(8, 24)
10202 >>> b.sbits()
10203 24
10204 """
10205 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10206
10207 def cast(self, val):
10208 """Try to cast `val` as a floating-point expression.
10209 >>> b = FPSort(8, 24)
10210 >>> b.cast(1.0)
10211 1
10212 >>> b.cast(1.0).sexpr()
10213 '(fp #b0 #x7f #b00000000000000000000000)'
10214 """
10215 if is_expr(val):
10216 if z3_debug():
10217 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10218 return val
10219 else:
10220 return FPVal(val, None, self, self.ctx)
10221
10222
10223def Float16(ctx=None):
10224 """Floating-point 16-bit (half) sort."""
10225 ctx = _get_ctx(ctx)
10226 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10227
10228
10229def FloatHalf(ctx=None):
10230 """Floating-point 16-bit (half) sort."""
10231 ctx = _get_ctx(ctx)
10232 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10233
10234
10235def Float32(ctx=None):
10236 """Floating-point 32-bit (single) sort."""
10237 ctx = _get_ctx(ctx)
10238 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10239
10240
10241def FloatSingle(ctx=None):
10242 """Floating-point 32-bit (single) sort."""
10243 ctx = _get_ctx(ctx)
10244 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10245
10246
10247def Float64(ctx=None):
10248 """Floating-point 64-bit (double) sort."""
10249 ctx = _get_ctx(ctx)
10250 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10251
10252
10253def FloatDouble(ctx=None):
10254 """Floating-point 64-bit (double) sort."""
10255 ctx = _get_ctx(ctx)
10256 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10257
10258
10259def Float128(ctx=None):
10260 """Floating-point 128-bit (quadruple) sort."""
10261 ctx = _get_ctx(ctx)
10262 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10263
10264
10265def FloatQuadruple(ctx=None):
10266 """Floating-point 128-bit (quadruple) sort."""
10267 ctx = _get_ctx(ctx)
10268 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10269
10270
10271class FPRMSortRef(SortRef):
10272 """"Floating-point rounding mode sort."""
10273
10274
10275def is_fp_sort(s):
10276 """Return True if `s` is a Z3 floating-point sort.
10277
10278 >>> is_fp_sort(FPSort(8, 24))
10279 True
10280 >>> is_fp_sort(IntSort())
10281 False
10282 """
10283 return isinstance(s, FPSortRef)
10284
10285
10286def is_fprm_sort(s):
10287 """Return True if `s` is a Z3 floating-point rounding mode sort.
10288
10289 >>> is_fprm_sort(FPSort(8, 24))
10290 False
10291 >>> is_fprm_sort(RNE().sort())
10292 True
10293 """
10294 return isinstance(s, FPRMSortRef)
10295
10296# FP Expressions
10297
10298
10299class FPRef(ExprRef):
10300 """Floating-point expressions."""
10301
10302 def sort(self):
10303 """Return the sort of the floating-point expression `self`.
10304
10305 >>> x = FP('1.0', FPSort(8, 24))
10306 >>> x.sort()
10307 FPSort(8, 24)
10308 >>> x.sort() == FPSort(8, 24)
10309 True
10310 """
10311 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10312
10313 def ebits(self):
10314 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10315 >>> b = FPSort(8, 24)
10316 >>> b.ebits()
10317 8
10318 """
10319 return self.sort().ebits()
10320
10321 def sbits(self):
10322 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10323 >>> b = FPSort(8, 24)
10324 >>> b.sbits()
10325 24
10326 """
10327 return self.sort().sbits()
10328
10329 def as_string(self):
10330 """Return a Z3 floating point expression as a Python string."""
10331 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10332
10333 def __le__(self, other):
10334 return fpLEQ(self, other, self.ctx)
10335
10336 def __lt__(self, other):
10337 return fpLT(self, other, self.ctx)
10338
10339 def __ge__(self, other):
10340 return fpGEQ(self, other, self.ctx)
10341
10342 def __gt__(self, other):
10343 return fpGT(self, other, self.ctx)
10344
10345 def __add__(self, other):
10346 """Create the Z3 expression `self + other`.
10347
10348 >>> x = FP('x', FPSort(8, 24))
10349 >>> y = FP('y', FPSort(8, 24))
10350 >>> x + y
10351 x + y
10352 >>> (x + y).sort()
10353 FPSort(8, 24)
10354 """
10355 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10356 return fpAdd(_dflt_rm(), a, b, self.ctx)
10357
10358 def __radd__(self, other):
10359 """Create the Z3 expression `other + self`.
10360
10361 >>> x = FP('x', FPSort(8, 24))
10362 >>> 10 + x
10363 1.25*(2**3) + x
10364 """
10365 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10366 return fpAdd(_dflt_rm(), a, b, self.ctx)
10367
10368 def __sub__(self, other):
10369 """Create the Z3 expression `self - other`.
10370
10371 >>> x = FP('x', FPSort(8, 24))
10372 >>> y = FP('y', FPSort(8, 24))
10373 >>> x - y
10374 x - y
10375 >>> (x - y).sort()
10376 FPSort(8, 24)
10377 """
10378 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10379 return fpSub(_dflt_rm(), a, b, self.ctx)
10380
10381 def __rsub__(self, other):
10382 """Create the Z3 expression `other - self`.
10383
10384 >>> x = FP('x', FPSort(8, 24))
10385 >>> 10 - x
10386 1.25*(2**3) - x
10387 """
10388 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10389 return fpSub(_dflt_rm(), a, b, self.ctx)
10390
10391 def __mul__(self, other):
10392 """Create the Z3 expression `self * other`.
10393
10394 >>> x = FP('x', FPSort(8, 24))
10395 >>> y = FP('y', FPSort(8, 24))
10396 >>> x * y
10397 x * y
10398 >>> (x * y).sort()
10399 FPSort(8, 24)
10400 >>> 10 * y
10401 1.25*(2**3) * y
10402 """
10403 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10404 return fpMul(_dflt_rm(), a, b, self.ctx)
10405
10406 def __rmul__(self, other):
10407 """Create the Z3 expression `other * self`.
10408
10409 >>> x = FP('x', FPSort(8, 24))
10410 >>> y = FP('y', FPSort(8, 24))
10411 >>> x * y
10412 x * y
10413 >>> x * 10
10414 x * 1.25*(2**3)
10415 """
10416 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10417 return fpMul(_dflt_rm(), a, b, self.ctx)
10418
10419 def __pos__(self):
10420 """Create the Z3 expression `+self`."""
10421 return self
10422
10423 def __neg__(self):
10424 """Create the Z3 expression `-self`.
10425
10426 >>> x = FP('x', Float32())
10427 >>> -x
10428 -x
10429 """
10430 return fpNeg(self)
10431
10432 def __div__(self, other):
10433 """Create the Z3 expression `self / other`.
10434
10435 >>> x = FP('x', FPSort(8, 24))
10436 >>> y = FP('y', FPSort(8, 24))
10437 >>> x / y
10438 x / y
10439 >>> (x / y).sort()
10440 FPSort(8, 24)
10441 >>> 10 / y
10442 1.25*(2**3) / y
10443 """
10444 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10445 return fpDiv(_dflt_rm(), a, b, self.ctx)
10446
10447 def __rdiv__(self, other):
10448 """Create the Z3 expression `other / self`.
10449
10450 >>> x = FP('x', FPSort(8, 24))
10451 >>> y = FP('y', FPSort(8, 24))
10452 >>> x / y
10453 x / y
10454 >>> x / 10
10455 x / 1.25*(2**3)
10456 """
10457 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10458 return fpDiv(_dflt_rm(), a, b, self.ctx)
10459
10460 def __truediv__(self, other):
10461 """Create the Z3 expression division `self / other`."""
10462 return self.__div__(other)
10463
10464 def __rtruediv__(self, other):
10465 """Create the Z3 expression division `other / self`."""
10466 return self.__rdiv__(other)
10467
10468 def __mod__(self, other):
10469 """Create the Z3 expression mod `self % other`."""
10470 return fpRem(self, other)
10471
10472 def __rmod__(self, other):
10473 """Create the Z3 expression mod `other % self`."""
10474 return fpRem(other, self)
10475
10476
10477class FPRMRef(ExprRef):
10478 """Floating-point rounding mode expressions"""
10479
10480 def as_string(self):
10481 """Return a Z3 floating point expression as a Python string."""
10482 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10483
10484
10485def RoundNearestTiesToEven(ctx=None):
10486 ctx = _get_ctx(ctx)
10487 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10488
10489
10490def RNE(ctx=None):
10491 ctx = _get_ctx(ctx)
10492 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10493
10494
10495def RoundNearestTiesToAway(ctx=None):
10496 ctx = _get_ctx(ctx)
10497 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10498
10499
10500def RNA(ctx=None):
10501 ctx = _get_ctx(ctx)
10502 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10503
10504
10505def RoundTowardPositive(ctx=None):
10506 ctx = _get_ctx(ctx)
10507 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10508
10509
10510def RTP(ctx=None):
10511 ctx = _get_ctx(ctx)
10512 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10513
10514
10515def RoundTowardNegative(ctx=None):
10516 ctx = _get_ctx(ctx)
10517 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10518
10519
10520def RTN(ctx=None):
10521 ctx = _get_ctx(ctx)
10522 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10523
10524
10525def RoundTowardZero(ctx=None):
10526 ctx = _get_ctx(ctx)
10527 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10528
10529
10530def RTZ(ctx=None):
10531 ctx = _get_ctx(ctx)
10532 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10533
10534
10535def is_fprm(a):
10536 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10537
10538 >>> rm = RNE()
10539 >>> is_fprm(rm)
10540 True
10541 >>> rm = 1.0
10542 >>> is_fprm(rm)
10543 False
10544 """
10545 return isinstance(a, FPRMRef)
10546
10547
10548def is_fprm_value(a):
10549 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10550 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10551
10552# FP Numerals
10553
10554
10555class FPNumRef(FPRef):
10556 """The sign of the numeral.
10557
10558 >>> x = FPVal(+1.0, FPSort(8, 24))
10559 >>> x.sign()
10560 False
10561 >>> x = FPVal(-1.0, FPSort(8, 24))
10562 >>> x.sign()
10563 True
10564 """
10565
10566 def sign(self):
10567 num = ctypes.c_bool()
10568 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10569 if nsign is False:
10570 raise Z3Exception("error retrieving the sign of a numeral.")
10571 return num.value != 0
10572
10573 """The sign of a floating-point numeral as a bit-vector expression.
10574
10575 Remark: NaN's are invalid arguments.
10576 """
10577
10578 def sign_as_bv(self):
10579 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10580
10581 """The significand of the numeral.
10582
10583 >>> x = FPVal(2.5, FPSort(8, 24))
10584 >>> x.significand()
10585 1.25
10586 """
10587
10588 def significand(self):
10589 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10590
10591 """The significand of the numeral as a long.
10592
10593 >>> x = FPVal(2.5, FPSort(8, 24))
10594 >>> x.significand_as_long()
10595 1.25
10596 """
10597
10598 def significand_as_long(self):
10599 ptr = (ctypes.c_ulonglong * 1)()
10600 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10601 raise Z3Exception("error retrieving the significand of a numeral.")
10602 return ptr[0]
10603
10604 """The significand of the numeral as a bit-vector expression.
10605
10606 Remark: NaN are invalid arguments.
10607 """
10608
10609 def significand_as_bv(self):
10610 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10611
10612 """The exponent of the numeral.
10613
10614 >>> x = FPVal(2.5, FPSort(8, 24))
10615 >>> x.exponent()
10616 1
10617 """
10618
10619 def exponent(self, biased=True):
10620 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10621
10622 """The exponent of the numeral as a long.
10623
10624 >>> x = FPVal(2.5, FPSort(8, 24))
10625 >>> x.exponent_as_long()
10626 1
10627 """
10628
10629 def exponent_as_long(self, biased=True):
10630 ptr = (ctypes.c_longlong * 1)()
10631 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10632 raise Z3Exception("error retrieving the exponent of a numeral.")
10633 return ptr[0]
10634
10635 """The exponent of the numeral as a bit-vector expression.
10636
10637 Remark: NaNs are invalid arguments.
10638 """
10639
10640 def exponent_as_bv(self, biased=True):
10641 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10642
10643 """Indicates whether the numeral is a NaN."""
10644
10645 def isNaN(self):
10646 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10647
10648 """Indicates whether the numeral is +oo or -oo."""
10649
10650 def isInf(self):
10651 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10652
10653 """Indicates whether the numeral is +zero or -zero."""
10654
10655 def isZero(self):
10656 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10657
10658 """Indicates whether the numeral is normal."""
10659
10660 def isNormal(self):
10661 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10662
10663 """Indicates whether the numeral is subnormal."""
10664
10665 def isSubnormal(self):
10666 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10667
10668 """Indicates whether the numeral is positive."""
10669
10670 def isPositive(self):
10671 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10672
10673 """Indicates whether the numeral is negative."""
10674
10675 def isNegative(self):
10676 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10677
10678 """
10679 The string representation of the numeral.
10680
10681 >>> x = FPVal(20, FPSort(8, 24))
10682 >>> x.as_string()
10683 1.25*(2**4)
10684 """
10685
10686 def as_string(self):
10687 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10688 return ("FPVal(%s, %s)" % (s, self.sort()))
10689
10690 def py_value(self):
10691 bv = simplify(fpToIEEEBV(self))
10692 binary = bv.py_value()
10693 if not isinstance(binary, int):
10694 return None
10695 # Decode the IEEE 754 binary representation
10696 import struct
10697 bytes_rep = binary.to_bytes(8, byteorder='big')
10698 return struct.unpack('>d', bytes_rep)[0]
10699
10700
10701def is_fp(a):
10702 """Return `True` if `a` is a Z3 floating-point expression.
10703
10704 >>> b = FP('b', FPSort(8, 24))
10705 >>> is_fp(b)
10706 True
10707 >>> is_fp(b + 1.0)
10708 True
10709 >>> is_fp(Int('x'))
10710 False
10711 """
10712 return isinstance(a, FPRef)
10713
10714
10715def is_fp_value(a):
10716 """Return `True` if `a` is a Z3 floating-point numeral value.
10717
10718 >>> b = FP('b', FPSort(8, 24))
10719 >>> is_fp_value(b)
10720 False
10721 >>> b = FPVal(1.0, FPSort(8, 24))
10722 >>> b
10723 1
10724 >>> is_fp_value(b)
10725 True
10726 """
10727 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10728
10729
10730def FPSort(ebits, sbits, ctx=None):
10731 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10732
10733 >>> Single = FPSort(8, 24)
10734 >>> Double = FPSort(11, 53)
10735 >>> Single
10736 FPSort(8, 24)
10737 >>> x = Const('x', Single)
10738 >>> eq(x, FP('x', FPSort(8, 24)))
10739 True
10740 """
10741 ctx = _get_ctx(ctx)
10742 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10743
10744
10745def _to_float_str(val, exp=0):
10746 if isinstance(val, float):
10747 if math.isnan(val):
10748 res = "NaN"
10749 elif val == 0.0:
10750 sone = math.copysign(1.0, val)
10751 if sone < 0.0:
10752 return "-0.0"
10753 else:
10754 return "+0.0"
10755 elif val == float("+inf"):
10756 res = "+oo"
10757 elif val == float("-inf"):
10758 res = "-oo"
10759 else:
10760 v = val.as_integer_ratio()
10761 num = v[0]
10762 den = v[1]
10763 rvs = str(num) + "/" + str(den)
10764 res = rvs + "p" + _to_int_str(exp)
10765 elif isinstance(val, bool):
10766 if val:
10767 res = "1.0"
10768 else:
10769 res = "0.0"
10770 elif _is_int(val):
10771 res = str(val)
10772 elif isinstance(val, str):
10773 inx = val.find("*(2**")
10774 if inx == -1:
10775 res = val
10776 elif val[-1] == ")":
10777 res = val[0:inx]
10778 exp = str(int(val[inx + 5:-1]) + int(exp))
10779 else:
10780 _z3_assert(False, "String does not have floating-point numeral form.")
10781 elif z3_debug():
10782 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10783 if exp == 0:
10784 return res
10785 else:
10786 return res + "p" + exp
10787
10788
10789def fpNaN(s):
10790 """Create a Z3 floating-point NaN term.
10791
10792 >>> s = FPSort(8, 24)
10793 >>> set_fpa_pretty(True)
10794 >>> fpNaN(s)
10795 NaN
10796 >>> pb = get_fpa_pretty()
10797 >>> set_fpa_pretty(False)
10798 >>> fpNaN(s)
10799 fpNaN(FPSort(8, 24))
10800 >>> set_fpa_pretty(pb)
10801 """
10802 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10803 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10804
10805
10806def fpPlusInfinity(s):
10807 """Create a Z3 floating-point +oo term.
10808
10809 >>> s = FPSort(8, 24)
10810 >>> pb = get_fpa_pretty()
10811 >>> set_fpa_pretty(True)
10812 >>> fpPlusInfinity(s)
10813 +oo
10814 >>> set_fpa_pretty(False)
10815 >>> fpPlusInfinity(s)
10816 fpPlusInfinity(FPSort(8, 24))
10817 >>> set_fpa_pretty(pb)
10818 """
10819 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10820 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10821
10822
10823def fpMinusInfinity(s):
10824 """Create a Z3 floating-point -oo term."""
10825 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10826 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10827
10828
10829def fpInfinity(s, negative):
10830 """Create a Z3 floating-point +oo or -oo term."""
10831 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10832 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10833 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10834
10835
10836def fpPlusZero(s):
10837 """Create a Z3 floating-point +0.0 term."""
10838 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10839 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10840
10841
10842def fpMinusZero(s):
10843 """Create a Z3 floating-point -0.0 term."""
10844 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10845 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10846
10847
10848def fpZero(s, negative):
10849 """Create a Z3 floating-point +0.0 or -0.0 term."""
10850 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10851 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10852 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10853
10854
10855def FPVal(sig, exp=None, fps=None, ctx=None):
10856 """Return a floating-point value of value `val` and sort `fps`.
10857 If `ctx=None`, then the global context is used.
10858
10859 >>> v = FPVal(20.0, FPSort(8, 24))
10860 >>> v
10861 1.25*(2**4)
10862 >>> print("0x%.8x" % v.exponent_as_long(False))
10863 0x00000004
10864 >>> v = FPVal(2.25, FPSort(8, 24))
10865 >>> v
10866 1.125*(2**1)
10867 >>> v = FPVal(-2.25, FPSort(8, 24))
10868 >>> v
10869 -1.125*(2**1)
10870 >>> FPVal(-0.0, FPSort(8, 24))
10871 -0.0
10872 >>> FPVal(0.0, FPSort(8, 24))
10873 +0.0
10874 >>> FPVal(+0.0, FPSort(8, 24))
10875 +0.0
10876 """
10877 ctx = _get_ctx(ctx)
10878 if is_fp_sort(exp):
10879 fps = exp
10880 exp = None
10881 elif fps is None:
10882 fps = _dflt_fps(ctx)
10883 _z3_assert(is_fp_sort(fps), "sort mismatch")
10884 if exp is None:
10885 exp = 0
10886 val = _to_float_str(sig)
10887 if val == "NaN" or val == "nan":
10888 return fpNaN(fps)
10889 elif val == "-0.0":
10890 return fpMinusZero(fps)
10891 elif val == "0.0" or val == "+0.0":
10892 return fpPlusZero(fps)
10893 elif val == "+oo" or val == "+inf" or val == "+Inf":
10894 return fpPlusInfinity(fps)
10895 elif val == "-oo" or val == "-inf" or val == "-Inf":
10896 return fpMinusInfinity(fps)
10897 else:
10898 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10899
10900
10901def FP(name, fpsort, ctx=None):
10902 """Return a floating-point constant named `name`.
10903 `fpsort` is the floating-point sort.
10904 If `ctx=None`, then the global context is used.
10905
10906 >>> x = FP('x', FPSort(8, 24))
10907 >>> is_fp(x)
10908 True
10909 >>> x.ebits()
10910 8
10911 >>> x.sort()
10912 FPSort(8, 24)
10913 >>> word = FPSort(8, 24)
10914 >>> x2 = FP('x', word)
10915 >>> eq(x, x2)
10916 True
10917 """
10918 if isinstance(fpsort, FPSortRef) and ctx is None:
10919 ctx = fpsort.ctx
10920 else:
10921 ctx = _get_ctx(ctx)
10922 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10923
10924
10925def FPs(names, fpsort, ctx=None):
10926 """Return an array of floating-point constants.
10927
10928 >>> x, y, z = FPs('x y z', FPSort(8, 24))
10929 >>> x.sort()
10930 FPSort(8, 24)
10931 >>> x.sbits()
10932 24
10933 >>> x.ebits()
10934 8
10935 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10936 (x + y) * z
10937 """
10938 ctx = _get_ctx(ctx)
10939 if isinstance(names, str):
10940 names = names.split(" ")
10941 return [FP(name, fpsort, ctx) for name in names]
10942
10943
10944def fpAbs(a, ctx=None):
10945 """Create a Z3 floating-point absolute value expression.
10946
10947 >>> s = FPSort(8, 24)
10948 >>> rm = RNE()
10949 >>> x = FPVal(1.0, s)
10950 >>> fpAbs(x)
10951 fpAbs(1)
10952 >>> y = FPVal(-20.0, s)
10953 >>> y
10954 -1.25*(2**4)
10955 >>> fpAbs(y)
10956 fpAbs(-1.25*(2**4))
10957 >>> fpAbs(-1.25*(2**4))
10958 fpAbs(-1.25*(2**4))
10959 >>> fpAbs(x).sort()
10960 FPSort(8, 24)
10961 """
10962 ctx = _get_ctx(ctx)
10963 [a] = _coerce_fp_expr_list([a], ctx)
10964 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10965
10966
10967def fpNeg(a, ctx=None):
10968 """Create a Z3 floating-point addition expression.
10969
10970 >>> s = FPSort(8, 24)
10971 >>> rm = RNE()
10972 >>> x = FP('x', s)
10973 >>> fpNeg(x)
10974 -x
10975 >>> fpNeg(x).sort()
10976 FPSort(8, 24)
10977 """
10978 ctx = _get_ctx(ctx)
10979 [a] = _coerce_fp_expr_list([a], ctx)
10980 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10981
10982
10983def _mk_fp_unary(f, rm, a, ctx):
10984 ctx = _get_ctx(ctx)
10985 [a] = _coerce_fp_expr_list([a], ctx)
10986 if z3_debug():
10987 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10988 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10989 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10990
10991
10992def _mk_fp_unary_pred(f, a, ctx):
10993 ctx = _get_ctx(ctx)
10994 [a] = _coerce_fp_expr_list([a], ctx)
10995 if z3_debug():
10996 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10997 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10998
10999
11000def _mk_fp_bin(f, rm, a, b, ctx):
11001 ctx = _get_ctx(ctx)
11002 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11003 if z3_debug():
11004 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11005 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
11006 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
11007
11008
11009def _mk_fp_bin_norm(f, a, b, ctx):
11010 ctx = _get_ctx(ctx)
11011 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11012 if z3_debug():
11013 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11014 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11015
11016
11017def _mk_fp_bin_pred(f, a, b, ctx):
11018 ctx = _get_ctx(ctx)
11019 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11020 if z3_debug():
11021 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11022 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11023
11024
11025def _mk_fp_tern(f, rm, a, b, c, ctx):
11026 ctx = _get_ctx(ctx)
11027 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11028 if z3_debug():
11029 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11030 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11031 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11032 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11033
11034
11035def fpAdd(rm, a, b, ctx=None):
11036 """Create a Z3 floating-point addition expression.
11037
11038 >>> s = FPSort(8, 24)
11039 >>> rm = RNE()
11040 >>> x = FP('x', s)
11041 >>> y = FP('y', s)
11042 >>> fpAdd(rm, x, y)
11043 x + y
11044 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11045 fpAdd(RTZ(), x, y)
11046 >>> fpAdd(rm, x, y).sort()
11047 FPSort(8, 24)
11048 """
11049 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11050
11051
11052def fpSub(rm, a, b, ctx=None):
11053 """Create a Z3 floating-point subtraction expression.
11054
11055 >>> s = FPSort(8, 24)
11056 >>> rm = RNE()
11057 >>> x = FP('x', s)
11058 >>> y = FP('y', s)
11059 >>> fpSub(rm, x, y)
11060 x - y
11061 >>> fpSub(rm, x, y).sort()
11062 FPSort(8, 24)
11063 """
11064 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11065
11066
11067def fpMul(rm, a, b, ctx=None):
11068 """Create a Z3 floating-point multiplication expression.
11069
11070 >>> s = FPSort(8, 24)
11071 >>> rm = RNE()
11072 >>> x = FP('x', s)
11073 >>> y = FP('y', s)
11074 >>> fpMul(rm, x, y)
11075 x * y
11076 >>> fpMul(rm, x, y).sort()
11077 FPSort(8, 24)
11078 """
11079 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11080
11081
11082def fpDiv(rm, a, b, ctx=None):
11083 """Create a Z3 floating-point division expression.
11084
11085 >>> s = FPSort(8, 24)
11086 >>> rm = RNE()
11087 >>> x = FP('x', s)
11088 >>> y = FP('y', s)
11089 >>> fpDiv(rm, x, y)
11090 x / y
11091 >>> fpDiv(rm, x, y).sort()
11092 FPSort(8, 24)
11093 """
11094 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11095
11096
11097def fpRem(a, b, ctx=None):
11098 """Create a Z3 floating-point remainder expression.
11099
11100 >>> s = FPSort(8, 24)
11101 >>> x = FP('x', s)
11102 >>> y = FP('y', s)
11103 >>> fpRem(x, y)
11104 fpRem(x, y)
11105 >>> fpRem(x, y).sort()
11106 FPSort(8, 24)
11107 """
11108 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11109
11110
11111def fpMin(a, b, ctx=None):
11112 """Create a Z3 floating-point minimum expression.
11113
11114 >>> s = FPSort(8, 24)
11115 >>> rm = RNE()
11116 >>> x = FP('x', s)
11117 >>> y = FP('y', s)
11118 >>> fpMin(x, y)
11119 fpMin(x, y)
11120 >>> fpMin(x, y).sort()
11121 FPSort(8, 24)
11122 """
11123 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11124
11125
11126def fpMax(a, b, ctx=None):
11127 """Create a Z3 floating-point maximum expression.
11128
11129 >>> s = FPSort(8, 24)
11130 >>> rm = RNE()
11131 >>> x = FP('x', s)
11132 >>> y = FP('y', s)
11133 >>> fpMax(x, y)
11134 fpMax(x, y)
11135 >>> fpMax(x, y).sort()
11136 FPSort(8, 24)
11137 """
11138 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11139
11140
11141def fpFMA(rm, a, b, c, ctx=None):
11142 """Create a Z3 floating-point fused multiply-add expression.
11143 """
11144 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11145
11146
11147def fpSqrt(rm, a, ctx=None):
11148 """Create a Z3 floating-point square root expression.
11149 """
11150 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11151
11152
11153def fpRoundToIntegral(rm, a, ctx=None):
11154 """Create a Z3 floating-point roundToIntegral expression.
11155 """
11156 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11157
11158
11159def fpIsNaN(a, ctx=None):
11160 """Create a Z3 floating-point isNaN expression.
11161
11162 >>> s = FPSort(8, 24)
11163 >>> x = FP('x', s)
11164 >>> y = FP('y', s)
11165 >>> fpIsNaN(x)
11166 fpIsNaN(x)
11167 """
11168 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11169
11170
11171def fpIsInf(a, ctx=None):
11172 """Create a Z3 floating-point isInfinite expression.
11173
11174 >>> s = FPSort(8, 24)
11175 >>> x = FP('x', s)
11176 >>> fpIsInf(x)
11177 fpIsInf(x)
11178 """
11179 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11180
11181
11182def fpIsZero(a, ctx=None):
11183 """Create a Z3 floating-point isZero expression.
11184 """
11185 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11186
11187
11188def fpIsNormal(a, ctx=None):
11189 """Create a Z3 floating-point isNormal expression.
11190 """
11191 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11192
11193
11194def fpIsSubnormal(a, ctx=None):
11195 """Create a Z3 floating-point isSubnormal expression.
11196 """
11197 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11198
11199
11200def fpIsNegative(a, ctx=None):
11201 """Create a Z3 floating-point isNegative expression.
11202 """
11203 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11204
11205
11206def fpIsPositive(a, ctx=None):
11207 """Create a Z3 floating-point isPositive expression.
11208 """
11209 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11210
11211
11212def _check_fp_args(a, b):
11213 if z3_debug():
11214 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11215
11216
11217def fpLT(a, b, ctx=None):
11218 """Create the Z3 floating-point expression `other < self`.
11219
11220 >>> x, y = FPs('x y', FPSort(8, 24))
11221 >>> fpLT(x, y)
11222 x < y
11223 >>> (x < y).sexpr()
11224 '(fp.lt x y)'
11225 """
11226 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11227
11228
11229def fpLEQ(a, b, ctx=None):
11230 """Create the Z3 floating-point expression `other <= self`.
11231
11232 >>> x, y = FPs('x y', FPSort(8, 24))
11233 >>> fpLEQ(x, y)
11234 x <= y
11235 >>> (x <= y).sexpr()
11236 '(fp.leq x y)'
11237 """
11238 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11239
11240
11241def fpGT(a, b, ctx=None):
11242 """Create the Z3 floating-point expression `other > self`.
11243
11244 >>> x, y = FPs('x y', FPSort(8, 24))
11245 >>> fpGT(x, y)
11246 x > y
11247 >>> (x > y).sexpr()
11248 '(fp.gt x y)'
11249 """
11250 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11251
11252
11253def fpGEQ(a, b, ctx=None):
11254 """Create the Z3 floating-point expression `other >= self`.
11255
11256 >>> x, y = FPs('x y', FPSort(8, 24))
11257 >>> fpGEQ(x, y)
11258 x >= y
11259 >>> (x >= y).sexpr()
11260 '(fp.geq x y)'
11261 """
11262 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11263
11264
11265def fpEQ(a, b, ctx=None):
11266 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11267
11268 >>> x, y = FPs('x y', FPSort(8, 24))
11269 >>> fpEQ(x, y)
11270 fpEQ(x, y)
11271 >>> fpEQ(x, y).sexpr()
11272 '(fp.eq x y)'
11273 """
11274 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11275
11276
11277def fpNEQ(a, b, ctx=None):
11278 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11279
11280 >>> x, y = FPs('x y', FPSort(8, 24))
11281 >>> fpNEQ(x, y)
11282 Not(fpEQ(x, y))
11283 >>> (x != y).sexpr()
11284 '(distinct x y)'
11285 """
11286 return Not(fpEQ(a, b, ctx))
11287
11288
11289def fpFP(sgn, exp, sig, ctx=None):
11290 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11291
11292 >>> s = FPSort(8, 24)
11293 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11294 >>> print(x)
11295 fpFP(1, 127, 4194304)
11296 >>> xv = FPVal(-1.5, s)
11297 >>> print(xv)
11298 -1.5
11299 >>> slvr = Solver()
11300 >>> slvr.add(fpEQ(x, xv))
11301 >>> slvr.check()
11302 sat
11303 >>> xv = FPVal(+1.5, s)
11304 >>> print(xv)
11305 1.5
11306 >>> slvr = Solver()
11307 >>> slvr.add(fpEQ(x, xv))
11308 >>> slvr.check()
11309 unsat
11310 """
11311 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11312 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11313 ctx = _get_ctx(ctx)
11314 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11315 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11316
11317
11318def fpToFP(a1, a2=None, a3=None, ctx=None):
11319 """Create a Z3 floating-point conversion expression from other term sorts
11320 to floating-point.
11321
11322 From a bit-vector term in IEEE 754-2008 format:
11323 >>> x = FPVal(1.0, Float32())
11324 >>> x_bv = fpToIEEEBV(x)
11325 >>> simplify(fpToFP(x_bv, Float32()))
11326 1
11327
11328 From a floating-point term with different precision:
11329 >>> x = FPVal(1.0, Float32())
11330 >>> x_db = fpToFP(RNE(), x, Float64())
11331 >>> x_db.sort()
11332 FPSort(11, 53)
11333
11334 From a real term:
11335 >>> x_r = RealVal(1.5)
11336 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11337 1.5
11338
11339 From a signed bit-vector term:
11340 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11341 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11342 -1.25*(2**2)
11343 """
11344 ctx = _get_ctx(ctx)
11345 if is_bv(a1) and is_fp_sort(a2):
11346 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11347 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11348 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11349 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11350 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11351 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11352 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11353 else:
11354 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11355
11356
11357def fpBVToFP(v, sort, ctx=None):
11358 """Create a Z3 floating-point conversion expression that represents the
11359 conversion from a bit-vector term to a floating-point term.
11360
11361 >>> x_bv = BitVecVal(0x3F800000, 32)
11362 >>> x_fp = fpBVToFP(x_bv, Float32())
11363 >>> x_fp
11364 fpToFP(1065353216)
11365 >>> simplify(x_fp)
11366 1
11367 """
11368 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11369 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11370 ctx = _get_ctx(ctx)
11371 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11372
11373
11374def fpFPToFP(rm, v, sort, ctx=None):
11375 """Create a Z3 floating-point conversion expression that represents the
11376 conversion from a floating-point term to a floating-point term of different precision.
11377
11378 >>> x_sgl = FPVal(1.0, Float32())
11379 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11380 >>> x_dbl
11381 fpToFP(RNE(), 1)
11382 >>> simplify(x_dbl)
11383 1
11384 >>> x_dbl.sort()
11385 FPSort(11, 53)
11386 """
11387 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11388 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11389 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11390 ctx = _get_ctx(ctx)
11391 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11392
11393
11394def fpRealToFP(rm, v, sort, ctx=None):
11395 """Create a Z3 floating-point conversion expression that represents the
11396 conversion from a real term to a floating-point term.
11397
11398 >>> x_r = RealVal(1.5)
11399 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11400 >>> x_fp
11401 fpToFP(RNE(), 3/2)
11402 >>> simplify(x_fp)
11403 1.5
11404 """
11405 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11406 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11407 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11408 ctx = _get_ctx(ctx)
11409 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11410
11411
11412def fpSignedToFP(rm, v, sort, ctx=None):
11413 """Create a Z3 floating-point conversion expression that represents the
11414 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11415
11416 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11417 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11418 >>> x_fp
11419 fpToFP(RNE(), 4294967291)
11420 >>> simplify(x_fp)
11421 -1.25*(2**2)
11422 """
11423 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11424 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11425 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11426 ctx = _get_ctx(ctx)
11427 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11428
11429
11430def fpUnsignedToFP(rm, v, sort, ctx=None):
11431 """Create a Z3 floating-point conversion expression that represents the
11432 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11433
11434 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11435 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11436 >>> x_fp
11437 fpToFPUnsigned(RNE(), 4294967291)
11438 >>> simplify(x_fp)
11439 1*(2**32)
11440 """
11441 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11442 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11443 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11444 ctx = _get_ctx(ctx)
11445 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11446
11447
11448def fpToFPUnsigned(rm, x, s, ctx=None):
11449 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11450 if z3_debug():
11451 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11452 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11453 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11454 ctx = _get_ctx(ctx)
11455 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11456
11457
11458def fpToSBV(rm, x, s, ctx=None):
11459 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11460
11461 >>> x = FP('x', FPSort(8, 24))
11462 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11463 >>> print(is_fp(x))
11464 True
11465 >>> print(is_bv(y))
11466 True
11467 >>> print(is_fp(y))
11468 False
11469 >>> print(is_bv(x))
11470 False
11471 """
11472 if z3_debug():
11473 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11474 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11475 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11476 ctx = _get_ctx(ctx)
11477 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11478
11479
11480def fpToUBV(rm, x, s, ctx=None):
11481 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11482
11483 >>> x = FP('x', FPSort(8, 24))
11484 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11485 >>> print(is_fp(x))
11486 True
11487 >>> print(is_bv(y))
11488 True
11489 >>> print(is_fp(y))
11490 False
11491 >>> print(is_bv(x))
11492 False
11493 """
11494 if z3_debug():
11495 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11496 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11497 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11498 ctx = _get_ctx(ctx)
11499 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11500
11501
11502def fpToReal(x, ctx=None):
11503 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11504
11505 >>> x = FP('x', FPSort(8, 24))
11506 >>> y = fpToReal(x)
11507 >>> print(is_fp(x))
11508 True
11509 >>> print(is_real(y))
11510 True
11511 >>> print(is_fp(y))
11512 False
11513 >>> print(is_real(x))
11514 False
11515 """
11516 if z3_debug():
11517 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11518 ctx = _get_ctx(ctx)
11519 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11520
11521
11522def fpToIEEEBV(x, ctx=None):
11523 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11524
11525 The size of the resulting bit-vector is automatically determined.
11526
11527 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11528 knows only one NaN and it will always produce the same bit-vector representation of
11529 that NaN.
11530
11531 >>> x = FP('x', FPSort(8, 24))
11532 >>> y = fpToIEEEBV(x)
11533 >>> print(is_fp(x))
11534 True
11535 >>> print(is_bv(y))
11536 True
11537 >>> print(is_fp(y))
11538 False
11539 >>> print(is_bv(x))
11540 False
11541 """
11542 if z3_debug():
11543 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11544 ctx = _get_ctx(ctx)
11545 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11546
11547
11548#########################################
11549#
11550# Strings, Sequences and Regular expressions
11551#
11552#########################################
11553
11554class SeqSortRef(SortRef):
11555 """Sequence sort."""
11556
11557 def is_string(self):
11558 """Determine if sort is a string
11559 >>> s = StringSort()
11560 >>> s.is_string()
11561 True
11562 >>> s = SeqSort(IntSort())
11563 >>> s.is_string()
11564 False
11565 """
11566 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11567
11568 def basis(self):
11569 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11570
11571class CharSortRef(SortRef):
11572 """Character sort."""
11573
11574
11575def StringSort(ctx=None):
11576 """Create a string sort
11577 >>> s = StringSort()
11578 >>> print(s)
11579 String
11580 """
11581 ctx = _get_ctx(ctx)
11582 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11583
11584def CharSort(ctx=None):
11585 """Create a character sort
11586 >>> ch = CharSort()
11587 >>> print(ch)
11588 Char
11589 """
11590 ctx = _get_ctx(ctx)
11591 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11592
11593
11594def SeqSort(s):
11595 """Create a sequence sort over elements provided in the argument
11596 >>> s = SeqSort(IntSort())
11597 >>> s == Unit(IntVal(1)).sort()
11598 True
11599 """
11600 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11601
11602
11603class SeqRef(ExprRef):
11604 """Sequence expression."""
11605
11606 def sort(self):
11607 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11608
11609 def __add__(self, other):
11610 return Concat(self, other)
11611
11612 def __radd__(self, other):
11613 return Concat(other, self)
11614
11615 def __pow__(self, other):
11616 return SeqPower(self, other)
11617
11618 def __getitem__(self, i):
11619 if _is_int(i):
11620 i = IntVal(i, self.ctx)
11621 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11622
11623 def at(self, i):
11624 if _is_int(i):
11625 i = IntVal(i, self.ctx)
11626 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11627
11628 def is_string(self):
11629 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11630
11631 def is_string_value(self):
11632 return Z3_is_string(self.ctx_ref(), self.as_ast())
11633
11634 def as_string(self):
11635 """Return a string representation of sequence expression."""
11636 if self.is_string_value():
11637 string_length = ctypes.c_uint()
11638 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11639 return string_at(chars, size=string_length.value).decode("latin-1")
11640 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11641
11642 def py_value(self):
11643 return self.as_string()
11644
11645 def __le__(self, other):
11646 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11647
11648 def __lt__(self, other):
11649 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11650
11651 def __ge__(self, other):
11652 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11653
11654 def __gt__(self, other):
11655 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11656
11657
11658def _coerce_char(ch, ctx=None):
11659 if isinstance(ch, str):
11660 ctx = _get_ctx(ctx)
11661 ch = CharVal(ch, ctx)
11662 if not is_expr(ch):
11663 raise Z3Exception("Character expression expected")
11664 return ch
11665
11666class CharRef(ExprRef):
11667 """Character expression."""
11668
11669 def __le__(self, other):
11670 other = _coerce_char(other, self.ctx)
11671 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11672
11673 def to_int(self):
11674 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11675
11676 def to_bv(self):
11677 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11678
11679 def is_digit(self):
11680 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11681
11682
11683def CharVal(ch, ctx=None):
11684 ctx = _get_ctx(ctx)
11685 if isinstance(ch, str):
11686 ch = ord(ch)
11687 if not isinstance(ch, int):
11688 raise Z3Exception("character value should be an ordinal")
11689 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11690
11691def CharFromBv(bv):
11692 if not is_expr(bv):
11693 raise Z3Exception("Bit-vector expression needed")
11694 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11695
11696def CharToBv(ch, ctx=None):
11697 ch = _coerce_char(ch, ctx)
11698 return ch.to_bv()
11699
11700def CharToInt(ch, ctx=None):
11701 ch = _coerce_char(ch, ctx)
11702 return ch.to_int()
11703
11704def CharIsDigit(ch, ctx=None):
11705 ch = _coerce_char(ch, ctx)
11706 return ch.is_digit()
11707
11708def _coerce_seq(s, ctx=None):
11709 if isinstance(s, str):
11710 ctx = _get_ctx(ctx)
11711 s = StringVal(s, ctx)
11712 if not is_expr(s):
11713 raise Z3Exception("Non-expression passed as a sequence")
11714 if not is_seq(s):
11715 raise Z3Exception("Non-sequence passed as a sequence")
11716 return s
11717
11718
11719def _get_ctx2(a, b, ctx=None):
11720 if is_expr(a):
11721 return a.ctx
11722 if is_expr(b):
11723 return b.ctx
11724 if ctx is None:
11725 ctx = main_ctx()
11726 return ctx
11727
11728
11729def is_seq(a):
11730 """Return `True` if `a` is a Z3 sequence expression.
11731 >>> print (is_seq(Unit(IntVal(0))))
11732 True
11733 >>> print (is_seq(StringVal("abc")))
11734 True
11735 """
11736 return isinstance(a, SeqRef)
11737
11738
11739def is_string(a: Any) -> bool:
11740 """Return `True` if `a` is a Z3 string expression.
11741 >>> print (is_string(StringVal("ab")))
11742 True
11743 """
11744 return isinstance(a, SeqRef) and a.is_string()
11745
11746
11747def is_string_value(a: Any) -> bool:
11748 """return 'True' if 'a' is a Z3 string constant expression.
11749 >>> print (is_string_value(StringVal("a")))
11750 True
11751 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11752 False
11753 """
11754 return isinstance(a, SeqRef) and a.is_string_value()
11755
11756def StringVal(s, ctx=None):
11757 """create a string expression"""
11758 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11759 ctx = _get_ctx(ctx)
11760 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11761
11762
11763def String(name, ctx=None):
11764 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11765
11766 >>> x = String('x')
11767 """
11768 ctx = _get_ctx(ctx)
11769 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11770
11771
11772def Strings(names, ctx=None):
11773 """Return a tuple of String constants. """
11774 ctx = _get_ctx(ctx)
11775 if isinstance(names, str):
11776 names = names.split(" ")
11777 return [String(name, ctx) for name in names]
11778
11779
11780def SubString(s, offset, length):
11781 """Extract substring or subsequence starting at offset.
11782
11783 This is a convenience function that redirects to Extract(s, offset, length).
11784
11785 >>> s = StringVal("hello world")
11786 >>> SubString(s, 6, 5) # Extract "world"
11787 str.substr("hello world", 6, 5)
11788 >>> simplify(SubString(StringVal("hello"), 1, 3))
11789 "ell"
11790 """
11791 return Extract(s, offset, length)
11792
11793
11794def SubSeq(s, offset, length):
11795 """Extract substring or subsequence starting at offset.
11796
11797 This is a convenience function that redirects to Extract(s, offset, length).
11798
11799 >>> s = StringVal("hello world")
11800 >>> SubSeq(s, 0, 5) # Extract "hello"
11801 str.substr("hello world", 0, 5)
11802 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11803 "stin"
11804 """
11805 return Extract(s, offset, length)
11806
11807
11808def Empty(s):
11809 """Create the empty sequence of the given sort
11810 >>> e = Empty(StringSort())
11811 >>> e2 = StringVal("")
11812 >>> print(e.eq(e2))
11813 True
11814 >>> e3 = Empty(SeqSort(IntSort()))
11815 >>> print(e3)
11816 Empty(Seq(Int))
11817 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11818 >>> print(e4)
11819 Empty(ReSort(Seq(Int)))
11820 """
11821 if isinstance(s, SeqSortRef):
11822 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11823 if isinstance(s, ReSortRef):
11824 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11825 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11826
11827
11828def Full(s):
11829 """Create the regular expression that accepts the universal language
11830 >>> e = Full(ReSort(SeqSort(IntSort())))
11831 >>> print(e)
11832 Full(ReSort(Seq(Int)))
11833 >>> e1 = Full(ReSort(StringSort()))
11834 >>> print(e1)
11835 Full(ReSort(String))
11836 """
11837 if isinstance(s, ReSortRef):
11838 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11839 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11840
11841
11842
11843def Unit(a):
11844 """Create a singleton sequence"""
11845 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11846
11847
11848def PrefixOf(a, b):
11849 """Check if 'a' is a prefix of 'b'
11850 >>> s1 = PrefixOf("ab", "abc")
11851 >>> simplify(s1)
11852 True
11853 >>> s2 = PrefixOf("bc", "abc")
11854 >>> simplify(s2)
11855 False
11856 """
11857 ctx = _get_ctx2(a, b)
11858 a = _coerce_seq(a, ctx)
11859 b = _coerce_seq(b, ctx)
11860 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11861
11862
11863def SuffixOf(a, b):
11864 """Check if 'a' is a suffix of 'b'
11865 >>> s1 = SuffixOf("ab", "abc")
11866 >>> simplify(s1)
11867 False
11868 >>> s2 = SuffixOf("bc", "abc")
11869 >>> simplify(s2)
11870 True
11871 """
11872 ctx = _get_ctx2(a, b)
11873 a = _coerce_seq(a, ctx)
11874 b = _coerce_seq(b, ctx)
11875 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11876
11877
11878def Contains(a, b):
11879 """Check if 'a' contains 'b'
11880 >>> s1 = Contains("abc", "ab")
11881 >>> simplify(s1)
11882 True
11883 >>> s2 = Contains("abc", "bc")
11884 >>> simplify(s2)
11885 True
11886 >>> x, y, z = Strings('x y z')
11887 >>> s3 = Contains(Concat(x,y,z), y)
11888 >>> simplify(s3)
11889 True
11890 """
11891 ctx = _get_ctx2(a, b)
11892 a = _coerce_seq(a, ctx)
11893 b = _coerce_seq(b, ctx)
11894 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11895
11896
11897def Replace(s, src, dst):
11898 """Replace the first occurrence of 'src' by 'dst' in 's'
11899 >>> r = Replace("aaa", "a", "b")
11900 >>> simplify(r)
11901 "baa"
11902 """
11903 ctx = _get_ctx2(dst, s)
11904 if ctx is None and is_expr(src):
11905 ctx = src.ctx
11906 src = _coerce_seq(src, ctx)
11907 dst = _coerce_seq(dst, ctx)
11908 s = _coerce_seq(s, ctx)
11909 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11910
11911
11912def IndexOf(s, substr, offset=None):
11913 """Retrieve the index of substring within a string starting at a specified offset.
11914 >>> simplify(IndexOf("abcabc", "bc", 0))
11915 1
11916 >>> simplify(IndexOf("abcabc", "bc", 2))
11917 4
11918 """
11919 if offset is None:
11920 offset = IntVal(0)
11921 ctx = None
11922 if is_expr(offset):
11923 ctx = offset.ctx
11924 ctx = _get_ctx2(s, substr, ctx)
11925 s = _coerce_seq(s, ctx)
11926 substr = _coerce_seq(substr, ctx)
11927 if _is_int(offset):
11928 offset = IntVal(offset, ctx)
11929 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11930
11931
11932def LastIndexOf(s, substr):
11933 """Retrieve the last index of substring within a string"""
11934 ctx = None
11935 ctx = _get_ctx2(s, substr, ctx)
11936 s = _coerce_seq(s, ctx)
11937 substr = _coerce_seq(substr, ctx)
11938 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11939
11940
11941def Length(s):
11942 """Obtain the length of a sequence 's'
11943 >>> l = Length(StringVal("abc"))
11944 >>> simplify(l)
11945 3
11946 """
11947 s = _coerce_seq(s)
11948 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11949
11950def SeqPower(s, n):
11951 """Concatenate the sequence 's' with itself 'n' times. It is the empty sequence for n <= 0
11952 >>> p = SeqPower(StringVal("ab"), 2)
11953 >>> simplify(p)
11954 "abab"
11955 """
11956 s = _coerce_seq(s)
11957 n = _py2expr(n, s.ctx)
11958 return SeqRef(Z3_mk_seq_power(s.ctx_ref(), s.as_ast(), n.as_ast()), s.ctx)
11959
11960def SeqMap(f, s):
11961 """Map function 'f' over sequence 's'"""
11962 ctx = _get_ctx2(f, s)
11963 s = _coerce_seq(s, ctx)
11964 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
11965
11966def SeqMapI(f, i, s):
11967 """Map function 'f' over sequence 's' at index 'i'"""
11968 ctx = _get_ctx2(f, s)
11969 s = _coerce_seq(s, ctx)
11970 if not is_expr(i):
11971 i = _py2expr(i)
11972 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
11973
11974def SeqFoldLeft(f, a, s):
11975 ctx = _get_ctx2(f, s)
11976 s = _coerce_seq(s, ctx)
11977 a = _py2expr(a)
11978 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
11979
11980def SeqFoldLeftI(f, i, a, s):
11981 ctx = _get_ctx2(f, s)
11982 s = _coerce_seq(s, ctx)
11983 a = _py2expr(a)
11984 i = _py2expr(i)
11985 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
11986
11987def StrToInt(s):
11988 """Convert string expression to integer
11989 >>> a = StrToInt("1")
11990 >>> simplify(1 == a)
11991 True
11992 >>> b = StrToInt("2")
11993 >>> simplify(1 == b)
11994 False
11995 >>> c = StrToInt(IntToStr(2))
11996 >>> simplify(1 == c)
11997 False
11998 """
11999 s = _coerce_seq(s)
12000 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
12001
12002
12003def IntToStr(s):
12004 """Convert integer expression to string"""
12005 if not is_expr(s):
12006 s = _py2expr(s)
12007 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
12008
12009
12010def StrToCode(s):
12011 """Convert a unit length string to integer code"""
12012 if not is_expr(s):
12013 s = _py2expr(s)
12014 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
12015
12016def StrFromCode(c):
12017 """Convert code to a string"""
12018 if not is_expr(c):
12019 c = _py2expr(c)
12020 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
12021
12022def Re(s, ctx=None):
12023 """The regular expression that accepts sequence 's'
12024 >>> s1 = Re("ab")
12025 >>> s2 = Re(StringVal("ab"))
12026 >>> s3 = Re(Unit(BoolVal(True)))
12027 """
12028 s = _coerce_seq(s, ctx)
12029 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12030
12031
12032# Regular expressions
12033
12034class ReSortRef(SortRef):
12035 """Regular expression sort."""
12036
12037 def basis(self):
12038 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12039
12040
12041def ReSort(s):
12042 if is_ast(s):
12043 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12044 if s is None or isinstance(s, Context):
12045 ctx = _get_ctx(s)
12046 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12047 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12048
12049
12050class ReRef(ExprRef):
12051 """Regular expressions."""
12052
12053 def __add__(self, other):
12054 return Union(self, other)
12055
12056
12057def is_re(s):
12058 return isinstance(s, ReRef)
12059
12060
12061def InRe(s, re):
12062 """Create regular expression membership test
12063 >>> re = Union(Re("a"),Re("b"))
12064 >>> print (simplify(InRe("a", re)))
12065 True
12066 >>> print (simplify(InRe("b", re)))
12067 True
12068 >>> print (simplify(InRe("c", re)))
12069 False
12070 """
12071 s = _coerce_seq(s, re.ctx)
12072 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12073
12074
12075def Union(*args):
12076 """Create union of regular expressions.
12077 >>> re = Union(Re("a"), Re("b"), Re("c"))
12078 >>> print (simplify(InRe("d", re)))
12079 False
12080 """
12081 args = _get_args(args)
12082 sz = len(args)
12083 if z3_debug():
12084 _z3_assert(sz > 0, "At least one argument expected.")
12085 arg0 = args[0]
12086 if is_finite_set(arg0):
12087 for a in args[1:]:
12088 if not is_finite_set(a):
12089 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12090 arg0 = arg0 | a
12091 return arg0
12092 if z3_debug():
12093 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12094 if sz == 1:
12095 return args[0]
12096 ctx = args[0].ctx
12097 v = (Ast * sz)()
12098 for i in range(sz):
12099 v[i] = args[i].as_ast()
12100 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12101
12102
12103def Intersect(*args):
12104 """Create intersection of regular expressions.
12105 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12106 """
12107 args = _get_args(args)
12108 sz = len(args)
12109 if z3_debug():
12110 _z3_assert(sz > 0, "At least one argument expected.")
12111 arg0 = args[0]
12112 if is_finite_set(arg0):
12113 for a in args[1:]:
12114 if not is_finite_set(a):
12115 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12116 arg0 = arg0 & a
12117 return arg0
12118 if z3_debug():
12119 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12120 if sz == 1:
12121 return args[0]
12122 ctx = args[0].ctx
12123 v = (Ast * sz)()
12124 for i in range(sz):
12125 v[i] = args[i].as_ast()
12126 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12127
12128
12129def Plus(re):
12130 """Create the regular expression accepting one or more repetitions of argument.
12131 >>> re = Plus(Re("a"))
12132 >>> print(simplify(InRe("aa", re)))
12133 True
12134 >>> print(simplify(InRe("ab", re)))
12135 False
12136 >>> print(simplify(InRe("", re)))
12137 False
12138 """
12139 if z3_debug():
12140 _z3_assert(is_expr(re), "expression expected")
12141 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12142
12143
12144def Option(re):
12145 """Create the regular expression that optionally accepts the argument.
12146 >>> re = Option(Re("a"))
12147 >>> print(simplify(InRe("a", re)))
12148 True
12149 >>> print(simplify(InRe("", re)))
12150 True
12151 >>> print(simplify(InRe("aa", re)))
12152 False
12153 """
12154 if z3_debug():
12155 _z3_assert(is_expr(re), "expression expected")
12156 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12157
12158
12159def Complement(re):
12160 """Create the complement regular expression."""
12161 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12162
12163
12164def Star(re):
12165 """Create the regular expression accepting zero or more repetitions of argument.
12166 >>> re = Star(Re("a"))
12167 >>> print(simplify(InRe("aa", re)))
12168 True
12169 >>> print(simplify(InRe("ab", re)))
12170 False
12171 >>> print(simplify(InRe("", re)))
12172 True
12173 """
12174 if z3_debug():
12175 _z3_assert(is_expr(re), "expression expected")
12176 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12177
12178
12179def Loop(re, lo, hi=0):
12180 """Create the regular expression accepting between a lower and upper bound repetitions
12181 >>> re = Loop(Re("a"), 1, 3)
12182 >>> print(simplify(InRe("aa", re)))
12183 True
12184 >>> print(simplify(InRe("aaaa", re)))
12185 False
12186 >>> print(simplify(InRe("", re)))
12187 False
12188 """
12189 if z3_debug():
12190 _z3_assert(is_expr(re), "expression expected")
12191 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12192
12193
12194def Range(lo, hi, ctx=None):
12195 """Create the range regular expression over two sequences of length 1
12196 >>> range = Range("a","z")
12197 >>> print(simplify(InRe("b", range)))
12198 True
12199 >>> print(simplify(InRe("bb", range)))
12200 False
12201 """
12202 lo = _coerce_seq(lo, ctx)
12203 hi = _coerce_seq(hi, ctx)
12204 if z3_debug():
12205 _z3_assert(is_expr(lo), "expression expected")
12206 _z3_assert(is_expr(hi), "expression expected")
12207 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12208
12209def Diff(a, b, ctx=None):
12210 """Create the difference regular expression
12211 """
12212 if z3_debug():
12213 _z3_assert(is_expr(a), "expression expected")
12214 _z3_assert(is_expr(b), "expression expected")
12215 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12216
12217def AllChar(regex_sort, ctx=None):
12218 """Create a regular expression that accepts all single character strings
12219 """
12220 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12221
12222# Special Relations
12223
12224
12225def PartialOrder(a, index):
12226 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12227
12228
12229def LinearOrder(a, index):
12230 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12231
12232
12233def TreeOrder(a, index):
12234 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12235
12236
12237def PiecewiseLinearOrder(a, index):
12238 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12239
12240
12241def TransitiveClosure(f):
12242 """Given a binary relation R, such that the two arguments have the same sort
12243 create the transitive closure relation R+.
12244 The transitive closure R+ is a new relation.
12245 """
12246 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12247
12248def to_Ast(ptr,):
12249 ast = Ast(ptr)
12250 super(ctypes.c_void_p, ast).__init__(ptr)
12251 return ast
12252
12253def to_ContextObj(ptr,):
12254 ctx = ContextObj(ptr)
12255 super(ctypes.c_void_p, ctx).__init__(ptr)
12256 return ctx
12257
12258def to_AstVectorObj(ptr,):
12259 v = AstVectorObj(ptr)
12260 super(ctypes.c_void_p, v).__init__(ptr)
12261 return v
12262
12263# NB. my-hacky-class only works for a single instance of OnClause
12264# it should be replaced with a proper correlation between OnClause
12265# and object references that can be passed over the FFI.
12266# for UserPropagator we use a global dictionary, which isn't great code.
12267
12268_my_hacky_class = None
12269def on_clause_eh(ctx, p, n, dep, clause):
12270 onc = _my_hacky_class
12271 p = _to_expr_ref(to_Ast(p), onc.ctx)
12272 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12273 deps = [dep[i] for i in range(n)]
12274 onc.on_clause(p, deps, clause)
12275
12276_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12277
12278class OnClause:
12279 def __init__(self, s, on_clause):
12280 self.s = s
12281 self.ctx = s.ctx
12282 self.on_clause = on_clause
12283 self.idx = 22
12284 global _my_hacky_class
12285 _my_hacky_class = self
12286 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12287
12288
12289class PropClosures:
12290 def __init__(self):
12291 self.bases = {}
12292 self.lock = None
12293
12294 def set_threaded(self):
12295 if self.lock is None:
12296 import threading
12297 self.lock = threading.Lock()
12298
12299 def get(self, ctx):
12300 if self.lock:
12301 with self.lock:
12302 r = self.bases[ctx]
12303 else:
12304 r = self.bases[ctx]
12305 return r
12306
12307 def set(self, ctx, r):
12308 if self.lock:
12309 with self.lock:
12310 self.bases[ctx] = r
12311 else:
12312 self.bases[ctx] = r
12313
12314 def insert(self, r):
12315 if self.lock:
12316 with self.lock:
12317 id = len(self.bases) + 3
12318 self.bases[id] = r
12319 else:
12320 id = len(self.bases) + 3
12321 self.bases[id] = r
12322 return id
12323
12324
12325_prop_closures = None
12326
12327
12328def ensure_prop_closures():
12329 global _prop_closures
12330 if _prop_closures is None:
12331 _prop_closures = PropClosures()
12332
12333
12334def user_prop_push(ctx, cb):
12335 prop = _prop_closures.get(ctx)
12336 prop.cb = cb
12337 prop.push()
12338
12339
12340def user_prop_pop(ctx, cb, num_scopes):
12341 prop = _prop_closures.get(ctx)
12342 prop.cb = cb
12343 prop.pop(num_scopes)
12344
12345
12346def user_prop_fresh(ctx, _new_ctx):
12347 _prop_closures.set_threaded()
12348 prop = _prop_closures.get(ctx)
12349 nctx = Context()
12350 Z3_del_context(nctx.ctx)
12351 new_ctx = to_ContextObj(_new_ctx)
12352 nctx.ctx = new_ctx
12353 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12354 nctx.owner = False
12355 new_prop = prop.fresh(nctx)
12356 _prop_closures.set(new_prop.id, new_prop)
12357 return new_prop.id
12358
12359
12360def user_prop_fixed(ctx, cb, id, value):
12361 prop = _prop_closures.get(ctx)
12362 old_cb = prop.cb
12363 prop.cb = cb
12364 id = _to_expr_ref(to_Ast(id), prop.ctx())
12365 value = _to_expr_ref(to_Ast(value), prop.ctx())
12366 prop.fixed(id, value)
12367 prop.cb = old_cb
12368
12369def user_prop_created(ctx, cb, id):
12370 prop = _prop_closures.get(ctx)
12371 old_cb = prop.cb
12372 prop.cb = cb
12373 id = _to_expr_ref(to_Ast(id), prop.ctx())
12374 prop.created(id)
12375 prop.cb = old_cb
12376
12377
12378def user_prop_final(ctx, cb):
12379 prop = _prop_closures.get(ctx)
12380 old_cb = prop.cb
12381 prop.cb = cb
12382 prop.final()
12383 prop.cb = old_cb
12384
12385def user_prop_eq(ctx, cb, x, y):
12386 prop = _prop_closures.get(ctx)
12387 old_cb = prop.cb
12388 prop.cb = cb
12389 x = _to_expr_ref(to_Ast(x), prop.ctx())
12390 y = _to_expr_ref(to_Ast(y), prop.ctx())
12391 prop.eq(x, y)
12392 prop.cb = old_cb
12393
12394def user_prop_diseq(ctx, cb, x, y):
12395 prop = _prop_closures.get(ctx)
12396 old_cb = prop.cb
12397 prop.cb = cb
12398 x = _to_expr_ref(to_Ast(x), prop.ctx())
12399 y = _to_expr_ref(to_Ast(y), prop.ctx())
12400 prop.diseq(x, y)
12401 prop.cb = old_cb
12402
12403def user_prop_decide(ctx, cb, t_ref, idx, phase):
12404 prop = _prop_closures.get(ctx)
12405 old_cb = prop.cb
12406 prop.cb = cb
12407 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12408 prop.decide(t, idx, phase)
12409 prop.cb = old_cb
12410
12411def user_prop_binding(ctx, cb, q_ref, inst_ref):
12412 prop = _prop_closures.get(ctx)
12413 old_cb = prop.cb
12414 prop.cb = cb
12415 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12416 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12417 r = prop.binding(q, inst)
12418 prop.cb = old_cb
12419 return r
12420
12421
12422_user_prop_push = Z3_push_eh(user_prop_push)
12423_user_prop_pop = Z3_pop_eh(user_prop_pop)
12424_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12425_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12426_user_prop_created = Z3_created_eh(user_prop_created)
12427_user_prop_final = Z3_final_eh(user_prop_final)
12428_user_prop_eq = Z3_eq_eh(user_prop_eq)
12429_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12430_user_prop_decide = Z3_decide_eh(user_prop_decide)
12431_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12432
12433
12434def PropagateFunction(name, *sig):
12435 """Create a function that gets tracked by user propagator.
12436 Every term headed by this function symbol is tracked.
12437 If a term is fixed and the fixed callback is registered a
12438 callback is invoked that the term headed by this function is fixed.
12439 """
12440 sig = _get_args(sig)
12441 if z3_debug():
12442 _z3_assert(len(sig) > 0, "At least two arguments expected")
12443 arity = len(sig) - 1
12444 rng = sig[arity]
12445 if z3_debug():
12446 _z3_assert(is_sort(rng), "Z3 sort expected")
12447 dom = (Sort * arity)()
12448 for i in range(arity):
12449 if z3_debug():
12450 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12451 dom[i] = sig[i].ast
12452 ctx = rng.ctx
12453 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12454
12455
12456
12457class UserPropagateBase:
12458
12459 #
12460 # Either solver is set or ctx is set.
12461 # Propagators that are created through callbacks
12462 # to "fresh" inherit the context of that is supplied
12463 # as argument to the callback.
12464 # This context should not be deleted. It is owned by the solver.
12465 #
12466 def __init__(self, s, ctx=None):
12467 assert s is None or ctx is None
12468 ensure_prop_closures()
12469 self.solver = s
12470 self._ctx = None
12471 self.fresh_ctx = None
12472 self.cb = None
12473 self.id = _prop_closures.insert(self)
12474 self.fixed = None
12475 self.final = None
12476 self.eq = None
12477 self.diseq = None
12478 self.decide = None
12479 self.created = None
12480 self.binding = None
12481 if ctx:
12482 self.fresh_ctx = ctx
12483 if s:
12484 Z3_solver_propagate_init(self.ctx_ref(),
12485 s.solver,
12486 ctypes.c_void_p(self.id),
12487 _user_prop_push,
12488 _user_prop_pop,
12489 _user_prop_fresh)
12490
12491 def __del__(self):
12492 if self._ctx:
12493 self._ctx.ctx = None
12494
12495 def ctx(self):
12496 if self.fresh_ctx:
12497 return self.fresh_ctx
12498 else:
12499 return self.solver.ctx
12500
12501 def ctx_ref(self):
12502 return self.ctx().ref()
12503
12504 def add_fixed(self, fixed):
12505 if self.fixed:
12506 raise Z3Exception("fixed callback already registered")
12507 if self._ctx:
12508 raise Z3Exception("context already initialized")
12509 if self.solver:
12510 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12511 self.fixed = fixed
12512
12513 def add_created(self, created):
12514 if self.created:
12515 raise Z3Exception("created callback already registered")
12516 if self._ctx:
12517 raise Z3Exception("context already initialized")
12518 if self.solver:
12519 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12520 self.created = created
12521
12522 def add_final(self, final):
12523 if self.final:
12524 raise Z3Exception("final callback already registered")
12525 if self._ctx:
12526 raise Z3Exception("context already initialized")
12527 if self.solver:
12528 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12529 self.final = final
12530
12531 def add_eq(self, eq):
12532 if self.eq:
12533 raise Z3Exception("eq callback already registered")
12534 if self._ctx:
12535 raise Z3Exception("context already initialized")
12536 if self.solver:
12537 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12538 self.eq = eq
12539
12540 def add_diseq(self, diseq):
12541 if self.diseq:
12542 raise Z3Exception("diseq callback already registered")
12543 if self._ctx:
12544 raise Z3Exception("context already initialized")
12545 if self.solver:
12546 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12547 self.diseq = diseq
12548
12549 def add_decide(self, decide):
12550 if self.decide:
12551 raise Z3Exception("decide callback already registered")
12552 if self._ctx:
12553 raise Z3Exception("context already initialized")
12554 if self.solver:
12555 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12556 self.decide = decide
12557
12558 def add_on_binding(self, binding):
12559 if self.binding:
12560 raise Z3Exception("binding callback already registered")
12561 if self._ctx:
12562 raise Z3Exception("context already initialized")
12563 if self.solver:
12564 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12565 self.binding = binding
12566
12567 def push(self):
12568 raise Z3Exception("push needs to be overwritten")
12569
12570 def pop(self, num_scopes):
12571 raise Z3Exception("pop needs to be overwritten")
12572
12573 def fresh(self, new_ctx):
12574 raise Z3Exception("fresh needs to be overwritten")
12575
12576 def add(self, e):
12577 if self._ctx:
12578 raise Z3Exception("context already initialized")
12579 if self.solver:
12580 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12581 else:
12582 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12583
12584 #
12585 # Tell the solver to perform the next split on a given term
12586 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12587 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12588 #
12589 def next_split(self, t, idx, phase):
12590 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12591
12592 #
12593 # Propagation can only be invoked as during a fixed or final callback.
12594 #
12595 def propagate(self, e, ids, eqs=[]):
12596 _ids, num_fixed = _to_ast_array(ids)
12597 num_eqs = len(eqs)
12598 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12599 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12600 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12601 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12602
12603 def conflict(self, deps = [], eqs = []):
12604 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
approx(self, precision=10)
Definition z3py.py:3258
as_decimal(self, prec)
Definition z3py.py:3270
__rmod__(self, other)
Definition z3py.py:2729
__mod__(self, other)
Definition z3py.py:2714
__pow__(self, other)
Definition z3py.py:2638
__gt__(self, other)
Definition z3py.py:2787
__lt__(self, other)
Definition z3py.py:2774
__rtruediv__(self, other)
Definition z3py.py:2710
__rmul__(self, other)
Definition z3py.py:2605
__abs__(self)
Definition z3py.py:2813
__rsub__(self, other)
Definition z3py.py:2628
__add__(self, other)
Definition z3py.py:2567
__sub__(self, other)
Definition z3py.py:2615
is_real(self)
Definition z3py.py:2556
is_int(self)
Definition z3py.py:2542
__radd__(self, other)
Definition z3py.py:2580
__truediv__(self, other)
Definition z3py.py:2689
__le__(self, other)
Definition z3py.py:2761
__rpow__(self, other)
Definition z3py.py:2652
__pos__(self)
Definition z3py.py:2752
sort(self)
Definition z3py.py:2532
__mul__(self, other)
Definition z3py.py:2590
__rdiv__(self, other)
Definition z3py.py:2693
__ge__(self, other)
Definition z3py.py:2800
__neg__(self)
Definition z3py.py:2741
__div__(self, other)
Definition z3py.py:2666
Arithmetic.
Definition z3py.py:2437
subsort(self, other)
Definition z3py.py:2471
cast(self, val)
Definition z3py.py:2475
domain(self)
Definition z3py.py:4795
domain_n(self, i)
Definition z3py.py:4804
__getitem__(self, arg)
Definition z3py.py:4817
range(self)
Definition z3py.py:4808
sort(self)
Definition z3py.py:4786
default(self)
Definition z3py.py:4829
domain_n(self, i)
Definition z3py.py:4768
erase(self, k)
Definition z3py.py:6710
__deepcopy__(self, memo={})
Definition z3py.py:6647
__init__(self, m=None, ctx=None)
Definition z3py.py:6636
__repr__(self)
Definition z3py.py:6707
__len__(self)
Definition z3py.py:6654
keys(self)
Definition z3py.py:6739
__setitem__(self, k, v)
Definition z3py.py:6691
__contains__(self, key)
Definition z3py.py:6667
__del__(self)
Definition z3py.py:6650
__getitem__(self, key)
Definition z3py.py:6680
reset(self)
Definition z3py.py:6724
__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:6616
translate(self, other_ctx)
Definition z3py.py:6597
__repr__(self)
Definition z3py.py:6619
__len__(self)
Definition z3py.py:6489
__init__(self, v=None, ctx=None)
Definition z3py.py:6474
push(self, v)
Definition z3py.py:6549
__getitem__(self, i)
Definition z3py.py:6502
sexpr(self)
Definition z3py.py:6622
__del__(self)
Definition z3py.py:6485
__setitem__(self, i, v)
Definition z3py.py:6531
__contains__(self, item)
Definition z3py.py:6574
__copy__(self)
Definition z3py.py:6613
resize(self, sz)
Definition z3py.py:6561
as_binary_string(self)
Definition z3py.py:4108
as_signed_long(self)
Definition z3py.py:4082
as_string(self)
Definition z3py.py:4105
__and__(self, other)
Definition z3py.py:3772
__rmod__(self, other)
Definition z3py.py:3913
__rrshift__(self, other)
Definition z3py.py:4039
__mod__(self, other)
Definition z3py.py:3892
__or__(self, other)
Definition z3py.py:3749
__rlshift__(self, other)
Definition z3py.py:4053
__gt__(self, other)
Definition z3py.py:3963
__lt__(self, other)
Definition z3py.py:3947
__invert__(self)
Definition z3py.py:3838
__rtruediv__(self, other)
Definition z3py.py:3888
__rmul__(self, other)
Definition z3py.py:3716
__rxor__(self, other)
Definition z3py.py:3808
__ror__(self, other)
Definition z3py.py:3762
__rsub__(self, other)
Definition z3py.py:3739
__add__(self, other)
Definition z3py.py:3680
__sub__(self, other)
Definition z3py.py:3726
__radd__(self, other)
Definition z3py.py:3693
size(self)
Definition z3py.py:3669
__rand__(self, other)
Definition z3py.py:3785
__truediv__(self, other)
Definition z3py.py:3868
__le__(self, other)
Definition z3py.py:3931
__xor__(self, other)
Definition z3py.py:3795
__lshift__(self, other)
Definition z3py.py:4025
__pos__(self)
Definition z3py.py:3818
sort(self)
Definition z3py.py:3658
__mul__(self, other)
Definition z3py.py:3703
__rdiv__(self, other)
Definition z3py.py:3872
__ge__(self, other)
Definition z3py.py:3979
__neg__(self)
Definition z3py.py:3827
__rshift__(self, other)
Definition z3py.py:3995
__div__(self, other)
Definition z3py.py:3849
Bit-Vectors.
Definition z3py.py:3611
subsort(self, other)
Definition z3py.py:3623
cast(self, val)
Definition z3py.py:3626
__and__(self, other)
Definition z3py.py:1688
__or__(self, other)
Definition z3py.py:1691
__invert__(self)
Definition z3py.py:1697
__rmul__(self, other)
Definition z3py.py:1674
__add__(self, other)
Definition z3py.py:1666
py_value(self)
Definition z3py.py:1700
__radd__(self, other)
Definition z3py.py:1671
__xor__(self, other)
Definition z3py.py:1694
sort(self)
Definition z3py.py:1663
__mul__(self, other)
Definition z3py.py:1677
Booleans.
Definition z3py.py:1624
subsort(self, other)
Definition z3py.py:1650
is_bool(self)
Definition z3py.py:1656
cast(self, val)
Definition z3py.py:1627
__deepcopy__(self, memo={})
Definition z3py.py:7506
__eq__(self, other)
Definition z3py.py:7509
__ne__(self, other)
Definition z3py.py:7512
__init__(self, r)
Definition z3py.py:7503
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:5562
create(self)
Definition z3py.py:5601
__init__(self, name, ctx=None)
Definition z3py.py:5557
__repr__(self)
Definition z3py.py:5598
declare(self, name, *args)
Definition z3py.py:5577
create_polymorphic(self, type_params)
Definition z3py.py:5617
declare_core(self, name, rec_name, *args)
Definition z3py.py:5567
update_field(self, field_accessor, new_value)
Definition z3py.py:5926
constructor(self, idx)
Definition z3py.py:5838
accessor(self, i, j)
Definition z3py.py:5885
num_constructors(self)
Definition z3py.py:5825
recognizer(self, idx)
Definition z3py.py:5857
Expressions.
Definition z3py.py:1020
update(self, *args)
Definition z3py.py:1176
as_ast(self)
Definition z3py.py:1031
__hash__(self)
Definition z3py.py:1077
kind(self)
Definition z3py.py:1117
children(self)
Definition z3py.py:1161
serialize(self)
Definition z3py.py:1203
get_id(self)
Definition z3py.py:1034
num_args(self)
Definition z3py.py:1124
__eq__(self, other)
Definition z3py.py:1060
__ne__(self, other)
Definition z3py.py:1081
from_string(self, s)
Definition z3py.py:1200
sort_kind(self)
Definition z3py.py:1049
arg(self, idx)
Definition z3py.py:1140
sort(self)
Definition z3py.py:1037
params(self)
Definition z3py.py:1099
decl(self)
Definition z3py.py:1102
__and__(self, other)
Definition z3py.py:5377
__or__(self, other)
Definition z3py.py:5373
__sub__(self, other)
Definition z3py.py:5381
Finite Sets.
Definition z3py.py:5305
subsort(self, other)
Definition z3py.py:5327
cast(self, val)
Definition z3py.py:5312
Function Declarations.
Definition z3py.py:777
as_func_decl(self)
Definition z3py.py:791
domain(self, i)
Definition z3py.py:815
as_ast(self)
Definition z3py.py:785
__call__(self, *args)
Definition z3py.py:878
arity(self)
Definition z3py.py:805
get_id(self)
Definition z3py.py:788
range(self)
Definition z3py.py:827
params(self)
Definition z3py.py:850
Definition z3py.py:6758
__deepcopy__(self, memo={})
Definition z3py.py:6766
ctx
Definition z3py.py:6763
__repr__(self)
Definition z3py.py:6863
num_args(self)
Definition z3py.py:6773
entry
Definition z3py.py:6762
value(self)
Definition z3py.py:6822
__init__(self, entry, ctx)
Definition z3py.py:6761
__del__(self)
Definition z3py.py:6769
as_list(self)
Definition z3py.py:6844
arg_value(self, idx)
Definition z3py.py:6791
__deepcopy__(self, memo={})
Definition z3py.py:6961
translate(self, other_ctx)
Definition z3py.py:6953
arity(self)
Definition z3py.py:6919
__repr__(self)
Definition z3py.py:6981
num_entries(self)
Definition z3py.py:6903
__init__(self, f, ctx)
Definition z3py.py:6870
__del__(self)
Definition z3py.py:6876
as_list(self)
Definition z3py.py:6964
else_value(self)
Definition z3py.py:6880
entry(self, idx)
Definition z3py.py:6933
__copy__(self)
Definition z3py.py:6958
__deepcopy__(self, memo={})
Definition z3py.py:6419
get(self, i)
Definition z3py.py:6275
prec(self)
Definition z3py.py:6219
translate(self, target)
Definition z3py.py:6393
append(self, *args)
Definition z3py.py:6320
as_expr(self)
Definition z3py.py:6442
assert_exprs(self, *args)
Definition z3py.py:6305
__repr__(self)
Definition z3py.py:6382
__len__(self)
Definition z3py.py:6262
inconsistent(self)
Definition z3py.py:6201
dimacs(self, include_names=True)
Definition z3py.py:6389
__getitem__(self, arg)
Definition z3py.py:6288
size(self)
Definition z3py.py:6249
precision(self)
Definition z3py.py:6240
simplify(self, *arguments, **keywords)
Definition z3py.py:6422
sexpr(self)
Definition z3py.py:6385
add(self, *args)
Definition z3py.py:6342
__del__(self)
Definition z3py.py:6179
convert_model(self, model)
Definition z3py.py:6353
insert(self, *args)
Definition z3py.py:6331
depth(self)
Definition z3py.py:6183
__init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition z3py.py:6169
__copy__(self)
Definition z3py.py:6416
as_binary_string(self)
Definition z3py.py:3143
py_value(self)
Definition z3py.py:3151
as_long(self)
Definition z3py.py:3122
as_string(self)
Definition z3py.py:3135
__deepcopy__(self, memo={})
Definition z3py.py:7329
eval(self, t, model_completion=False)
Definition z3py.py:7005
translate(self, target)
Definition z3py.py:7294
__getitem__(self, idx)
Definition z3py.py:7206
num_sorts(self)
Definition z3py.py:7131
get_universe(self, s)
Definition z3py.py:7186
get_sort(self, idx)
Definition z3py.py:7146
project(self, vars, fml)
Definition z3py.py:7302
__repr__(self)
Definition z3py.py:6998
__len__(self)
Definition z3py.py:7062
get_interp(self, decl)
Definition z3py.py:7079
__init__(self, m, ctx)
Definition z3py.py:6988
sexpr(self)
Definition z3py.py:7001
sorts(self)
Definition z3py.py:7169
__del__(self)
Definition z3py.py:6994
decls(self)
Definition z3py.py:7253
project_with_witness(self, vars, fml)
Definition z3py.py:7314
update_value(self, x, value)
Definition z3py.py:7272
evaluate(self, t, model_completion=False)
Definition z3py.py:7036
__copy__(self)
Definition z3py.py:7326
__deepcopy__(self, memo={})
Definition z3py.py:6113
__init__(self, descr, ctx=None)
Definition z3py.py:6107
get_kind(self, n)
Definition z3py.py:6135
get_documentation(self, n)
Definition z3py.py:6140
__getitem__(self, arg)
Definition z3py.py:6145
get_name(self, i)
Definition z3py.py:6130
Parameter Sets.
Definition z3py.py:6034
__deepcopy__(self, memo={})
Definition z3py.py:6048
validate(self, ds)
Definition z3py.py:6075
__repr__(self)
Definition z3py.py:6072
__init__(self, ctx=None, params=None)
Definition z3py.py:6040
set(self, name, val)
Definition z3py.py:6055
__del__(self)
Definition z3py.py:6051
Patterns.
Definition z3py.py:2060
as_ast(self)
Definition z3py.py:2065
get_id(self)
Definition z3py.py:2068
Quantifiers.
Definition z3py.py:2127
num_no_patterns(self)
Definition z3py.py:2245
no_pattern(self, idx)
Definition z3py.py:2249
num_patterns(self)
Definition z3py.py:2215
var_name(self, idx)
Definition z3py.py:2278
__getitem__(self, arg)
Definition z3py.py:2184
var_sort(self, idx)
Definition z3py.py:2294
pattern(self, idx)
Definition z3py.py:2227
numerator_as_long(self)
Definition z3py.py:3184
is_int_value(self)
Definition z3py.py:3214
as_fraction(self)
Definition z3py.py:3242
py_value(self)
Definition z3py.py:3251
numerator(self)
Definition z3py.py:3158
is_real(self)
Definition z3py.py:3211
as_long(self)
Definition z3py.py:3217
is_int(self)
Definition z3py.py:3208
denominator_as_long(self)
Definition z3py.py:3197
as_string(self)
Definition z3py.py:3233
denominator(self)
Definition z3py.py:3173
as_decimal(self, prec)
Definition z3py.py:3221
__init__(self, c, ctx)
Definition z3py.py:5635
__init__(self, c, ctx)
Definition z3py.py:5647
Strings, Sequences and Regular expressions.
Definition z3py.py:11554
__init__(self, solver=None, ctx=None, logFile=None)
Definition z3py.py:7550
assert_and_track(self, a, p)
Definition z3py.py:7719
num_scopes(self)
Definition z3py.py:7631
append(self, *args)
Definition z3py.py:7697
__iadd__(self, fml)
Definition z3py.py:7693
backtrack_level
Definition z3py.py:7553
pop(self, num=1)
Definition z3py.py:7609
import_model_converter(self, other)
Definition z3py.py:7797
assert_exprs(self, *args)
Definition z3py.py:7663
model(self)
Definition z3py.py:7778
set(self, *args, **keys)
Definition z3py.py:7574
__enter__(self)
Definition z3py.py:7567
add(self, *args)
Definition z3py.py:7682
__del__(self)
Definition z3py.py:7563
insert(self, *args)
Definition z3py.py:7708
check(self, *assumptions)
Definition z3py.py:7749
push(self)
Definition z3py.py:7587
__exit__(self, *exc_info)
Definition z3py.py:7571
reset(self)
Definition z3py.py:7649
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:7359
__deepcopy__(self, memo={})
Definition z3py.py:7367
__getattr__(self, name)
Definition z3py.py:7462
__getitem__(self, idx)
Definition z3py.py:7406
__init__(self, stats, ctx)
Definition z3py.py:7362
__repr__(self)
Definition z3py.py:7374
__len__(self)
Definition z3py.py:7392
__del__(self)
Definition z3py.py:7370
get_key_value(self, key)
Definition z3py.py:7442
subsort(self, other)
Definition z3py.py:753
cast(self, val)
Definition z3py.py:756
ASTs base class.
Definition z3py.py:355
_repr_html_(self)
Definition z3py.py:361
use_pp(self)
Definition z3py.py:358
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
Z3_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
Z3_ast Z3_API Z3_mk_bvxnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise xnor.
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_mk_bvnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nor.
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_ast Z3_API Z3_mk_finite_set_empty(Z3_context c, Z3_sort set_sort)
Create an empty finite set of the given sort.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
bool Z3_API Z3_is_finite_set_sort(Z3_context c, Z3_sort s)
Check if a sort is a finite set sort.
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
Z3_ast Z3_API Z3_mk_finite_set_difference(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the set difference of two finite sets.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
Z3_symbol Z3_API Z3_get_quantifier_skolem_id(Z3_context c, Z3_ast a)
Obtain skolem id of quantifier.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
Z3_ast Z3_API Z3_mk_finite_set_subset(Z3_context c, Z3_ast s1, Z3_ast s2)
Check if one finite set is a subset of another.
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_sort Z3_API Z3_mk_polymorphic_datatype(Z3_context c, Z3_symbol name, unsigned num_parameters, Z3_sort parameters[], unsigned num_constructors, Z3_constructor constructors[])
Create a parametric datatype with explicit type parameters.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context....
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
Z3_ast Z3_API Z3_datatype_update_field(Z3_context c, Z3_func_decl field_access, Z3_ast t, Z3_ast value)
Update record field with a value.
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_sort Z3_API Z3_get_finite_set_sort_basis(Z3_context c, Z3_sort s)
Get the element sort of a finite set sort.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_finite_set_filter(Z3_context c, Z3_ast f, Z3_ast set)
Filter a finite set using a predicate.
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a)
The (_ as-array f) AST node is a construct for assigning interpretations for arrays in Z3....
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
Z3_ast Z3_API Z3_mk_is_int(Z3_context c, Z3_ast t1)
Check if a real number is an integer.
void Z3_API Z3_params_set_bool(Z3_context c, Z3_params p, Z3_symbol k, bool v)
Add a Boolean parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
Z3_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i)
Array read. The argument a is the array and i is the index of the array that gets read.
Z3_ast Z3_API Z3_mk_sign_ext(Z3_context c, unsigned i, Z3_ast t1)
Sign-extend of the given bit-vector to the (signed) equivalent bit-vector of size m+i,...
Z3_ast Z3_API Z3_mk_finite_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check if an element is a member of a finite set.
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_sort Z3_API Z3_mk_datatype_sort(Z3_context c, Z3_symbol name, unsigned num_params, Z3_sort const params[])
create a forward reference to a recursive datatype being declared. The forward reference can be used ...
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Z3_ast Z3_API Z3_mk_finite_set_union(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the union of two finite sets.
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_sort Z3_API Z3_get_array_sort_domain_n(Z3_context c, Z3_sort t, unsigned idx)
Return the i'th domain sort of an n-dimensional array.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_finite_set_intersect(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the intersection of two finite sets.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
void Z3_API Z3_add_const_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast a)
Add a constant interpretation.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a)
Return which root of the polynomial the algebraic number represents.
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
Z3_ast Z3_API Z3_update_term(Z3_context c, Z3_ast a, unsigned num_args, Z3_ast const args[])
Update the arguments of term a using the arguments args. The number of arguments num_args should coin...
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
Z3_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
Z3_ast Z3_API Z3_mk_bvnand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nand.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a variable.
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural but two different AST objects can m...
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_ast Z3_API Z3_mk_finite_set_singleton(Z3_context c, Z3_ast elem)
Create a singleton finite set.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_ast Z3_API Z3_mk_finite_set_map(Z3_context c, Z3_ast f, Z3_ast set)
Apply a function to all elements of a finite set.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_store_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs, Z3_ast v)
n-ary Array update.
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
Z3_sort Z3_API Z3_mk_finite_set_sort(Z3_context c, Z3_sort elem_sort)
Create a finite set sort.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
Z3_ast Z3_API Z3_mk_finite_set_size(Z3_context c, Z3_ast set)
Get the size (cardinality) of a finite set.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_mk_finite_set_range(Z3_context c, Z3_ast low, Z3_ast high)
Create a finite set of integers in the range [low, high].
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_sort Z3_API Z3_mk_type_variable(Z3_context c, Z3_symbol s)
Create a type variable.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
void Z3_API Z3_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value)
add a function entry to a function interpretation.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_ast Z3_API Z3_mk_as_array(Z3_context c, Z3_func_decl f)
Create array with the same interpretation as a function. The array satisfies the property (f x) = (se...
Z3_string Z3_API Z3_get_numeral_binary_string(Z3_context c, Z3_ast a)
Return numeral value, as a binary string of a numeric constant term.
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
double Z3_API Z3_get_numeral_double(Z3_context c, Z3_ast a)
Return numeral as a double.
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_symbol Z3_API Z3_get_quantifier_id(Z3_context c, Z3_ast a)
Obtain id of quantifier.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
_py2expr(a, ctx=None)
Definition z3py.py:3289
RotateRight(a, b)
Definition z3py.py:4543
_symbol2py(ctx, s)
Definition z3py.py:140
BitVecVal(val, bv, ctx=None)
Definition z3py.py:4193
BVSNegNoOverflow(a)
Definition z3py.py:4729
SetAdd(s, e)
Definition z3py.py:5223
SetSort(s)
Sets.
Definition z3py.py:5166
_coerce_exprs(a, b, ctx=None)
Definition z3py.py:1308
UGT(a, b)
Definition z3py.py:4414
is_probe(p)
Definition z3py.py:9456
SetDel(s, e)
Definition z3py.py:5236
bool is_le(Any a)
Definition z3py.py:3029
BoolSort(ctx=None)
Definition z3py.py:1830
is_bv_sort(s)
Definition z3py.py:3644
_ctx_from_ast_args(*args)
Definition z3py.py:542
RatVal(a, b, ctx=None)
Definition z3py.py:3381
_to_func_decl_ref(a, ctx)
Definition z3py.py:964
SetUnion(*args)
Definition z3py.py:5191
_valid_accessor(acc)
Datatypes.
Definition z3py.py:5521
BitVec(name, bv, ctx=None)
Definition z3py.py:4210
EmptySet(s)
Definition z3py.py:5171
BVMulNoUnderflow(a, b)
Definition z3py.py:4743
CreateDatatypes(*ds)
Definition z3py.py:5656
is_func_decl(a)
Definition z3py.py:909
FiniteSetUnion(s1, s2)
Definition z3py.py:5414
get_as_array_func(n)
Definition z3py.py:7346
Distinct(*args)
Definition z3py.py:1513
RecAddDefinition(f, args, body)
Definition z3py.py:986
ToInt(a)
Definition z3py.py:3544
Implies(a, b, ctx=None)
Definition z3py.py:1924
UGE(a, b)
Definition z3py.py:4396
Ext(a, b)
Definition z3py.py:5105
_to_ast_array(args)
Definition z3py.py:554
bool is_sort(Any s)
Definition z3py.py:682
_check_bv_args(a, b)
Definition z3py.py:4355
RealSort(ctx=None)
Definition z3py.py:3321
IsSubset(a, b)
Definition z3py.py:5285
DeclareTypeVar(name, ctx=None)
Definition z3py.py:760
_get_args_ast_list(args)
Definition z3py.py:168
bool is_to_real(Any a)
Definition z3py.py:3089
_to_ref_array(ref, args)
Definition z3py.py:562
get_map_func(a)
Definition z3py.py:4911
is_finite_set(a)
Definition z3py.py:5346
_z3_check_cint_overflow(n, name)
Definition z3py.py:118
bool is_and(Any a)
Definition z3py.py:1760
TupleSort(name, sorts, ctx=None)
Definition z3py.py:5977
_coerce_expr_list(alist, ctx=None)
Definition z3py.py:1339
is_select(a)
Definition z3py.py:5135
SignExt(n, a)
Definition z3py.py:4559
Int(name, ctx=None)
Definition z3py.py:3414
Bools(names, ctx=None)
Definition z3py.py:1879
_probe_and(args, ctx)
Definition z3py.py:9523
Int2BV(a, num_bits)
Definition z3py.py:4169
Lambda(vs, body)
Definition z3py.py:2410
_to_param_value(val)
Definition z3py.py:178
FreshFunction(*sig)
Definition z3py.py:945
RealVector(prefix, sz, ctx=None)
Definition z3py.py:3495
BVRedOr(a)
Definition z3py.py:4648
is_finite_set_sort(s)
Definition z3py.py:5357
SRem(a, b)
Definition z3py.py:4474
FiniteSetFilter(f, set)
Definition z3py.py:5493
SortRef _sort(Context ctx, Any a)
Definition z3py.py:728
set_option(*args, **kws)
Definition z3py.py:328
ExprRef RealVar(int idx, ctx=None)
Definition z3py.py:1596
bool is_sub(Any a)
Definition z3py.py:2976
is_bv(a)
Definition z3py.py:4117
SetDifference(a, b)
Definition z3py.py:5259
bool is_arith_sort(Any s)
Definition z3py.py:2513
BitVecs(names, bv, ctx=None)
Definition z3py.py:4234
_check_same_sort(a, b, ctx=None)
Definition z3py.py:1295
bool is_mod(Any a)
Definition z3py.py:3017
BoolVector(prefix, sz, ctx=None)
Definition z3py.py:1895
FiniteSetEmpty(set_sort)
Definition z3py.py:5395
_has_probe(args)
Definition z3py.py:1980
IsMember(e, s)
Definition z3py.py:5272
get_param(name)
Definition z3py.py:334
BVAddNoUnderflow(a, b)
Definition z3py.py:4701
deserialize(st)
Definition z3py.py:1209
bool is_not(Any a)
Definition z3py.py:1796
BvXnor(a, b)
Definition z3py.py:4681
FiniteSetMap(f, set)
Definition z3py.py:5480
Extract(high, low, a)
Definition z3py.py:4301
Function(name, *sig)
Definition z3py.py:922
get_version()
Definition z3py.py:100
FreshConst(sort, prefix="c")
Definition z3py.py:1573
ULT(a, b)
Definition z3py.py:4378
EnumSort(name, values, ctx=None)
Definition z3py.py:6001
bool is_is_int(Any a)
Definition z3py.py:3077
_to_int_str(val)
Definition z3py.py:3338
is_algebraic_value(a)
Definition z3py.py:2938
is_bv_value(a)
Definition z3py.py:4131
BVSDivNoOverflow(a, b)
Definition z3py.py:4722
bool is_eq(Any a)
Definition z3py.py:1808
Context main_ctx()
Definition z3py.py:266
CreatePolymorphicDatatype(d, type_params)
Definition z3py.py:5752
BvNand(a, b)
Definition z3py.py:4655
SetIntersect(*args)
Definition z3py.py:5207
simplify(a, *arguments, **keywords)
Utils.
Definition z3py.py:9590
BV2Int(a, is_signed=False)
Definition z3py.py:4146
FreshInt(prefix="x", ctx=None)
Definition z3py.py:3453
_to_ast_ref(a, ctx)
Definition z3py.py:570
_to_func_decl_array(args)
Definition z3py.py:546
disable_trace(msg)
Definition z3py.py:87
bool is_to_int(Any a)
Definition z3py.py:3104
is_map(a)
Definition z3py.py:4886
Context _get_ctx(ctx)
Definition z3py.py:287
Or(*args)
Definition z3py.py:2021
is_re(s)
Definition z3py.py:12057
FiniteSetIntersect(s1, s2)
Definition z3py.py:5425
args2params(arguments, keywords, ctx=None)
Definition z3py.py:6080
bool is_idiv(Any a)
Definition z3py.py:3005
Consts(names, sort)
Definition z3py.py:1558
Cond(p, t1, t2, ctx=None)
Definition z3py.py:9573
_to_pattern(arg)
Definition z3py.py:2114
RealVarVector(int n, ctx=None)
Definition z3py.py:1606
is_arith(a)
Definition z3py.py:2825
bool is_true(Any a)
Definition z3py.py:1728
bool is_false(Any a)
Definition z3py.py:1746
bool is_int(a)
Definition z3py.py:2846
If(a, b, c, ctx=None)
Definition z3py.py:1490
bool eq(AstRef a, AstRef b)
Definition z3py.py:503
is_app_of(a, k)
Definition z3py.py:1477
is_app(a)
Definition z3py.py:1374
bool is_add(Any a)
Definition z3py.py:2952
z3_error_handler(c, e)
Definition z3py.py:184
None reset_params()
Definition z3py.py:322
Reals(names, ctx=None)
Definition z3py.py:3480
is_int_value(a)
Definition z3py.py:2892
set_param(*args, **kws)
Definition z3py.py:298
is_pattern(a)
Definition z3py.py:2072
_coerce_seq(s, ctx=None)
Definition z3py.py:11708
bool is_distinct(Any a)
Definition z3py.py:1818
bool is_lt(Any a)
Definition z3py.py:3041
FiniteSetRange(low, high)
Definition z3py.py:5506
ULE(a, b)
Definition z3py.py:4360
is_real(a)
Definition z3py.py:2865
Abs(arg)
Definition z3py.py:9751
FullSet(s)
Definition z3py.py:5182
to_symbol(s, ctx=None)
Definition z3py.py:132
FiniteSetMember(elem, set)
Definition z3py.py:5447
bool is_mul(Any a)
Definition z3py.py:2964
bool is_ast(Any a)
Definition z3py.py:482
_get_args(args)
Definition z3py.py:152
Singleton(elem)
Definition z3py.py:5405
And(*args)
Definition z3py.py:1988
RepeatBitVec(n, a)
Definition z3py.py:4617
FiniteSetDifference(s1, s2)
Definition z3py.py:5436
get_version_string()
Definition z3py.py:91
FreshReal(prefix="b", ctx=None)
Definition z3py.py:3510
Array(name, *sorts)
Definition z3py.py:4970
Concat(*args)
Definition z3py.py:4255
_reduce(func, sequence, initial)
Definition z3py.py:1332
_is_algebraic(ctx, a)
Definition z3py.py:2888
Ints(names, ctx=None)
Definition z3py.py:3427
Select(a, *args)
Definition z3py.py:5044
Const(name, sort)
Definition z3py.py:1546
is_array_sort(a)
Definition z3py.py:4842
bool is_div(Any a)
Definition z3py.py:2988
ExprRef Var(int idx, SortRef s)
Definition z3py.py:1581
BVAddNoOverflow(a, b, signed)
Definition z3py.py:4694
BvNor(a, b)
Definition z3py.py:4668
Real(name, ctx=None)
Definition z3py.py:3467
FreshBool(prefix="b", ctx=None)
Definition z3py.py:1910
BitVecSort(sz, ctx=None)
Definition z3py.py:4178
open_log(fname)
Definition z3py.py:122
RecFunction(name, *sig)
Definition z3py.py:968
FiniteSetSize(set)
Definition z3py.py:5459
bool is_ge(Any a)
Definition z3py.py:3053
Model(ctx=None, eval={})
Definition z3py.py:7333
BVSubNoOverflow(a, b)
Definition z3py.py:4708
bool is_gt(Any a)
Definition z3py.py:3065
In(elem, set)
Definition z3py.py:5456
is_default(a)
Definition z3py.py:4902
is_K(a)
Definition z3py.py:4873
Bool(name, ctx=None)
Definition z3py.py:1867
_is_int(v)
Definition z3py.py:76
is_const_array(a)
Definition z3py.py:4860
Sqrt(a, ctx=None)
Definition z3py.py:3579
FiniteSetSort(elem_sort)
Definition z3py.py:5386
Default(a)
Definition z3py.py:5016
_ctx_from_ast_arg_list(args, default_ctx=None)
Definition z3py.py:528
SetComplement(s)
Definition z3py.py:5249
is_as_array(n)
Definition z3py.py:7341
is_store(a)
Definition z3py.py:5148
FiniteSetSubset(s1, s2)
Definition z3py.py:5469
bool is_or(Any a)
Definition z3py.py:1772
is_quantifier(a)
Definition z3py.py:2322
_mk_bin(f, a, b)
Definition z3py.py:1537
K(dom, v)
Definition z3py.py:5083
Xor(a, b, ctx=None)
Definition z3py.py:1938
Store(a, *args)
Definition z3py.py:5027
bool is_array(Any a)
Definition z3py.py:4846
mk_not(a)
Definition z3py.py:1973
is_expr(a)
Definition z3py.py:1351
_array_select(ar, arg)
Definition z3py.py:4833
is_const(a)
Definition z3py.py:1400
BoolVal(val, ctx=None)
Definition z3py.py:1848
RealVal(val, ctx=None)
Definition z3py.py:3362
bool is_implies(Any a)
Definition z3py.py:1784
z3_debug()
Definition z3py.py:70
get_full_version()
Definition z3py.py:109
IntVector(prefix, sz, ctx=None)
Definition z3py.py:3440
_coerce_expr_merge(s, a)
Definition z3py.py:1277
Context get_ctx(ctx)
Definition z3py.py:294
LShR(a, b)
Definition z3py.py:4495
ArraySort(*sig)
Definition z3py.py:4935
Map(f, *args)
Definition z3py.py:5060
is_rational_value(a)
Definition z3py.py:2916
_probe_or(args, ctx)
Definition z3py.py:9527
BVRedAnd(a)
Definition z3py.py:4641
Cbrt(a, ctx=None)
Definition z3py.py:3592
_to_expr_ref(a, ctx)
Definition z3py.py:1223
DisjointSum(name, sorts, ctx=None)
Definition z3py.py:5989
IntSort(ctx=None)
Definition z3py.py:3304
is_seq(a)
Definition z3py.py:11729
Not(a, ctx=None)
Definition z3py.py:1954
_to_sort_ref(s, ctx)
Definition z3py.py:695
enable_trace(msg)
Definition z3py.py:83
Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2389
ToReal(a)
Definition z3py.py:3524
URem(a, b)
Definition z3py.py:4453
bool is_bool(Any a)
Definition z3py.py:1710
StringVal(s, ctx=None)
Definition z3py.py:11756
IsInt(a)
Definition z3py.py:3562
_is_numeral(ctx, a)
Definition z3py.py:2884
MultiPattern(*args)
Definition z3py.py:2090
ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2371
ZeroExt(n, a)
Definition z3py.py:4589
_sort_kind(ctx, s)
Sorts.
Definition z3py.py:586
int _ast_kind(Context ctx, Any a)
Definition z3py.py:522
DatatypeSort(name, params=None, ctx=None)
Definition z3py.py:5952
BVSubNoUnderflow(a, b, signed)
Definition z3py.py:4715
UDiv(a, b)
Definition z3py.py:4432
Q(a, b, ctx=None)
Definition z3py.py:3401
Update(a, *args)
Definition z3py.py:4984
get_var_index(a)
Definition z3py.py:1444
append_log(s)
Definition z3py.py:127
AsArray(f)
Definition z3py.py:5117
is_var(a)
Definition z3py.py:1419
SortRef DeclareSort(name, ctx=None)
Definition z3py.py:732
IntVal(val, ctx=None)
Definition z3py.py:3350
BVMulNoOverflow(a, b, signed)
Definition z3py.py:4736
RotateLeft(a, b)
Definition z3py.py:4527
_mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition z3py.py:2336
_z3_assert(cond, msg)
Definition z3py.py:113