-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcvc5_pythonic.py
More file actions
9623 lines (7795 loc) · 242 KB
/
cvc5_pythonic.py
File metadata and controls
9623 lines (7795 loc) · 242 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
############################################
# Copyright (c) 2021 The cvc5 Developers
# 2012 The Microsoft Corporation
#
# cvc5's Z3-compatible Python interface
#
# Author: Alex Ozdemir (aozdemir)
# pyz3 Author: Leonardo de Moura (leonardo)
############################################
"""
cvc5 is an SMT solver.
This is its pythonic API that is (as much as possible) Z3-compatible.
Several online tutorials for Z3Py are available at:
http://rise4fun.com/Z3Py/tutorial/guide
Please send feedback, comments and/or corrections on the Issue tracker for
https://github.com/cvc5/cvc5.git. Your comments are very valuable.
Small example:
>>> x = Int('x')
>>> y = Int('y')
>>> s = Solver()
>>> s.add(x > 0)
>>> s.add(x < 2)
>>> s.add(y == x + 1)
>>> s.check()
sat
>>> m = s.model()
>>> m[x]
1
>>> m[y]
2
SMT exceptions:
>>> try:
... x = BitVec('x', 32)
... y = Bool('y')
... # the expression x + y is type incorrect
... n = x + y
... except SMTException as ex:
... print("failed: %s" % ex)
failed: sort mismatch
Differences with Z3py:
* Missing features:
* Patterns
* Models for uninterpreted sorts
* The `Model` function
* In our API, this function returns an object whose only method is `evaluate`.
* Pseudo-boolean counting constraints
* AtMost, AtLeast, PbLe, PbGe, PbEq
* HTML integration
* User propagation hooks
* Special relations:
* PartialOrder, LinearOrder, TreeOrder, PiecewiseLinearOrder, TransitiveClosure
* Optimization
* FiniteDomainSort
* Fixedpoint API
* SMT2 file support
* Not missing, but different
* Options
* as expected
* Some pretty printing
"""
from .cvc5_pythonic_printer import *
from fractions import Fraction
from decimal import Decimal
import ctypes
import decimal
import sys
import math
import io
import functools as ft
import operator as op
import cvc5 as pc
from cvc5 import Kind
DEBUG = __debug__
def debugging():
global DEBUG
return DEBUG
def _is_int(v):
"""int testing"""
return isinstance(v, int)
def unimplemented(msg):
raise SMTException("Unimplemented: {}".format(msg))
class SMTException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
# We use _assert instead of the assert command because we want to
# use our own exception class
def _assert(cond, msg):
if not cond:
raise SMTException(msg)
# Hack for having nary functions that can receive one argument that is the
# list of arguments.
# Use this when function takes a single list of arguments
def _get_args(args):
if len(args) == 1 and isinstance(args[0], (list, tuple)):
return list(args[0])
else:
return list(args)
class Context(object):
"""A Context manages all terms, configurations, etc.
In z3's API, a context owns terms, sorts, and solvers. It is used to create
them. Terms/sorts/solvers from one context cannot be implicitly used in
another. Items *can* be explicitly transfered between contexts. The result
is that essentially all functions have a context threaded through them.
There is a default "main" context.
Similarly, terms and sorts are created using a term manager in cvc5's API.
Our compatibility solution is:
* a context wraps a term manager, so that a context can be used to create terms
* also, a context does these things:
* making fresh identifiers for a given sort
* looking up previously defined constants
"""
def __init__(self):
self.tm = pc.TermManager()
# Map from (name, sort) pairs to constant terms
self.vars = {}
# An increasing identifier used to make fresh identifiers
self.next_fresh_var = 0
# Function definitions to be added to a solver once it is created
self.defined_functions = []
def __del__(self):
self.tm = None
def get_var(self, name, sort):
"""Get the variable identified by `name`.
If no variable of that name (with that sort) has been created, creates
one.
Returns a Term
"""
if (name, sort) not in self.vars:
self.vars[(name, sort)] = self.tm.mkConst(sort.ast, name)
return self.vars[(name, sort)]
def next_fresh(self, sort, prefix):
"""Make a name such that (name, sort) is fresh.
The name will be prefixed by `prefix`"""
name = "{}{}".format(prefix, self.next_fresh_var)
while (name, sort) in self.vars:
self.next_fresh_var += 1
name = "{}{}".format(prefix, self.next_fresh_var)
return name
def __eq__(self, o):
return self.tm is o.tm
# Global SMT context
_main_ctx = None
def main_ctx():
"""Return a reference to the global context.
>>> x = Real('x')
>>> x.ctx == main_ctx()
True
"""
# Pending multiple solvers
# >>> c = Context()
# >>> c == main_ctx()
# False
# >>> x2 = Real('x', c)
# >>> x2.ctx == c
# True
# >>> eq(x, x2)
# False
global _main_ctx
if _main_ctx is None:
_main_ctx = Context()
return _main_ctx
def _get_ctx(ctx):
if ctx is None:
return main_ctx()
else:
return ctx
def get_ctx(ctx):
"""
Returns `ctx` if it is not `None`, and the default context otherwise.
>>> get_ctx(None) is main_ctx()
True
>>> get_ctx(main_ctx()) is main_ctx()
True
"""
return _get_ctx(ctx)
#########################################
#
# Term base class
#
#########################################
class ExprRef(object):
"""Constraints, formulas and terms are expressions."""
def __init__(self, ast, ctx=None, reverse_children=False):
self.ast = ast
self.ctx = _get_ctx(ctx)
self.reverse_children = reverse_children
assert isinstance(self.ast, pc.Term)
assert isinstance(self.ctx, Context)
def __del__(self):
if self.ctx is not None and self.ast is not None:
self.ctx = None
self.ast = None
def __str__(self):
return obj_to_string(self)
def __repr__(self):
return obj_to_string(self)
def __nonzero__(self):
"""Convert this expression to a python boolean. See __bool__.
>>> (BoolVal(False) == BoolVal(False)).__nonzero__()
True
"""
return self.__bool__()
def __bool__(self):
"""Convert this expression to a python boolean.
Produces
* the appropriate value for a BoolVal.
* whether structural equality holds for an EQ-node
>>> bool(BoolVal(True))
True
>>> bool(BoolVal(False))
False
>>> bool(BoolVal(False) == BoolVal(False))
True
>>> try:
... bool(Int('y'))
... except SMTException as ex:
... print("failed: %s" % ex)
failed: Symbolic expressions cannot be cast to concrete Boolean values.
"""
if is_true(self):
return True
elif is_false(self):
return False
elif is_eq(self) and self.num_args() == 2:
# Special case so that expressions bool(x == y) yield a Python boolean.
# This is critical because
# 1) We want x == y to be symbolic AND
# 2) we want symbolic terms to be hashable
# - in Python, hashable objects must support == that returns
# something castable to a Python boolean via __bool__.
return self.arg(0).eq(self.arg(1))
else:
raise SMTException(
"Symbolic expressions cannot be cast to concrete Boolean values."
)
def sexpr(self):
"""Return a string representing the AST node in s-expression notation.
>>> x = Int('x')
>>> ((x + 1)*x).sexpr()
'(* (+ x 1) x)'
"""
return str(self.ast)
def as_ast(self):
"""Return a pointer to the underlying Term object."""
return self.ast
def get_id(self):
"""Return unique identifier for object.
It can be used for hash-tables and maps.
>>> BoolVal(True).get_id() == BoolVal(True).get_id()
True
"""
return self.ast.getId()
def eq(self, other):
"""Return `True` if `self` and `other` are structurally identical.
>>> x = Int('x')
>>> n1 = x + 1
>>> n2 = 1 + x
>>> n1.eq(n2)
False
"""
if debugging():
_assert(is_ast(other), "SMT AST expected")
return self.ctx == other.ctx and self.as_ast() == other.as_ast()
def hash(self):
"""Return a hashcode for the `self`.
>>> n1 = Int('x') + 1
>>> n2 = Int('x') + 1
>>> n1.hash() == n2.hash()
True
"""
return self.as_ast().__hash__()
def sort(self):
"""Return the sort of expression `self`.
>>> x = Int('x')
>>> (x + 1).sort()
Int
>>> y = Real('y')
>>> (x + y).sort()
Real
"""
return _sort(self.ctx, self.ast)
def __eq__(self, other):
"""Return an SMT expression that represents the constraint `self == other`.
If `other` is `None`, then this method simply returns `False`.
>>> a = Int('a')
>>> b = Int('b')
>>> a == b
a == b
>>> a is None
False
>>> a == None
False
"""
if other is None:
return False
a, b = _coerce_exprs(self, other)
c = self.ctx
return BoolRef(c.tm.mkTerm(Kind.EQUAL, a.as_ast(), b.as_ast()), c)
def __hash__(self):
"""Hash code."""
return self.ast.__hash__()
def __ne__(self, other):
"""Return an SMT expression that represents the constraint `self != other`.
If `other` is `None`, then this method simply returns `True`.
>>> a = Int('a')
>>> b = Int('b')
>>> a != b
a != b
>>> a is not None
True
>>> a != None
True
"""
if other is None:
return True
a, b = _coerce_exprs(self, other)
c = self.ctx
return BoolRef(c.tm.mkTerm(Kind.DISTINCT, a.as_ast(), b.as_ast()), c)
def decl(self):
"""Return the SMT function declaration associated with an SMT application.
>>> f = Function('f', IntSort(), IntSort())
>>> a = Int('a')
>>> t = f(a)
>>> eq(t.decl(), f)
True
>>> try:
... Int('y').decl()
... except SMTException as ex:
... print("failed: %s" % ex)
failed: Declarations for non-function applications
"""
if is_app_of(self, Kind.APPLY_UF):
return _to_expr_ref(list(self.ast)[0], self.ctx) # type: ignore
else:
raise SMTException("Declarations for non-function applications")
def kind(self):
"""Return the Kind of this term
>>> f = Function('f', IntSort(), IntSort())
>>> a = Int('a')
>>> t = f(a)
>>> t.kind() == Kind.APPLY_UF
True
"""
return self.ast.getKind()
def num_args(self):
"""Return the number of arguments of an SMT application.
>>> a = Int('a')
>>> b = Int('b')
>>> (a + b).num_args()
2
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.num_args()
3
"""
if debugging():
_assert(is_app(self), "SMT application expected")
if is_app_of(self, Kind.APPLY_UF):
return len(list(self.as_ast())) - 1 # type: ignore
else:
return len(list(self.as_ast())) # type: ignore
def arg(self, idx):
"""Return argument `idx` of the application `self`.
This method assumes that `self` is a function application with at least
`idx+1` arguments.
>>> a = Int('a')
>>> b = Int('b')
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.arg(0)
a
>>> t.arg(1)
b
>>> t.arg(2)
0
"""
if debugging():
_assert(is_app(self), "SMT application expected")
_assert(idx < self.num_args(), "Invalid argument index")
if is_app_of(self, Kind.APPLY_UF):
return _to_expr_ref(self.as_ast()[idx + 1], self.ctx)
elif self.reverse_children:
return _to_expr_ref(self.as_ast()[self.num_args() - (idx + 1)], self.ctx)
else:
return _to_expr_ref(self.as_ast()[idx], self.ctx)
def children(self):
"""Return a list containing the children of the given expression
>>> a = Int('a')
>>> b = Int('b')
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.children()
[a, b, 0]
"""
if is_app_of(self, Kind.APPLY_UF):
return [_to_expr_ref(a, self.ctx) for a in list(self.ast)[1:]] # type: ignore
else:
if is_app(self):
args = list(self.ast) # type: ignore
if self.reverse_children:
args = reversed(args)
return [_to_expr_ref(a, self.ctx) for a in args]
else:
return []
def is_int(self):
"""Return `True` if `self` is of the sort Integer.
>>> x = Int('x')
>>> x.is_int()
True
>>> (x + 1).is_int()
True
>>> x = Real('x')
>>> x.is_int()
False
>>> Set('x', IntSort()).is_int()
False
"""
return False
def is_ast(a):
"""Return `True` for expressions and sorts.
Exposed by the Z3 API. Less relevant to us.
>>> is_ast(10)
False
>>> is_ast(IntVal(10))
True
>>> is_ast(Int('x'))
True
>>> is_ast(BoolSort())
True
>>> is_ast(Function('f', IntSort(), IntSort()))
True
>>> is_ast("x")
False
>>> is_ast(Solver())
False
"""
return isinstance(a, (ExprRef, SortRef))
def eq(a, b):
"""Return `True` if `a` and `b` are structurally identical AST nodes.
>>> x = Int('x')
>>> y = Int('y')
>>> eq(x, y)
False
>>> eq(x + 1, x + 1)
True
>>> eq(x + 1, 1 + x)
False
"""
if debugging():
_assert(is_ast(a) and is_ast(b), "SMT ASTs expected")
return a.eq(b)
def _ctx_from_ast_arg_list(args, default_ctx=None):
ctx = None
for a in args:
if is_ast(a):
if ctx is None:
ctx = a.ctx
if ctx is None:
ctx = default_ctx
return ctx
#########################################
#
# Sorts
#
#########################################
class SortRef(object):
"""A Sort is essentially a type. Every term has a sort"""
def __init__(self, ast, ctx=None):
self.ast = ast
self.ctx = _get_ctx(ctx)
assert isinstance(self.ast, pc.Sort)
assert isinstance(self.ctx, Context)
def __del__(self):
if self.ctx is not None:
self.ctx = None
if self.ast is not None:
self.ast = None
def __str__(self):
"""
A pretty-printed representation of this sort.
>>> str(IntSort())
'Int'
"""
return obj_to_string(self)
def __repr__(self):
"""
A pretty-printed representation of this sort.
>>> repr(IntSort())
'Int'
"""
return obj_to_string(self)
def __eq__(self, other):
return self.ast == other.ast
def sexpr(self):
"""Return a string representing the AST node in s-expression notation.
>>> IntSort().sexpr()
'Int'
"""
return str(self.ast)
def as_ast(self):
"""Return a pointer to the underlying Sort object."""
return self.ast
def eq(self, other):
"""Return `True` if `self` and `other` are structurally identical.
>>> x = Int('x')
>>> n1 = x + 1
>>> n2 = 1 + x
>>> n1.eq(n2)
False
>>> n1.eq(x + 1)
True
"""
instance_check(other, SortRef)
return self.as_ast() == other.as_ast()
def hash(self):
"""Return a hashcode for the `self`.
>>> n1 = IntSort()
>>> n2 = RealSort()
>>> n1.hash() == n2.hash()
False
"""
return self.as_ast().__hash__()
def subsort(self, other):
"""Return `True` if `self` is a subsort of `other`.
>>> IntSort().subsort(RealSort())
True
>>> BoolSort().subsort(RealSort())
True
>>> SetSort(BitVecSort(2)).subsort(SetSort(IntSort()))
False
"""
# subclasses override
return False
def cast(self, val):
"""Try to cast `val` as an element of sort `self`.
This method is used in SMT to convert Python objects such as integers,
floats, longs and strings into SMT expressions.
>>> x = Int('x')
>>> RealSort().cast(x)
ToReal(x)
"""
if debugging():
_assert(is_expr(val), "SMT expression expected")
_assert(self.eq(val.sort()), "Sort mismatch")
# subclasses override
return val
def name(self):
"""Return the name (string) of sort `self`.
>>> BoolSort().name()
'Bool'
>>> ArraySort(IntSort(), IntSort()).name()
'(Array Int Int)'
"""
return str(self.ast)
def __ne__(self, other):
"""Return `True` if `self` and `other` are not the same SMT sort.
>>> p = Bool('p')
>>> p.sort() != BoolSort()
False
>>> p.sort() != IntSort()
True
"""
return self.ast != other.ast
def __hash__(self):
"""Hash code."""
return self.ast.__hash__()
def is_int(self):
"""
Subclasses override
>>> SetSort(IntSort()).is_int()
False
"""
return False
def is_bool(self):
return False
def _sort(ctx, a):
instance_check(a, pc.Term)
return _to_sort_ref(a.getSort(), ctx)
def DeclareSort(name, ctx=None):
"""Create a new uninterpreted sort named `name`.
If `ctx=None`, then the new sort is declared in the global SMT context.
>>> A = DeclareSort('A')
>>> a = Const('a', A)
>>> b = Const('b', A)
>>> a.sort() == A
True
>>> b.sort() == A
True
>>> a == b
a == b
>>> solve(a == b)
[a = (as @A_0 A), b = (as @A_0 A)]
"""
ctx = _get_ctx(ctx)
return SortRef(ctx.tm.mkUninterpretedSort(name), ctx)
def is_sort(s):
"""Return `True` if `s` is an SMT sort.
>>> is_sort(IntSort())
True
>>> is_sort(Int('x'))
False
>>> is_expr(Int('x'))
True
"""
return isinstance(s, SortRef)
def instance_check(item, instance):
_assert(
isinstance(item, instance),
"Expected {}, but got a {}".format(instance, type(item)),
)
def _to_sort_ref(s, ctx):
"""Construct the correct SortRef subclass for `s`
s must be a base Sort.
"""
if debugging():
instance_check(s, pc.Sort)
if s.isString():
return StringSortRef(s, ctx)
if s.isSequence():
return SeqSortRef(s, ctx)
if s.isBoolean():
return BoolSortRef(s, ctx)
elif s.isInteger() or s.isReal():
return ArithSortRef(s, ctx)
elif s.isBitVector():
return BitVecSortRef(s, ctx)
elif s.isFiniteField():
return FiniteFieldSortRef(s, ctx)
elif s.isArray():
return ArraySortRef(s, ctx)
elif s.isSet():
return SetSortRef(s, ctx)
elif s.isFloatingPoint():
return FPSortRef(s, ctx)
elif s.isRoundingMode():
return FPRMSortRef(s, ctx)
return SortRef(s, ctx)
#########################################
#
# Function Declarations
#
#########################################
class FuncDeclRef(ExprRef):
"""Function declaration.
Every constant and function have an associated declaration.
The declaration assigns a name, a sort (i.e., type), and for function
the sort (i.e., type) of each of its arguments. Note that, in SMT,
a constant is a function with 0 arguments.
"""
def name(self):
"""Return the name of the function declaration `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> f.name()
'f'
>>> isinstance(f.name(), str)
True
"""
return str(self.ast)
def arity(self):
"""Return the number of arguments of a function declaration.
If `self` is a constant, then `self.arity()` is 0.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.arity()
2
"""
return self.ast.getSort().getFunctionArity()
def domain(self, i):
"""Return the sort of the argument `i` of a function declaration.
This method assumes that `0 <= i < self.arity()`.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.domain(0)
Int
>>> f.domain(1)
Real
"""
return _to_sort_ref(self.ast.getSort().getFunctionDomainSorts()[i], self.ctx)
def range(self):
"""Return the sort of the range of a function declaration.
For constants, this is the sort of the constant.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.range()
Bool
"""
return _to_sort_ref(self.ast.getSort().getFunctionCodomainSort(), self.ctx)
def __call__(self, *args):
"""Create an SMT application expression using the function `self`,
and the given arguments.
The arguments must be SMT expressions. This method assumes that
the sorts of the elements in `args` match the sorts of the
domain. Limited coercion is supported. For example, if
args[0] is a Python integer, and the function expects a SMT
integer, then the argument is automatically converted into a
SMT integer.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> x = Int('x')
>>> y = Real('y')
>>> f(x, y)
f(x, y)
>>> f(x, x)
f(x, ToReal(x))
"""
return _higherorder_apply(self, args, Kind.APPLY_UF)
def _higherorder_apply(func, args, kind):
"""Create an SMT application from a FuncDeclRef and a kind of application"""
args = _get_args(args)
num = len(args)
if debugging():
_assert(
num == func.arity(),
"Incorrect number of arguments to %s" % func,
)
_args = []
for i in range(num):
tmp = func.domain(i).cast(args[i])
_args.append(tmp.as_ast())
return _to_expr_ref(func.ctx.tm.mkTerm(kind, func.ast, *_args), func.ctx)
def is_func_decl(a):
"""Return `True` if `a` is an SMT function declaration.
>>> f = Function('f', IntSort(), IntSort())
>>> is_func_decl(f)
True
>>> x = Real('x')
>>> is_func_decl(x)
False
"""
return isinstance(a, FuncDeclRef)
def Function(name, *sig):
"""Create a new SMT uninterpreted function with the given sorts.
>>> f = Function('f', IntSort(), IntSort())
>>> f(f(0))
f(f(0))
"""
sig = _get_args(sig)
if debugging():
_assert(len(sig) > 0, "At least two arguments expected")
arity = len(sig) - 1
rng = sig[arity]
if debugging():
_assert(is_sort(rng), "SMT sort expected")
ctx = rng.ctx
sort = ctx.tm.mkFunctionSort([sig[i].ast for i in range(arity)], rng.ast)
e = ctx.get_var(name, _to_sort_ref(sort, ctx))
return FuncDeclRef(e, ctx)
def FreshFunction(*sig):
"""Create a new fresh SMT uninterpreted function with the given sorts.
>>> f = FreshFunction(IntSort(), IntSort())
>>> x = Int('x')
>>> solve([f(x) != f(x)])
no solution
"""
sig = _get_args(sig)
if debugging():
_assert(len(sig) > 0, "At least two arguments expected")
arity = len(sig) - 1
rng = sig[arity]
if debugging():
_assert(is_sort(rng), "SMT sort expected")
ctx = rng.ctx
sort = ctx.tm.mkFunctionSort([sig[i].ast for i in range(arity)], rng.ast)
name = ctx.next_fresh(sort, "freshfn")
return Function(name, *sig)
def RecFunction(name, *sig):
"""Create a new SMT uninterpreted function with the given sorts."""
return Function(name, sig)
def RecAddDefinition(func, args, body):
"""Define a new SMT recursive function with the given function declaration.
Replaces constants in `args` with bound variables.
>>> fact = Function('fact', IntSort(), IntSort())
>>> n = Int('n')
>>> RecAddDefinition(fact, n, If(n == 0, 1, n * fact(n - 1)))
>>> solve(Not(fact(5) == 120))
unsat
"""
if is_app(args):
args = [args]
ctx = func.ctx
consts = [a.ast for a in args]
vars_ = [ctx.tm.mkVar(a.sort().ast, str(a)) for a in args]
subbed_body = body.ast.substitute(consts, vars_)
ctx.defined_functions.append(((func.ast, vars_, subbed_body), True))
def AddDefinition(name, args, body):
"""Define a new SMT function with the given function declaration.
Replaces constants in `args` with bound variables.
>>> x, y = Ints('x y')
>>> minus = AddDefinition(minus, [x, y], x - y)
>>> solve(Not(minus(10, 5) == 5))
unsat
"""
if is_app(args):
args = [args]
ctx = body.ctx
consts = [a.ast for a in args]
vars_ = [ctx.tm.mkVar(a.sort().ast, str(a)) for a in args]
subbed_body = body.ast.substitute(consts, vars_)
ctx.defined_functions.append(
((name, vars_, subbed_body.getSort(), subbed_body), False)
)
#########################################
#
# Expressions
#
#########################################
def _to_expr_ref(a, ctx, r=None):
"""Construct the correct ExprRef subclass for `a`
a may be a base Term or a ExprRef.
Based on the underlying sort of a.
>>> _to_expr_ref(BoolVal(True), main_ctx())
True