-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyclid.py
1545 lines (1392 loc) · 55.8 KB
/
pyclid.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
import logging
import textwrap
from enum import Enum
from typing import List, Dict
__author__ = "Adwait Godbole"
__copyright__ = "Adwait Godbole"
__license__ = "MIT"
_logger = logging.getLogger(__name__)
class UclidContext():
# dict: str (modulename) -> UclidModule
modules = {}
# name of current module
curr_module_name = "main"
# current module context
curr_module = None
@staticmethod
def clearAll():
"""
Deletes all context information (restart).
"""
UclidContext.curr_module_name = "main"
UclidContext.curr_module = UclidModule("main")
UclidContext.modules = { "main" : UclidModule("main") }
@staticmethod
def setContext(module_name):
UclidContext.curr_module_name = module_name
if module_name not in UclidContext.modules:
UclidContext.modules[module_name] = UclidModule(module_name)
@staticmethod
def __inject__():
acc = ""
for modulename in UclidContext.modules:
acc += UclidContext.modules[modulename].__inject__()
return acc
class UclidElement():
def __init__(self) -> None:
pass
def __inject__(self) -> str:
raise NotImplementedError
class PortType(Enum):
var = 0
input = 1
output = 2
# ==============================================================================
# Uclid Declarations
# ==============================================================================
class DeclTypes(Enum):
VAR = 0
FUNCTION = 1
TYPE = 2
INSTANCE = 3
SYNTHFUN = 4
DEFINE = 5
CONST = 6
PROCEDURE = 7
CONSTRAINTS = 8
# Base class for (all sorts of) uclid declarations
class UclidDecl(UclidElement):
def __init__(self, decltype) -> None:
super().__init__()
self.decltype = decltype
def __inject__(self) -> str:
if self.decltype == DeclTypes.VAR:
return "{} {} : {};".format(
self.porttype.name, self.name, self.__declstring__
)
elif self.decltype == DeclTypes.TYPE:
if self.__declstring__ == "":
return "type {};".format(self.name)
return "type {} = {};".format(self.name, self.__declstring__)
elif self.decltype == DeclTypes.INSTANCE:
return "instance {} : {};".format(self.name, self.__declstring__)
elif self.decltype == DeclTypes.CONST:
return "const {} : {};".format(self.name, self.__declstring__)
elif self.decltype == DeclTypes.DEFINE:
return self.__declstring__
elif self.decltype == DeclTypes.FUNCTION:
return self.__declstring__
elif self.decltype == DeclTypes.PROCEDURE:
return self.__declstring__
elif self.decltype == DeclTypes.CONSTRAINTS:
return self.__declstring__
else:
_logger.error(f"Declaration for decltype {self.decltype} is not permitted")
exit(1)
@property
def __declstring__(self) -> str:
raise NotImplementedError
class UclidTypeDecl(UclidDecl):
def __init__(self, name: str, typexp=None) -> None:
super().__init__(DeclTypes.TYPE)
self.name = name
self.typexp = typexp
@property
def __declstring__(self):
return "" if self.typexp is None else self.typexp.__inject__()
class UclidVarDecl(UclidDecl):
def __init__(self, name, typ, porttype=PortType.var):
super().__init__(DeclTypes.VAR)
self.name = name
self.typ = typ
self.porttype = porttype
@property
def __declstring__(self):
return self.typ.__inject__()
class UclidConstDecl(UclidDecl):
def __init__(self, name, typ, val = None):
super().__init__(DeclTypes.CONST)
self.name = name
self.typ = typ
self.val = val
@property
def __declstring__(self):
if self.val is None:
return self.typ.__inject__()
return f"{self.typ.__inject__()} = {self.val.__inject__()}"
class UclidDefineDecl(UclidDecl):
def __init__(self, name: str, functionsig, body) -> None:
super().__init__(DeclTypes.DEFINE)
self.name = name
self.functionsig = functionsig
self.body = body
@property
def __declstring__(self) -> str:
return "\tdefine {}{} = {};".format(
self.name, self.functionsig.__inject__(), self.body.__inject__()
)
class UclidFunctionDecl(UclidDecl):
def __init__(self, name: str, functionsig) -> None:
super().__init__(DeclTypes.FUNCTION)
self.name = name
self.functionsig = functionsig
@property
def __declstring__(self) -> str:
return "\tfunction {}{};".format(
self.name, self.functionsig.__inject__()
)
class UclidProcedureDecl(UclidDecl):
def __init__(self, name: str, proceduresig, body):
super().__init__(DeclTypes.PROCEDURE)
self.name = name
self.proceduresig = proceduresig
self.body = body
@property
def __declstring__(self) -> str:
return """procedure {}
{}
{{
{}
}}
""".format(
self.name,
self.proceduresig.__inject__(),
textwrap.indent(self.body.__inject__(), '\t')
)
class UclidInstanceDecl(UclidDecl):
def __init__(self, instancename, module, argmap):
super().__init__(DeclTypes.INSTANCE)
self.name = instancename
self.module = module
self.argmap = argmap
@property
def __declstring__(self):
if self.modulename not in UclidContext.modules:
_logger.error("Module {} not found in UclidContext.modules".format(self.modulename))
_logger.debug("Available modules: {}".format(UclidContext.modules.keys()))
exit(1)
argmapstr = ', '.join([
"{} : ({})".format(port.name, self.argmap[port.name].__inject__())
for port in self.module.ip_var_decls + self.module.op_var_decls
])
return "{}({})".format(self.module.name, argmapstr)
class UclidRawInstanceDecl(UclidDecl):
""" Raw (external) module instances in Uclid """
def __init__(self, instancename, module, argmap):
super().__init__(DeclTypes.INSTANCE)
self.name = instancename
self.modname = module.name if isinstance(module, UclidModule) else module
self.argmap = argmap
@property
def __declstring__(self):
argmapstr = ', '.join([
"{} : ({})".format(portname, self.argmap[portname].__inject__())
for portname in self.argmap
])
return "{}({})".format(self.modname, argmapstr)
class UclidImportDecl(UclidDecl):
def __init__(self, decltype, name, modulename, refname) -> None:
"""Import objects from a module
Args:
decltype (DeclTypes): type of objects to import
name (str): Name of imported object in current module
modulename (Module/str): Module (or its name) from which to import
refname (str): Name of object in the module
"""
super().__init__(decltype)
self.name = name
self.modulename = modulename if isinstance(modulename, str) else modulename.name
self.refname = refname
@property
def __declstring__(self):
return f"{self.modulename}.{self.refname}"
class UclidWildcardImportDecl(UclidImportDecl):
def __init__(self, decltype, modulename) -> None:
super().__init__(decltype, "*", modulename, "*")
# ==============================================================================
# Uclid Spec (assertions)
# ==============================================================================
class UclidSpecDecl(UclidDecl):
def __init__(self, name: str, body, is_ltl=False) -> None:
"""Specification declaration"""
super().__init__(DeclTypes.CONSTRAINTS)
self.name = name
self.body = body
self.is_ltl = is_ltl
@property
def __declstring__(self) -> str:
if self.name != "":
if not self.is_ltl:
return "property {} : {};\n".format(
self.name, self.body.__inject__()
)
return "property[LTL] {} : {};\n".format(
self.name, self.body.__inject__()
)
else:
if not self.is_ltl:
return "property {};\n".format(self.body.__inject__())
return "property[LTL] {};\n".format(self.body.__inject__())
# ==============================================================================
# Uclid Axiom (assumptions)
# ==============================================================================
class UclidAxiomDecl(UclidDecl):
def __init__(self, name: str, body) -> None:
super().__init__(DeclTypes.CONSTRAINTS)
self.name = name
self.body = body
def __declstring__(self) -> str:
if self.name != "":
return "axiom {} : ({});\n".format(self.name, self.body.__inject__())
else:
return "axiom ({});".format(self.body.__inject__())
# ==============================================================================
# Uclid Init
# ==============================================================================
class UclidInitBlock(UclidElement):
def __init__(self, block) -> None:
super().__init__()
if isinstance(block, UclidBlockStmt):
self.block = block
elif isinstance(block, list):
self.block = UclidBlockStmt(block)
elif isinstance(block, UclidStmt):
self.block = UclidBlockStmt([block])
else:
_logger.error("Unsupported type {} of block in UclidInitBlock".format(
type(block)
))
def __inject__(self) -> str:
return textwrap.dedent("""
init {{
{}
}}""").format(textwrap.indent(self.block.__inject__().strip(), '\t'))
# ==============================================================================
# Uclid Next
# ==============================================================================
class UclidNextBlock(UclidElement):
def __init__(self, block) -> None:
super().__init__()
if isinstance(block, UclidBlockStmt):
self.block = block
elif isinstance(block, list):
self.block = UclidBlockStmt(block)
elif isinstance(block, UclidStmt):
self.block = UclidBlockStmt([block])
else:
_logger.error("Unsupported type {} of block in UclidNextBlock".format(
type(block)
))
def __inject__(self) -> str:
return textwrap.dedent("""
next {{
{}
}}""").format(textwrap.indent(self.block.__inject__().strip(), '\t'))
# ==============================================================================
# Uclid Types
# ==============================================================================
class UclidType(UclidElement):
def __init__(self, typestring):
self.typestring = typestring
def __inject__(self) -> str:
return self.typestring
class UclidBooleanType(UclidType):
def __init__(self):
super().__init__("boolean")
class UclidIntegerType(UclidType):
def __init__(self):
super().__init__("integer")
class UclidBVType(UclidType):
def __init__(self, width):
super().__init__("bv{}".format(width))
self.width = width
class UclidArrayType(UclidType):
def __init__(self, itype, etype):
super().__init__("[{}]{}".format(itype.__inject__(), etype.__inject__()))
self.indextype = itype
self.elemtype = etype
class UclidEnumType(UclidType):
def __init__(self, members):
super().__init__("enum {{ {} }}".format(", ".join(members)))
self.members = members
class UclidSynonymType(UclidType):
def __init__(self, name):
super().__init__(name)
self.name = name
class UclidUninterpretedType(UclidType):
def __init__(self, name):
super().__init__(name)
self.name = name
# ==============================================================================
# Uclid Define macros and Functions
# ==============================================================================
class UclidFunctionSig(UclidElement):
def __init__(self, inputs: list, outtype: UclidType) -> None:
"""Uclid function signature
Args:
inputs (List[(UclidLiteral|str, UclidType)]): List of input arguments
outtype (UclidType): Output type
"""
super().__init__()
self.inputs = inputs
self.outtype = outtype
def __inject__(self) -> str:
input_sig = ', '.join(["{} : {}".format(
i[0] if isinstance(i[0], str) else i[0].__inject__(),
i[1].__inject__()
) for i in self.inputs])
return "({}) : {}".format(input_sig, self.outtype.__inject__())
class UclidDefine(UclidElement):
def __init__(self, name) -> None:
super().__init__()
self.name = name
def __inject__(self) -> str:
return self.name
class UclidFunction(UclidElement):
def __init__(self, name) -> None:
"""Uclid uninterpreted function"""
super().__init__()
self.name = name
def __inject__(self) -> str:
return self.name
# ==============================================================================
# Uclid Procedures
# ==============================================================================
class UclidProcedureSig(UclidElement):
# ip_args are pairs of str, Uclidtype elements
def __init__(self, inputs, modifies = None, returns = None, requires = None, ensures = None) -> None:
"""Procedure signature
Args:
inputs (List[(UclidLiteral|str, UclidType)]): List of (typed) input arguments
modifies (List[UclidLiteral], optional): List of modified variables. Defaults to None.
returns (List[(UclidLiteral|str, UclidType)], optional): List of returned variables. Defaults to None.
requires (UclidExpr, optional): Input/initial assumptions in procedural verification. Defaults to None.
ensures (UclidExpr, optional): Output/final guarantees in procedural verification. Defaults to None.
"""
super().__init__()
self.inputs = inputs
self.modifies = modifies
self.returns = returns
self.requires = requires
self.ensures = ensures
def __inject__(self) -> str:
input_str = ', '.join(["{} : {}".format(
i[0] if isinstance(i[0], str) else i[0].lit,
i[1].__inject__()
) for i in self.inputs])
return_str = "\n\treturns ({})".format(', '.join(["{} : {}".format(
i[0] if isinstance(i[0], str) else i[0].lit,
i[1].__inject__()) for i in self.returns])
) if self.returns is not None else ''
modify_str = "\n\tmodifies {};".format(
', '.join([sig.__inject__() for sig in self.modifies])
) if self.modifies is not None else ''
requires_str = "\nrequires ({});".format(
self.requires.__inject__()
) if self.requires is not None else ''
ensures_str = "\nensures ({});".format(
self.ensures.__inject__()
) if self.ensures is not None else ''
return "({}){}{}{}{}".format(input_str, modify_str, return_str, requires_str, ensures_str)
class UclidProcedure(UclidElement):
def __init__(self, name):
super().__init__()
self.name = name
def __inject__(self) -> str:
return self.name
# ==============================================================================
# Uclid sub-module instances
# ==============================================================================
class UclidInstance(UclidElement):
"""Module instances in Uclid"""
def __init__(self, instancename) -> None:
super().__init__()
self.instancename = instancename
def __inject__(self) -> str:
return self.instancename
# ==============================================================================
# Uclid Expressions
# ==============================================================================
class Operators:
"""
Comprehensive operator list
"""
OpMapping = {
"add" : ("+", 2),
"sub" : ("-", 2),
"umin" : ("-", 1),
"gt" : (">", 2),
"gte" : (">=", 2),
"lt" : ("<", 2),
"lte" : ("<=", 2),
"eq" : ("==", 2),
"neq" : ("!=", 2),
"not" : ("!", 1),
"xor" : ("^", 2),
"and" : ("&&", -1),
"or" : ("||", -1),
"implies" : ("==>", 2),
"bvadd" : ("+", 2),
"bvsub" : ("-", 2),
"bvand" : ("&", 2),
"bvor" : ("|", 2),
"bvnot" : ("~", 1),
"bvlt" : ("<", 2),
"bvult" : ("<_u", 2),
"bvgt" : (">", 2),
"bvugt" : (">_u", 2),
"next" : ("X", 1),
"eventually" : ("F", 1),
"always" : ("G", 1),
"concat" : ("++", -1)
}
def __init__(self, op_) -> None:
self.op = op_
def __inject__(self) -> str:
return Operators.OpMapping[self.op][0]
# Base class for Uclid expressions
class UclidExpr(UclidElement):
def __inject__(self) -> str:
raise NotImplementedError
def __make_op__(self, op, other):
if isinstance(other, UclidExpr):
return UclidOpExpr(op, [self, other])
elif isinstance(other, int):
return UclidOpExpr(op, [self, UclidLiteral(str(other))])
elif isinstance(other, str):
return UclidOpExpr(op, [self, UclidLiteral(other)])
else:
_logger.error("Unsupported types for operation {}: {} and {}".format(
op, 'UclidExpr', type(other)))
def __eq__(self, other):
return self.__make_op__("eq", other)
def __ne__(self, other):
return self.__make_op__("neq", other)
def __add__(self, other):
return self.__make_op__("add", other)
def __sub__(self, other):
return self.__make_op__("sub", other)
def __mul__(self, other):
return self.__make_op__("mul", other)
def __invert__(self):
return UclidOpExpr("not", [self])
def __and__(self, other):
if isinstance(other, UclidExpr):
return UclidOpExpr("and", [self, other])
else:
_logger.error("Unsupported types for operation {}: {} and {}".format(
'&', 'UclidExpr', type(other)))
class UclidOpExpr(UclidExpr):
"""
Generic Uclid operator expression
"""
def __init__(self, op, children) -> None:
super().__init__()
self.op = op
self.children = [
UclidLiteral(str(child)) if isinstance(child, int) else child
for child in children
]
def __inject__(self) -> str:
c_code = ["({})".format(child.__inject__()) for child in self.children]
oprep = Operators.OpMapping[self.op]
if oprep[1] == 1:
assert len(c_code) == 1, "Unary operator must have one argument"
return f"{oprep[0]} {c_code[0]}"
if oprep[1] == 2:
assert len(c_code) == 2, "Binary operator must have two arguments"
return f"{c_code[0]} {oprep[0]} {c_code[1]}"
if oprep[1] == -1:
return (f" {oprep[0]} ").join(c_code)
else:
_logger.error("Operator arity not yet supported")
# ==============================================================================
# Uclid Complex expressions
# ==============================================================================
class UclidBVSignExtend(UclidExpr):
def __init__(self, bvexpr, newwidth):
super().__init__()
self.bvexpr = bvexpr
self.newwidth = newwidth
def __inject__(self) -> str:
return "bv_sign_extend({}, {})".format(self.newwidth, self.bvexpr.__inject__())
class UclidBVExtract(UclidExpr):
def __init__(self, bvexpr: UclidExpr, high: int, low: int):
"""Extract a sub-bitvector from a bitvector
Args:
bvexpr (UclidExpr): Bitvector expression to extract from
high (int): high index (inclusive)
low (int): low index (inclusive)
"""
super().__init__()
self.bvexpr = bvexpr
self.high = high
self.low = low
def __inject__(self) -> str:
return "({})[{}:{}]".format(self.bvexpr.__inject__(), self.high, self.low)
class UclidFunctionApplication(UclidExpr):
def __init__(self, function, arglist):
super().__init__()
self.function = function if isinstance(function, str) else function.name
self.arglist = arglist
def __inject__(self) -> str:
return "{}({})".format(
self.function,
', '.join([arg.__inject__() for arg in self.arglist])
)
class UclidArraySelect(UclidExpr):
def __init__(self, arrayexpr: UclidExpr, indexseq: List[UclidExpr]):
"""Select an element from an array
Args:
arrayexpr (UclidExpr): Array-typed expression to select from
indexseq (List[UclidExpr]): List of indices
"""
super().__init__()
self.arrayexpr = arrayexpr if isinstance(arrayexpr, str) else arrayexpr.__inject__()
self.indexseq = [
ind if isinstance(ind, UclidExpr) else UclidLiteral(str(ind))
for ind in indexseq
]
def __inject__(self) -> str:
return "{}[{}]".format(self.arrayexpr,
"][".join([ind.__inject__() for ind in self.indexseq])
)
class UclidArrayUpdate(UclidExpr):
def __init__(self, arrayexpr: UclidExpr, index: UclidExpr, value: UclidExpr):
"""Update an element in an array
Args:
arrayexpr (UclidExpr): Array-typed expression to update
index (UclidExpr): Index to update (only supported for 1-D arrays)
value (UclidExpr): New value
"""
super().__init__()
self.arrayexpr = arrayexpr if isinstance(arrayexpr, str) else arrayexpr.__inject__()
self.index = index if isinstance(index, UclidExpr) else UclidLiteral(str(index))
self.value = value if isinstance(value, UclidExpr) else UclidLiteral(str(value))
def __inject__(self) -> str:
return "{}[{} -> {}]".format(self.arrayexpr, self.index.__inject__(), self.value.__inject__())
class UclidRecordSelect(UclidExpr):
def __init__(self, recexpr: UclidExpr, elemname: str):
"""Select a record element
Args:
recexpr (UclidExpr): Record-typed to select from
elemname (str): Field in the record to select
"""
super().__init__()
self.recexpr = recexpr if isinstance(recexpr, str) else recexpr.__inject__()
self.elemname = elemname
def __inject__(self) -> str:
return "{}.{}".format(self.recexpr, self.elemname)
class UclidRecordUpdate(UclidExpr):
def __init__(self, recexpr: UclidExpr, elemname: str, value: UclidExpr):
"""Update a record element
Args:
recexpr (UclidExpr): Record to update
elemname (str): Field in the record to update
value (UclidExpr): New value
"""
super().__init__()
self.recexpr = recexpr if isinstance(recexpr, str) else recexpr.__inject__()
self.elemname = elemname
self.value = value
def __inject__(self) -> str:
return "{}[{} := {}]".format(self.recexpr, self.elemname, self.value.__inject__())
class UclidForallExpr(UclidExpr):
def __init__(self, iterator, typ, bodyexpr : UclidExpr):
super().__init__()
self.iterator = iterator if isinstance(iterator, str) else iterator.__inject__()
self.typ = typ
self.bodyexpr = bodyexpr
def __inject__(self) -> str:
return "forall ({} : {}) :: ({})".format(
self.iterator,
self.typ.__inject__(),
self.bodyexpr.__inject__()
)
# ==============================================================================
# Uclid Literals
# ==============================================================================
class UclidLiteral(UclidExpr):
""" Uclid literal """
def __init__(self, lit, isprime = False) -> None:
super().__init__()
self.lit = lit if isinstance(lit, str) else str(lit)
self.isprime = isprime
def p(self):
if self.isprime:
_logger.warn("Double prime for literal {}".format(self.lit))
return UclidLiteral(self.lit + '\'', True)
def __inject__(self) -> str:
return self.lit
def __add__(self, other):
return super().__add__(other)
class UclidIntegerLiteral(UclidLiteral):
"""Uclid integer literal"""
def __init__(self, val):
super().__init__(val)
self.val = val
class UclidBooleanLiteral(UclidLiteral):
"""Uclid boolean literal"""
def __init__(self, val : bool):
super().__init__("true" if val else "false")
self.val = val
class UclidBVLiteral(UclidLiteral):
"""Uclid bitvector literal"""
def __init__(self, val, width: int):
super().__init__(f'{val}bv{str(width)}')
self.val = val
self.width = width
# ==============================================================================
# Uclid Variables
# ==============================================================================
class UclidVar(UclidLiteral):
def __init__(self, name, typ):
super().__init__(name)
self.name = name
self.typ = typ
def __inject__(self) -> str:
return self.name
def __add__(self, other):
return super().__add__(other)
# Uclid integer type declaration
class UclidIntegerVar(UclidVar):
def __init__(self, name) -> None:
super().__init__(name, UclidIntegerType())
def __add__(self, other):
return super().__add__(other)
# Uclid bitvector type declaration
class UclidBVVar(UclidVar):
def __init__(self, name, width) -> None:
super().__init__(name, UclidBVType(width))
self.width = width
def __add__(self, other):
return super().__add__(other)
class UclidBooleanVar(UclidVar):
def __init__(self, name) -> None:
super().__init__(name, UclidBooleanType())
def __add__(self, _):
_logger.error("Addition not supported on Boolean type")
exit(1)
# Uclid Const declaration
class UclidConst(UclidLiteral):
def __init__(self, name: str):
super().__init__(name)
self.name = name
def __inject__(self) -> str:
return self.name
# ==============================================================================
# Uclid instance variable access
# ==============================================================================
class UclidInstanceVarAccess(UclidExpr):
def __init__(self, instance : UclidInstance, var: UclidLiteral):
"""Access to a variable in a module instance
Args:
instance (UclidInstance/str): Module instance (or its name)
var (UclidExpr): Variable to access (must be a single variable, not an expression)
"""
self.instance = instance.__inject__() if isinstance(instance, UclidModule) else instance
self.var = var
def __inject__(self) -> str:
return "{}.{}".format(self.instance, self.var.__inject__())
# ==============================================================================
# Uclid statements
# ==============================================================================
class UclidStmt(UclidElement):
""" Statements in Uclid. """
def __init__(self):
pass
def __inject__(self) -> str:
raise NotImplementedError
class UclidComment(UclidStmt):
def __init__(self, text: str) -> None:
"""Uclid comment
Args:
text (str): Comment text
"""
super().__init__()
self.text = text
def __inject__(self) -> str:
return '\t//'.join(('\n' + self.text.lstrip()).splitlines(True))
class UclidRaw(UclidStmt):
def __init__(self, rawstring : str):
"""Raw Uclid statement
Args:
rawstring (str): Injects this string as is into the Uclid code
"""
super().__init__()
self.rawstring = rawstring
def __inject__(self) -> str:
return self.rawstring
class UclidEmpty(UclidRaw):
def __init__(self):
super().__init__("")
class UclidLocalVarInstanceStmt(UclidStmt):
def __init__(self, name, typ):
super().__init__()
self.name = name
self.typ = typ
def __inject__(self) -> str:
return "var {} : {};".format(self.name, self.typ.__inject__())
class UclidAssignStmt(UclidStmt):
def __init__(self, lval: UclidExpr, rval: UclidExpr) -> None:
"""Assignment statement
Args:
lval (UclidExpr): LHS of the assignment
rval (UclidExpr): RHS of the assignment
"""
super().__init__()
self.lval = lval
if isinstance(rval, UclidExpr):
self.rval = rval
elif isinstance(rval, int):
self.rval = UclidLiteral(str(rval))
elif isinstance(rval, str):
self.rval = UclidLiteral(rval)
else:
_logger.error(f"Unsupported rval {rval} has type {type(rval)} in UclidAssign")
def __inject__(self) -> str:
return "{} = {};".format(self.lval.__inject__(), self.rval.__inject__())
class UclidBlockStmt(UclidStmt):
def __init__(self, stmts : List[UclidStmt] = []) -> None:
"""Block statement: a sequence of statements
Args:
stmts (List[UclidStmt], optional): Statements in this block. Defaults to [].
"""
super().__init__()
self.stmts = stmts
def __inject__(self) -> str:
return '\n'.join([stmt.__inject__() for stmt in self.stmts])
class UclidCaseStmt(UclidStmt):
def __init__(self, conditionlist: List[UclidExpr], stmtlist: List[UclidStmt]):
"""Case statement: a sequence of case-split conditions and statements
Args:
conditionlist (List[UclidExpr]): List of boolean condition expressions
stmtlist (List[UclidStmt]): List of statements to execute based on the conditions
"""
if not isinstance(conditionlist, list) or not isinstance(stmtlist, list):
_logger.error("UclidCase requires a pair of lists denoting case-split conditions and statements")
_logger.error("Received {} and {}".format(type(conditionlist), type(stmtlist)))
exit(1)
self.conditionlist = conditionlist
self.stmtlist = stmtlist
def __inject__(self) -> str:
cases = [
"({})\t: {{ \n{} \n}}".format(
item[0].__inject__(), textwrap.indent(item[1].__inject__(), '\t')
)
for item in zip(self.conditionlist, self.stmtlist)
]
return textwrap.dedent(
"""
case
{}
esac
"""
).format("\n".join(cases))
class UclidITEStmt(UclidStmt):
def __init__(self, condition: UclidExpr, tstmt: UclidStmt, estmt: UclidStmt=None):
"""If-then-else statement
Args:
condition (UclidExpr): If condition
tstmt (UclidStmt): Then statement
estmt (UclidStmt, optional): Else statement. Defaults to None.
"""
self.condition = condition
self.tstmt = tstmt
self.estmt = estmt
def __inject__(self) -> str:
if self.estmt == None:
return """
if ({}) {{ {} }}
""".format(
self.condition.__inject__(), self.tstmt.__inject__()
)
else:
return """
if ({}) {{ {} }} else {{ {} }}
""".format(
self.condition.__inject__(),
self.tstmt.__inject__(),
self.estmt.__inject__()
)
class UclidITENestedStmt(UclidStmt):
def __init__(self, conditionlist: List[UclidExpr], stmtlist: List[UclidStmt]):
"""Nested if-then-else statement (sugaring)
Args:
conditionlist (List[UclidExpr]): List of conditions (each nested within the previous else block)
stmtlist (List[UclidStmt]): List of corresponding statements
"""
if len(conditionlist) == len(stmtlist):
self.format = "IT"
elif len(conditionlist) == len(stmtlist) - 1:
self.format = "ITE"
else:
_logger.error(
"Illegal lengths of conditionlist and stmt blocks in ITE operator"
)
self.conditionlist = conditionlist
self.stmtlist = stmtlist
def __inject__(self) -> str:
def ite_rec(clist, slist):
if len(clist) > 0 and len(slist) > 0:
nesting = ite_rec(clist[1:], slist[1:])
return """
if ({}) {{ {} }}
else {{ {} }}""".format(
clist[0].__inject__(), slist[0].__inject__(), nesting
)
elif len(slist) > 0:
return "{}".format(slist[0].__inject__())
elif len(clist) == 0:
return ""
else:
_logger.error("Mismatched clist/slist lengths in ite_rec")
return ite_rec(self.conditionlist, self.stmtlist)
class UclidProcedureCallStmt(UclidStmt):
def __init__(self, proc: UclidProcedure, inputs: List[UclidExpr], returns: List[UclidExpr]):
"""Procedure call statement
Args:
proc (UclidProcedure): Procedure to call
inputs (List[UclidExpr]): List of input argument expressions
returns (List[UclidExpr]): Return variables to assign
"""
super().__init__()
self.iname = proc if isinstance(proc, str) else proc.name
self.inputs = inputs
self.returns = returns
def __inject__(self) -> str:
return "call ({}) = {}({});".format(
', '.join([ret.__inject__() for ret in self.returns]),
self.iname,
', '.join([arg.__inject__() for arg in self.inputs])
)
class UclidInstanceProcedureCallStmt(UclidStmt):
def __init__(self, instance: UclidInstance, proc, inputs: List[UclidExpr], returns: List[UclidExpr]):
"""Call procedure from a (sub-)module instance
Args:
instance (UclidInstance): Module instance to call
proc (_type_): Procedure to call from that instance
inputs (List[UclidExpr]): List of input argument expressions
returns (List[UclidExpr]): Return variables to assign
"""
super().__init__()
self.instance = instance if isinstance(instance, str) else instance.name
self.iname = "{}.{}".format(
self.instance,
proc if isinstance(proc, str) else proc.name
)
self.inputs = inputs
self.returns = returns
def __inject__(self) -> str:
return "call ({}) = {}({});".format(
', '.join([ret.__inject__() for ret in self.returns]),
self.iname,
', '.join([arg.__inject__() for arg in self.inputs])
)
class UclidNextStmt(UclidStmt):
def __init__(self, instance: UclidInstance):
"""Next statement: this advances the state of the module instance
Args:
instance (UclidInstance): Module instance to advance
"""
super().__init__()
self.instance = instance
def __inject__(self) -> str:
return "next ({});".format(self.instance.__inject__())
class UclidAssumeStmt(UclidStmt):
def __init__(self, body: UclidExpr):
"""Assumption statement: this assumes that the body expression is true
(constrains executions to only those that satisfy the assumption)
Args:
body (UclidExpr): Assumption body
"""
super().__init__()
self.body = body
def __inject__(self) -> str:
return "assume({});".format(self.body.__inject__())
class UclidAssertStmt(UclidStmt):
def __init__(self, body: UclidExpr):
"""Assertion statement: this checks that the body expression is true
Args:
body (UclidExpr): Assertion body
"""
super().__init__()
self.body = body
def __inject__(self) -> str:
return "assert({});".format(self.body.__inject__())
class UclidHavocStmt(UclidStmt):
def __init__(self, variable: UclidVar):
"""Havoc statement: this sets the variable to an arbitrary (non-deterministic) value
Args:
variable (UclidVar): Variable to havoc
"""