-
Notifications
You must be signed in to change notification settings - Fork 7
/
vcg.py
1442 lines (1184 loc) · 55.1 KB
/
vcg.py
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
#!/usr/bin/env python3
#
# TRLC - Treat Requirements Like Code
# Copyright (C) 2023 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
# Copyright (C) 2023 Florian Schanda
#
# This file is part of the TRLC Python Reference Implementation.
#
# TRLC is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# TRLC is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with TRLC. If not, see <https://www.gnu.org/licenses/>.
import subprocess
from trlc.ast import *
from trlc.errors import Location, Message_Handler
try:
from pyvcg import smt
from pyvcg import graph
from pyvcg import vcg
from pyvcg.driver.file_smtlib import SMTLIB_Generator
from pyvcg.driver.cvc5_smtlib import CVC5_File_Solver
VCG_AVAILABLE = True
except ImportError: # pragma: no cover
VCG_AVAILABLE = False
try:
from pyvcg.driver.cvc5_api import CVC5_Solver
CVC5_API_AVAILABLE = True
except ImportError: # pragma: no cover
CVC5_API_AVAILABLE = False
CVC5_OPTIONS = {
"tlimit-per" : 2500,
"seed" : 42,
"sat-random-seed" : 42,
}
class Unsupported(Exception): # pragma: no cover
# lobster-exclude: Not safety relevant
def __init__(self, node, text):
assert isinstance(node, Node)
assert isinstance(text, str) or text is None
super().__init__()
self.message = "%s not yet supported in VCG" % \
(text if text else node.__class__.__name__)
self.location = node.location
class Feedback:
# lobster-exclude: Not safety relevant
def __init__(self, node, message, kind, expect_unsat=True):
assert isinstance(node, Expression)
assert isinstance(message, str)
assert isinstance(kind, str)
assert isinstance(expect_unsat, bool)
self.node = node
self.message = message
self.kind = "vcg-" + kind
self.expect_unsat = expect_unsat
class VCG:
# lobster-exclude: Not safety relevant
def __init__(self, mh, n_ctyp, debug, use_api=True, cvc5_binary=None):
assert VCG_AVAILABLE
assert isinstance(mh, Message_Handler)
assert isinstance(n_ctyp, Composite_Type)
assert isinstance(debug, bool)
assert isinstance(use_api, bool)
assert use_api or isinstance(cvc5_binary, str)
self.mh = mh
self.n_ctyp = n_ctyp
self.debug = debug
self.use_api = use_api
self.cvc5_bin = cvc5_binary
self.vc_name = "trlc-%s-%s" % (n_ctyp.n_package.name,
n_ctyp.name)
self.tmp_id = 0
self.vcg = vcg.VCG()
self.graph = self.vcg.graph
self.start = self.vcg.start
# Current start node, we will update this as we go along.
self.preamble = None
# We do remember the first node where we put all our
# declarations, in case we need to add some more later.
self.constants = {}
self.enumerations = {}
self.tuples = {}
self.arrays = {}
self.bound_vars = {}
self.qe_vars = {}
self.tuple_base = {}
self.uf_matches = None
# Pointer to the UF we use for matches. We only generate it
# when we must, as it may affect the logics selected due to
# string theory being used.
self.functional = False
# If set to true, then we ignore validity checks and do not
# create intermediates. We just build the value and validity
# expresions and return them.
self.emit_checks = True
# If set to false, we skip creating checks.
@staticmethod
def flag_unsupported(node, text=None): # pragma: no cover
assert isinstance(node, Node)
raise Unsupported(node, text)
def new_temp_name(self):
self.tmp_id += 1
return "tmp.%u" % self.tmp_id
def get_uf_matches(self):
if self.uf_matches is None:
self.uf_matches = \
smt.Function("trlc.matches",
smt.BUILTIN_BOOLEAN,
smt.Bound_Variable(smt.BUILTIN_STRING,
"subject"),
smt.Bound_Variable(smt.BUILTIN_STRING,
"regex"))
# Create UF for the matches function (for now, later we
# will deal with regex properly).
self.preamble.add_statement(
smt.Function_Declaration(self.uf_matches))
return self.uf_matches
def create_return(self, node, s_value, s_valid=None):
assert isinstance(node, Expression)
assert isinstance(s_value, smt.Expression)
assert isinstance(s_valid, smt.Expression) or s_valid is None
if s_valid is None:
s_valid = smt.Boolean_Literal(True)
if self.functional:
return s_value, s_valid
else:
sym_result = smt.Constant(s_value.sort,
self.new_temp_name())
self.attach_temp_declaration(node, sym_result, s_value)
return sym_result, s_valid
def attach_validity_check(self, bool_expr, origin):
assert isinstance(bool_expr, smt.Expression)
assert bool_expr.sort is smt.BUILTIN_BOOLEAN
assert isinstance(origin, Expression)
assert not self.functional
if not self.emit_checks:
return
# Attach new graph node advance start
if not bool_expr.is_static_true():
gn_check = graph.Check(self.graph)
gn_check.add_goal(bool_expr,
Feedback(origin,
"expression could be null",
"evaluation-of-null"),
"validity check for %s" % origin.to_string())
self.start.add_edge_to(gn_check)
self.start = gn_check
def attach_int_division_check(self, int_expr, origin):
assert isinstance(int_expr, smt.Expression)
assert int_expr.sort is smt.BUILTIN_INTEGER
assert isinstance(origin, Expression)
assert not self.functional
if not self.emit_checks:
return
# Attach new graph node advance start
gn_check = graph.Check(self.graph)
gn_check.add_goal(
smt.Boolean_Negation(
smt.Comparison("=", int_expr, smt.Integer_Literal(0))),
Feedback(origin,
"divisor could be 0",
"div-by-zero"),
"division by zero check for %s" % origin.to_string())
self.start.add_edge_to(gn_check)
self.start = gn_check
def attach_real_division_check(self, real_expr, origin):
assert isinstance(real_expr, smt.Expression)
assert real_expr.sort is smt.BUILTIN_REAL
assert isinstance(origin, Expression)
assert not self.functional
if not self.emit_checks:
return
# Attach new graph node advance start
gn_check = graph.Check(self.graph)
gn_check.add_goal(
smt.Boolean_Negation(
smt.Comparison("=", real_expr, smt.Real_Literal(0))),
Feedback(origin,
"divisor could be 0.0",
"div-by-zero"),
"division by zero check for %s" % origin.to_string())
self.start.add_edge_to(gn_check)
self.start = gn_check
def attach_index_check(self, seq_expr, index_expr, origin):
assert isinstance(seq_expr, smt.Expression)
assert isinstance(seq_expr.sort, smt.Sequence_Sort)
assert isinstance(index_expr, smt.Expression)
assert index_expr.sort is smt.BUILTIN_INTEGER
assert isinstance(origin, Binary_Expression)
assert origin.operator == Binary_Operator.INDEX
assert not self.functional
if not self.emit_checks:
return
# Attach new graph node advance start
gn_check = graph.Check(self.graph)
gn_check.add_goal(
smt.Comparison(">=", index_expr, smt.Integer_Literal(0)),
Feedback(origin,
"array index could be less than 0",
"array-index"),
"index lower bound check for %s" % origin.to_string())
gn_check.add_goal(
smt.Comparison("<",
index_expr,
smt.Sequence_Length(seq_expr)),
Feedback(origin,
"array index could be larger than len(%s)" %
origin.n_lhs.to_string(),
"array-index"),
"index lower bound check for %s" % origin.to_string())
self.start.add_edge_to(gn_check)
self.start = gn_check
def attach_feasability_check(self, bool_expr, origin):
assert isinstance(bool_expr, smt.Expression)
assert bool_expr.sort is smt.BUILTIN_BOOLEAN
assert isinstance(origin, Expression)
assert not self.functional
if not self.emit_checks:
return
# Attach new graph node advance start
gn_check = graph.Check(self.graph)
gn_check.add_goal(bool_expr,
Feedback(origin,
"expression is always true",
"always-true",
expect_unsat = False),
"feasability check for %s" % origin.to_string())
self.start.add_edge_to(gn_check)
def attach_assumption(self, bool_expr):
assert isinstance(bool_expr, smt.Expression)
assert bool_expr.sort is smt.BUILTIN_BOOLEAN
assert not self.functional
# Attach new graph node advance start
gn_ass = graph.Assumption(self.graph)
gn_ass.add_statement(smt.Assertion(bool_expr))
self.start.add_edge_to(gn_ass)
self.start = gn_ass
def attach_temp_declaration(self, node, sym, value=None):
assert isinstance(node, (Expression, Action))
assert isinstance(sym, smt.Constant)
assert isinstance(value, smt.Expression) or value is None
assert not self.functional
# Attach new graph node advance start
gn_decl = graph.Assumption(self.graph)
gn_decl.add_statement(
smt.Constant_Declaration(
symbol = sym,
value = value,
comment = "result of %s at %s" % (node.to_string(),
node.location.to_string()),
relevant = False))
self.start.add_edge_to(gn_decl)
self.start = gn_decl
def attach_empty_assumption(self):
assert not self.functional
# Attach new graph node advance start
gn_decl = graph.Assumption(self.graph)
self.start.add_edge_to(gn_decl)
self.start = gn_decl
def analyze(self):
try:
self.checks_on_composite_type(self.n_ctyp)
except Unsupported as exc: # pragma: no cover
self.mh.warning(exc.location,
exc.message)
def checks_on_composite_type(self, n_ctyp):
assert isinstance(n_ctyp, Composite_Type)
# Create node for global declarations
gn_locals = graph.Assumption(self.graph)
self.start.add_edge_to(gn_locals)
self.start = gn_locals
self.preamble = gn_locals
# Create local variables
for n_component in n_ctyp.all_components():
self.tr_component_decl(n_component, self.start)
# Create paths for checks
for n_check in n_ctyp.iter_checks():
current_start = self.start
self.tr_check(n_check)
# Only fatal checks contribute to the total knowledge
if n_check.severity != "fatal":
self.start = current_start
# Emit debug graph
if self.debug: # pragma: no cover
subprocess.run(["dot", "-Tpdf", "-o%s.pdf" % self.vc_name],
input = self.graph.debug_render_dot(),
check = True,
encoding = "UTF-8")
# Generate VCs
self.vcg.generate()
# Solve VCs and provide feedback
nok_feasibility_checks = []
ok_feasibility_checks = set()
nok_validity_checks = set()
for vc_id, vc in enumerate(self.vcg.vcs):
if self.debug: # pramga: no cover
with open(self.vc_name + "_%04u.smt2" % vc_id, "w",
encoding="UTF-8") as fd:
fd.write(vc["script"].generate_vc(SMTLIB_Generator()))
# Checks that have already failed don't need to be checked
# again on a different path
if vc["feedback"].expect_unsat and \
vc["feedback"] in nok_validity_checks:
continue
if self.use_api:
solver = CVC5_Solver()
else:
solver = CVC5_File_Solver(self.cvc5_bin)
for name, value in CVC5_OPTIONS.items():
solver.set_solver_option(name, value)
status, values = vc["script"].solve_vc(solver)
message = vc["feedback"].message
if self.debug: # pragma: no cover
message += " [vc_id = %u]" % vc_id
if vc["feedback"].expect_unsat:
if status != "unsat":
self.mh.check(vc["feedback"].node.location,
message,
vc["feedback"].kind,
self.create_counterexample(status,
values))
nok_validity_checks.add(vc["feedback"])
else:
if status == "unsat":
nok_feasibility_checks.append(vc["feedback"])
else:
ok_feasibility_checks.add(vc["feedback"])
# This is a bit wonky, but this way we make sure the ording is
# consistent
for feedback in nok_feasibility_checks:
if feedback not in ok_feasibility_checks:
self.mh.check(feedback.node.location,
feedback.message,
feedback.kind)
ok_feasibility_checks.add(feedback)
def create_counterexample(self, status, values):
rv = [
"example %s triggering error:" %
self.n_ctyp.__class__.__name__.lower(),
" %s bad_potato {" % self.n_ctyp.name
]
for n_component in self.n_ctyp.all_components():
id_value = self.tr_component_value_name(n_component)
id_valid = self.tr_component_valid_name(n_component)
if status == "unknown" and (id_value not in values or
id_valid not in values):
rv.append(" %s = ???" % n_component.name)
elif values.get(id_valid):
rv.append(" %s = %s" %
(n_component.name,
self.value_to_trlc(n_component.n_typ,
values[id_value])))
else:
rv.append(" /* %s is null */" % n_component.name)
rv.append(" }")
if status == "unknown":
rv.append("/* note: counter-example is unreliable in this case */")
return "\n".join(rv)
def fraction_to_decimal_string(self, num, den):
assert isinstance(num, int)
assert isinstance(den, int) and den >= 1
tmp = den
if tmp > 2:
while tmp > 1:
if tmp % 2 == 0:
tmp = tmp // 2
elif tmp % 5 == 0:
tmp = tmp // 5
else:
return "%i / %u" % (num, den)
rv = str(abs(num) // den)
i = abs(num) % den
j = den
if i > 0:
rv += "."
while i > 0:
i *= 10
rv += str(i // j)
i = i % j
else:
rv += ".0"
if num < 0:
return "-" + rv
else:
return rv
def value_to_trlc(self, n_typ, value):
assert isinstance(n_typ, Type)
if isinstance(n_typ, Builtin_Integer):
return str(value)
elif isinstance(n_typ, Builtin_Decimal):
if isinstance(value, Fraction):
num, den = value.as_integer_ratio()
if den >= 1:
return self.fraction_to_decimal_string(num, den)
else:
return self.fraction_to_decimal_string(-num, -den)
else:
return "/* unable to generate precise value */"
elif isinstance(n_typ, Builtin_Boolean):
return "true" if value else "false"
elif isinstance(n_typ, Enumeration_Type):
return n_typ.name + "." + value
elif isinstance(n_typ, Builtin_String):
if "\n" in value:
return "'''%s'''" % value
else:
return '"%s"' % value
elif isinstance(n_typ, Record_Type):
if value < 0:
instance_id = value * -2 - 1
else:
instance_id = value * 2
if n_typ.n_package is self.n_ctyp.n_package:
return "%s_instance_%i" % (n_typ.name, instance_id)
else:
return "%s.%s_instance_%i" % (n_typ.n_package.name,
n_typ.name,
instance_id)
elif isinstance(n_typ, Tuple_Type):
parts = []
for n_item in n_typ.iter_sequence():
if isinstance(n_item, Composite_Component):
if n_item.optional and not value[n_item.name + ".valid"]:
parts.pop()
break
parts.append(
self.value_to_trlc(n_item.n_typ,
value[n_item.name + ".value"]))
else:
assert isinstance(n_item, Separator)
sep_text = {
"AT" : "@",
"COLON" : ":",
"SEMICOLON" : ";"
}.get(n_item.token.kind, n_item.token.value)
parts.append(sep_text)
if n_typ.has_separators():
return "".join(parts)
else:
return "(%s)" % ", ".join(parts)
elif isinstance(n_typ, Array_Type):
return "[%s]" % ", ".join(self.value_to_trlc(n_typ.element_type,
item)
for item in value)
else: # pragma: no cover
self.flag_unsupported(n_typ,
"back-conversion from %s" % n_typ.name)
def tr_component_value_name(self, n_component):
return n_component.member_of.fully_qualified_name() + \
"." + n_component.name + ".value"
def tr_component_valid_name(self, n_component):
return n_component.member_of.fully_qualified_name() + \
"." + n_component.name + ".valid"
def emit_tuple_constraints(self, n_tuple, s_sym):
assert isinstance(n_tuple, Tuple_Type)
assert isinstance(s_sym, smt.Constant)
old_functional, self.functional = self.functional, True
self.tuple_base[n_tuple] = s_sym
constraints = []
# The first tuple constraint is that all checks must have
# passed, otherwise the tool would just error. An error in a
# tuple is pretty much the same as a fatal in the enclosing
# record.
for n_check in n_tuple.iter_checks():
if n_check.severity == "warning":
continue
# We do consider both fatal and errors to be sources of
# truth here.
c_value, _ = self.tr_expression(n_check.n_expr)
constraints.append(c_value)
# The secopnd tuple constraint is that once you get a null
# field, all following fields must also be null.
components = n_tuple.all_components()
for i, component in enumerate(components):
if component.optional:
condition = smt.Boolean_Negation(
smt.Record_Access(s_sym,
component.name + ".valid"))
consequences = [
smt.Boolean_Negation(
smt.Record_Access(s_sym,
c.name + ".valid"))
for c in components[i + 1:]
]
if len(consequences) == 0:
break
elif len(consequences) == 1:
consequence = consequences[0]
else:
consequence = smt.Conjunction(*consequences)
constraints.append(smt.Implication(condition, consequence))
del self.tuple_base[n_tuple]
self.functional = old_functional
for cons in constraints:
self.start.add_statement(smt.Assertion(cons))
def tr_component_decl(self, n_component, gn_locals):
assert isinstance(n_component, Composite_Component)
assert isinstance(gn_locals, graph.Assumption)
if isinstance(self.n_ctyp, Record_Type):
frozen = self.n_ctyp.is_frozen(n_component)
else:
frozen = False
id_value = self.tr_component_value_name(n_component)
s_sort = self.tr_type(n_component.n_typ)
s_sym = smt.Constant(s_sort, id_value)
if frozen:
old_functional, self.functional = self.functional, True
s_val, _ = self.tr_expression(
self.n_ctyp.get_freezing_expression(n_component))
self.functional = old_functional
else:
s_val = None
s_decl = smt.Constant_Declaration(
symbol = s_sym,
value = s_val,
comment = "value for %s declared on %s" % (
n_component.name,
n_component.location.to_string()),
relevant = True)
gn_locals.add_statement(s_decl)
self.constants[id_value] = s_sym
if isinstance(n_component.n_typ, Tuple_Type):
self.emit_tuple_constraints(n_component.n_typ, s_sym)
# For arrays we need to add additional constraints for the
# length
if isinstance(n_component.n_typ, Array_Type):
if n_component.n_typ.lower_bound > 0:
s_lower = smt.Integer_Literal(n_component.n_typ.lower_bound)
gn_locals.add_statement(
smt.Assertion(
smt.Comparison(">=",
smt.Sequence_Length(s_sym),
s_lower)))
if n_component.n_typ.upper_bound is not None:
s_upper = smt.Integer_Literal(n_component.n_typ.upper_bound)
gn_locals.add_statement(
smt.Assertion(
smt.Comparison("<=",
smt.Sequence_Length(s_sym),
s_upper)))
id_valid = self.tr_component_valid_name(n_component)
s_sym = smt.Constant(smt.BUILTIN_BOOLEAN, id_valid)
s_val = (None
if n_component.optional and not frozen
else smt.Boolean_Literal(True))
s_decl = smt.Constant_Declaration(
symbol = s_sym,
value = s_val,
relevant = True)
gn_locals.add_statement(s_decl)
self.constants[id_valid] = s_sym
def tr_type(self, n_type):
assert isinstance(n_type, Type)
if isinstance(n_type, Builtin_Boolean):
return smt.BUILTIN_BOOLEAN
elif isinstance(n_type, Builtin_Integer):
return smt.BUILTIN_INTEGER
elif isinstance(n_type, Builtin_Decimal):
return smt.BUILTIN_REAL
elif isinstance(n_type, Builtin_String):
return smt.BUILTIN_STRING
elif isinstance(n_type, Enumeration_Type):
if n_type not in self.enumerations:
s_sort = smt.Enumeration(n_type.n_package.name +
"." + n_type.name)
for n_lit in n_type.literals.values():
s_sort.add_literal(n_lit.name)
self.enumerations[n_type] = s_sort
self.start.add_statement(
smt.Enumeration_Declaration(
s_sort,
"enumeration %s from %s" % (
n_type.name,
n_type.location.to_string())))
return self.enumerations[n_type]
elif isinstance(n_type, Tuple_Type):
if n_type not in self.tuples:
s_sort = smt.Record(n_type.n_package.name +
"." + n_type.name)
for n_component in n_type.all_components():
s_sort.add_component(n_component.name + ".value",
self.tr_type(n_component.n_typ))
if n_component.optional:
s_sort.add_component(n_component.name + ".valid",
smt.BUILTIN_BOOLEAN)
self.tuples[n_type] = s_sort
self.start.add_statement(
smt.Record_Declaration(
s_sort,
"tuple %s from %s" % (
n_type.name,
n_type.location.to_string())))
return self.tuples[n_type]
elif isinstance(n_type, Array_Type):
if n_type not in self.arrays:
s_element_sort = self.tr_type(n_type.element_type)
s_sequence = smt.Sequence_Sort(s_element_sort)
self.arrays[n_type] = s_sequence
return self.arrays[n_type]
elif isinstance(n_type, Record_Type):
# Record references are modelled as a free integer, since
# we can't really _do_ anything with them. We just need a
# variable with infinite range so we can generate
# arbitrary fictional record names
return smt.BUILTIN_INTEGER
else: # pragma: no cover
self.flag_unsupported(n_type)
def tr_check(self, n_check):
assert isinstance(n_check, Check)
# If the check belongs to a different type then we are looking
# at a type extension. In this case we do not create checks
# again, because if a check would failt it would already have
# failed.
if n_check.n_type is not self.n_ctyp:
old_emit, self.emit_checks = self.emit_checks, False
value, valid = self.tr_expression(n_check.n_expr)
self.attach_validity_check(valid, n_check.n_expr)
self.attach_feasability_check(value, n_check.n_expr)
self.attach_assumption(value)
if n_check.n_type is not self.n_ctyp:
self.emit_checks = old_emit
def tr_expression(self, n_expr):
value = None
if isinstance(n_expr, Name_Reference):
return self.tr_name_reference(n_expr)
elif isinstance(n_expr, Unary_Expression):
return self.tr_unary_expression(n_expr)
elif isinstance(n_expr, Binary_Expression):
return self.tr_binary_expression(n_expr)
elif isinstance(n_expr, Range_Test):
return self.tr_range_test(n_expr)
elif isinstance(n_expr, Conditional_Expression):
if self.functional:
return self.tr_conditional_expression_functional(n_expr)
else:
return self.tr_conditional_expression(n_expr)
elif isinstance(n_expr, Null_Literal):
return None, smt.Boolean_Literal(False)
elif isinstance(n_expr, Boolean_Literal):
value = smt.Boolean_Literal(n_expr.value)
elif isinstance(n_expr, Integer_Literal):
value = smt.Integer_Literal(n_expr.value)
elif isinstance(n_expr, Decimal_Literal):
value = smt.Real_Literal(n_expr.value)
elif isinstance(n_expr, Enumeration_Literal):
value = smt.Enumeration_Literal(self.tr_type(n_expr.typ),
n_expr.value.name)
elif isinstance(n_expr, String_Literal):
value = smt.String_Literal(n_expr.value)
elif isinstance(n_expr, Quantified_Expression):
return self.tr_quantified_expression(n_expr)
elif isinstance(n_expr, Field_Access_Expression):
return self.tr_field_access_expression(n_expr)
else: # pragma: no cover
self.flag_unsupported(n_expr)
return value, smt.Boolean_Literal(True)
def tr_name_reference(self, n_ref):
assert isinstance(n_ref, Name_Reference)
if isinstance(n_ref.entity, Composite_Component):
if n_ref.entity.member_of in self.tuple_base:
sym = self.tuple_base[n_ref.entity.member_of]
if n_ref.entity.optional:
s_valid = smt.Record_Access(sym,
n_ref.entity.name + ".valid")
else:
s_valid = smt.Boolean_Literal(True)
s_value = smt.Record_Access(sym,
n_ref.entity.name + ".value")
return s_value, s_valid
else:
id_value = self.tr_component_value_name(n_ref.entity)
id_valid = self.tr_component_valid_name(n_ref.entity)
return self.constants[id_value], self.constants[id_valid]
else:
assert isinstance(n_ref.entity, Quantified_Variable)
if n_ref.entity in self.qe_vars:
return self.qe_vars[n_ref.entity], smt.Boolean_Literal(True)
else:
return self.bound_vars[n_ref.entity], smt.Boolean_Literal(True)
def tr_unary_expression(self, n_expr):
assert isinstance(n_expr, Unary_Expression)
operand_value, operand_valid = self.tr_expression(n_expr.n_operand)
if not self.functional:
self.attach_validity_check(operand_valid, n_expr.n_operand)
sym_value = None
if n_expr.operator == Unary_Operator.MINUS:
if isinstance(n_expr.n_operand.typ, Builtin_Integer):
sym_value = smt.Unary_Int_Arithmetic_Op("-",
operand_value)
else:
assert isinstance(n_expr.n_operand.typ, Builtin_Decimal)
sym_value = smt.Unary_Real_Arithmetic_Op("-",
operand_value)
elif n_expr.operator == Unary_Operator.PLUS:
sym_value = operand_value
elif n_expr.operator == Unary_Operator.LOGICAL_NOT:
sym_value = smt.Boolean_Negation(operand_value)
elif n_expr.operator == Unary_Operator.ABSOLUTE_VALUE:
if isinstance(n_expr.n_operand.typ, Builtin_Integer):
sym_value = smt.Unary_Int_Arithmetic_Op("abs",
operand_value)
else:
assert isinstance(n_expr.n_operand.typ, Builtin_Decimal)
sym_value = smt.Unary_Real_Arithmetic_Op("abs",
operand_value)
elif n_expr.operator == Unary_Operator.STRING_LENGTH:
sym_value = smt.String_Length(operand_value)
elif n_expr.operator == Unary_Operator.ARRAY_LENGTH:
sym_value = smt.Sequence_Length(operand_value)
elif n_expr.operator == Unary_Operator.CONVERSION_TO_DECIMAL:
sym_value = smt.Conversion_To_Real(operand_value)
elif n_expr.operator == Unary_Operator.CONVERSION_TO_INT:
sym_value = smt.Conversion_To_Integer("rna", operand_value)
else:
self.mh.ice_loc(n_expr,
"unexpected unary operator %s" %
n_expr.operator.name)
return self.create_return(n_expr, sym_value)
def tr_binary_expression(self, n_expr):
assert isinstance(n_expr, Binary_Expression)
# Some operators deal with validity in a different way. We
# deal with them first and then exit.
if n_expr.operator in (Binary_Operator.COMP_EQ,
Binary_Operator.COMP_NEQ):
return self.tr_op_equality(n_expr)
elif n_expr.operator == Binary_Operator.LOGICAL_IMPLIES:
return self.tr_op_implication(n_expr)
elif n_expr.operator == Binary_Operator.LOGICAL_AND:
return self.tr_op_and(n_expr)
elif n_expr.operator == Binary_Operator.LOGICAL_OR:
return self.tr_op_or(n_expr)
# The remaining operators always check for validity, so we can
# obtain the values of both sides now.
lhs_value, lhs_valid = self.tr_expression(n_expr.n_lhs)
if not self.functional:
self.attach_validity_check(lhs_valid, n_expr.n_lhs)
rhs_value, rhs_valid = self.tr_expression(n_expr.n_rhs)
if not self.functional:
self.attach_validity_check(rhs_valid, n_expr.n_rhs)
sym_value = None
if n_expr.operator == Binary_Operator.LOGICAL_XOR:
sym_value = smt.Exclusive_Disjunction(lhs_value, rhs_value)
elif n_expr.operator in (Binary_Operator.PLUS,
Binary_Operator.MINUS,
Binary_Operator.TIMES,
Binary_Operator.DIVIDE,
Binary_Operator.REMAINDER):
if isinstance(n_expr.n_lhs.typ, Builtin_String):
assert n_expr.operator == Binary_Operator.PLUS
sym_value = smt.String_Concatenation(lhs_value, rhs_value)
elif isinstance(n_expr.n_lhs.typ, Builtin_Integer):
if n_expr.operator in (Binary_Operator.DIVIDE,
Binary_Operator.REMAINDER):
self.attach_int_division_check(rhs_value, n_expr)
smt_op = {
Binary_Operator.PLUS : "+",
Binary_Operator.MINUS : "-",
Binary_Operator.TIMES : "*",
Binary_Operator.DIVIDE : "floor_div",
Binary_Operator.REMAINDER : "ada_remainder",
}[n_expr.operator]
sym_value = smt.Binary_Int_Arithmetic_Op(smt_op,
lhs_value,
rhs_value)
else:
assert isinstance(n_expr.n_lhs.typ, Builtin_Decimal)
if n_expr.operator == Binary_Operator.DIVIDE:
self.attach_real_division_check(rhs_value, n_expr)
smt_op = {
Binary_Operator.PLUS : "+",
Binary_Operator.MINUS : "-",
Binary_Operator.TIMES : "*",
Binary_Operator.DIVIDE : "/",
}[n_expr.operator]
sym_value = smt.Binary_Real_Arithmetic_Op(smt_op,
lhs_value,
rhs_value)
elif n_expr.operator in (Binary_Operator.COMP_LT,
Binary_Operator.COMP_LEQ,
Binary_Operator.COMP_GT,
Binary_Operator.COMP_GEQ):
smt_op = {
Binary_Operator.COMP_LT : "<",
Binary_Operator.COMP_LEQ : "<=",
Binary_Operator.COMP_GT : ">",
Binary_Operator.COMP_GEQ : ">=",
}[n_expr.operator]
sym_value = smt.Comparison(smt_op, lhs_value, rhs_value)
elif n_expr.operator in (Binary_Operator.STRING_CONTAINS,
Binary_Operator.STRING_STARTSWITH,
Binary_Operator.STRING_ENDSWITH):
smt_op = {
Binary_Operator.STRING_CONTAINS : "contains",
Binary_Operator.STRING_STARTSWITH : "prefixof",
Binary_Operator.STRING_ENDSWITH : "suffixof"
}
# LHS / RHS ordering is not a mistake, in SMTLIB it's the
# other way around than in TRLC.
sym_value = smt.String_Predicate(smt_op[n_expr.operator],
rhs_value,
lhs_value)
elif n_expr.operator == Binary_Operator.STRING_REGEX:
rhs_evaluation = n_expr.n_rhs.evaluate(self.mh, None).value
assert isinstance(rhs_evaluation, str)
sym_value = smt.Function_Application(
self.get_uf_matches(),
lhs_value,
smt.String_Literal(rhs_evaluation))
elif n_expr.operator == Binary_Operator.INDEX:
self.attach_index_check(lhs_value, rhs_value, n_expr)
sym_value = smt.Sequence_Index(lhs_value, rhs_value)
elif n_expr.operator == Binary_Operator.ARRAY_CONTAINS:
sym_value = smt.Sequence_Contains(rhs_value, lhs_value)