-
Notifications
You must be signed in to change notification settings - Fork 6
/
message.py
2364 lines (2112 loc) · 88.5 KB
/
message.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
# pylint: disable=too-many-lines
from __future__ import annotations
import itertools
from abc import abstractmethod
from collections import defaultdict
from copy import copy
from dataclasses import dataclass, field as dataclass_field
from enum import Enum
from typing import Dict, List, Mapping, Optional, Sequence, Set, Tuple, Union
import rflx.typing_ as rty
from rflx import expression as expr
from rflx.common import Base, indent, indent_next, unique, verbose_repr
from rflx.contract import ensure, invariant
from rflx.error import Location, RecordFluxError, Severity, Subsystem, fail, fatal_fail
from rflx.identifier import ID, StrID
from . import type_ as mty
class ByteOrder(Enum):
HIGH_ORDER_FIRST = 1
LOW_ORDER_FIRST = 2
class Field(Base):
def __init__(self, identifier: StrID) -> None:
self.identifier = ID(identifier)
def __hash__(self) -> int:
return hash(self.identifier)
def __repr__(self) -> str:
return f'Field("{self.identifier}")'
def __lt__(self, other: "Field") -> int:
return self.identifier < other.identifier
@property
def name(self) -> str:
return str(self.identifier)
@property
def affixed_name(self) -> str:
return f"F_{self.name}"
INITIAL = Field("Initial")
FINAL = Field("Final")
@dataclass(order=True)
class Link(Base):
source: Field
target: Field
condition: expr.Expr = expr.TRUE
size: expr.Expr = expr.UNDEFINED
first: expr.Expr = expr.UNDEFINED
location: Optional[Location] = dataclass_field(default=None, repr=False)
def __str__(self) -> str:
condition = indent_next(
f"\nif {indent_next(str(self.condition), 3)}" if self.condition != expr.TRUE else "", 3
)
aspects = []
if self.size != expr.UNDEFINED:
aspects.append(f"Size => {self.size}")
if self.first != expr.UNDEFINED:
aspects.append(f"First => {self.first}")
with_clause = indent_next("\nwith " + ", ".join(aspects) if aspects else "", 3)
target_name = self.target.name if self.target != FINAL else "null"
return f"then {target_name}{with_clause}{condition}"
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
return (
self.source == other.source
and self.target == other.target
and self.condition == other.condition
and self.size == other.size
and self.first == other.first
)
return NotImplemented
def __hash__(self) -> int:
return 0
@property
def has_implicit_size(self) -> bool:
return bool(self.size.findall(lambda x: x in [expr.Size("Message"), expr.Last("Message")]))
def valid_message_field_types(message: "AbstractMessage") -> bool:
for t in message.types.values():
if not isinstance(t, (mty.Scalar, mty.Composite, AbstractMessage)):
return False
return True
class MessageState(Base):
parameter_types: Mapping[Field, mty.Type] = {}
field_types: Mapping[Field, mty.Type] = {}
definite_predecessors: Optional[Mapping[Field, Tuple[Field, ...]]] = None
path_condition: Optional[Mapping[Field, expr.Expr]] = None
@invariant(lambda self: valid_message_field_types(self))
@invariant(lambda self: not self.types if not self.structure else True)
class AbstractMessage(mty.Type):
# pylint: disable=too-many-arguments,too-many-public-methods,too-many-instance-attributes
def __init__(
self,
identifier: StrID,
structure: Sequence[Link],
types: Mapping[Field, mty.Type],
checksums: Mapping[ID, Sequence[expr.Expr]] = None,
byte_order: ByteOrder = None,
location: Location = None,
error: RecordFluxError = None,
state: MessageState = None,
) -> None:
super().__init__(identifier, location, error)
assert len(self.identifier.parts) > 1, "type identifier must contain package"
self.structure = sorted(structure)
self.__types = types
self.__has_unreachable = False
self.__paths_cache: Dict[Field, Set[Tuple[Link, ...]]] = {}
self.byte_order = byte_order if byte_order else ByteOrder.HIGH_ORDER_FIRST
self._checksums = checksums or {}
self._state = state or MessageState()
self._unqualified_enum_literals = {
l
for t in self.dependencies
if isinstance(t, mty.Enumeration) and t.package == self.package
for l in t.literals
}
self._qualified_enum_literals = mty.qualified_enum_literals(self.dependencies)
self._type_literals = mty.qualified_type_literals(self.dependencies)
if not state and (structure or types):
try:
self.__validate()
self.__normalize()
fields = self.__compute_topological_sorting()
if fields:
self._state.field_types = {f: self.__types[f] for f in fields}
self._state.parameter_types = {
f: t for f, t in self.__types.items() if f not in fields
}
except RecordFluxError:
pass
def __hash__(self) -> int:
return hash(self.identifier)
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
return (
self.identifier == other.identifier
and self.structure == other.structure
and self.types == other.types
and self.byte_order == other.byte_order
and self.checksums == other.checksums
)
return NotImplemented
def __repr__(self) -> str:
return verbose_repr(self, ["identifier", "structure", "types", "checksums", "byte_order"])
def __str__(self) -> str:
if not self.structure or not self.types:
return f"type {self.name} is null message"
parameters = "; ".join(
[
f"{p.identifier} : {type_identifier}"
for p, t in self.parameter_types.items()
for type_identifier in (
t.name if mty.is_builtin_type(t.identifier) else t.identifier,
)
]
)
if parameters:
parameters = f" ({parameters})"
fields = ""
field_list = [INITIAL, *self.fields]
for i, f in enumerate(field_list):
if f != INITIAL:
fields += "\n" if fields else ""
fields += f"{f.name} : {self.types[f].name}"
outgoing = self.outgoing(f)
if not (
len(outgoing) == 1
and outgoing[0].condition == expr.TRUE
and outgoing[0].size == expr.UNDEFINED
and outgoing[0].first == expr.UNDEFINED
and (i >= len(field_list) - 1 or field_list[i + 1] == outgoing[0].target)
):
if f == INITIAL:
fields += "null"
fields += "\n" + indent("\n".join(str(o) for o in outgoing), 3)
if fields:
fields += ";"
return f"type {self.name}{parameters} is\n message\n{indent(fields, 6)}\n end message"
@property
def dependencies(self) -> List[mty.Type]:
return [self, *unique(a for t in self.__types.values() for a in t.dependencies)]
@abstractmethod
def copy(
self,
identifier: StrID = None,
structure: Sequence[Link] = None,
types: Mapping[Field, mty.Type] = None,
checksums: Mapping[ID, Sequence[expr.Expr]] = None,
byte_order: ByteOrder = None,
location: Location = None,
error: RecordFluxError = None,
) -> "AbstractMessage":
raise NotImplementedError
@abstractmethod
def proven(self, skip_proof: bool = False, workers: int = 1) -> "Message":
raise NotImplementedError
@property
def parameters(self) -> Tuple[Field, ...]:
return tuple(self._state.parameter_types or {})
@property
def fields(self) -> Tuple[Field, ...]:
"""Return fields topologically sorted."""
return tuple(self._state.field_types or {})
@property
def all_fields(self) -> Tuple[Field, ...]:
return (INITIAL, *self.fields, FINAL)
@property
def parameter_types(self) -> Mapping[Field, mty.Type]:
"""Return parameters and corresponding types."""
return self._state.parameter_types
@property
def field_types(self) -> Mapping[Field, mty.Type]:
"""Return fields and corresponding types topologically sorted."""
return self._state.field_types
@property
def types(self) -> Mapping[Field, mty.Type]:
"""Return parameters, fields and corresponding types topologically sorted."""
return {**self._state.parameter_types, **self._state.field_types}
@property
def checksums(self) -> Mapping[ID, Sequence[expr.Expr]]:
return self._checksums
def incoming(self, field: Field) -> List[Link]:
return [l for l in self.structure if l.target == field]
def outgoing(self, field: Field) -> List[Link]:
return [l for l in self.structure if l.source == field]
def predecessors(self, field: Field) -> Tuple[Field, ...]:
if field == INITIAL:
return ()
if field == FINAL:
return self.fields
return self.fields[: self.fields.index(field)]
def successors(self, field: Field) -> Tuple[Field, ...]:
if field == INITIAL:
return self.fields
if field == FINAL:
return ()
return self.fields[self.fields.index(field) + 1 :]
def direct_predecessors(self, field: Field) -> List[Field]:
return list(dict.fromkeys([l.source for l in self.incoming(field)]))
def direct_successors(self, field: Field) -> List[Field]:
return list(dict.fromkeys([l.target for l in self.outgoing(field)]))
def definite_predecessors(self, field: Field) -> Tuple[Field, ...]:
"""Return preceding fields which are part of all possible paths."""
if self._state.definite_predecessors is None:
self._state.definite_predecessors = {
f: self.__compute_definite_predecessors(f) for f in self.all_fields
}
return self._state.definite_predecessors[field]
def path_condition(self, field: Field) -> expr.Expr:
"""Return conjunction of all conditions on path from INITIAL to field."""
if self._state.path_condition is None:
self._state.path_condition = {
f: self.__compute_path_condition(f).simplified() for f in self.all_fields
}
return self._state.path_condition[field]
def field_size(self, field: Field) -> expr.Number:
"""Return field size if field size is fixed and fail otherwise."""
if field == FINAL:
return expr.Number(0)
assert field in self.fields, f'field "{field.name}" not found'
field_type = self.types[field]
if isinstance(field_type, mty.Scalar):
return field_type.size
sizes = [
l.size.substituted(mapping=to_mapping(self.type_constraints(expr.TRUE))).simplified()
for l in self.incoming(field)
]
size = sizes[0]
if isinstance(size, expr.Number) and all(size == s for s in sizes):
return size
fail(
f'unable to calculate size of field "{field.name}" of message "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
field.identifier.location,
)
def paths(self, field: Field) -> Set[Tuple[Link, ...]]:
if field == INITIAL:
return set()
if field in self.__paths_cache:
return self.__paths_cache[field]
result = set()
for l in self.incoming(field):
source = self.paths(l.source)
for s in source:
result.add(s + (l,))
if not source:
result.add((l,))
self.__paths_cache[field] = result
return result
def prefixed(self, prefix: str) -> "AbstractMessage":
fields = {f.identifier for f in self.fields}
def prefixed_expression(expression: expr.Expr) -> expr.Expr:
variables = {v.identifier for v in expression.variables()}
literals = {l for l in variables - fields if len(l.parts) == 1}
return expression.substituted(
mapping={
**{
v: v.__class__(ID(prefix) + v.name)
for v in expression.variables()
if v.identifier in fields
},
**{
v: v.__class__(self.package * v.name)
for v in expression.variables()
if v.identifier in literals
and v.identifier not in mty.BUILTIN_LITERALS
and v.identifier != ID("Message")
and Field(v.identifier) not in self.parameters
},
}
).simplified()
structure = []
for l in self.structure:
source = Field(prefix + l.source.identifier) if l.source != INITIAL else INITIAL
target = Field(prefix + l.target.identifier) if l.target != FINAL else FINAL
condition = prefixed_expression(l.condition)
size = prefixed_expression(l.size)
first = prefixed_expression(l.first)
structure.append(Link(source, target, condition, size, first, l.location))
types = {
**{Field(f.identifier): t for f, t in self.parameter_types.items()},
**{Field(prefix + f.identifier): t for f, t in self.field_types.items()},
}
return self.copy(structure=structure, types=types)
def type_constraints(self, expression: expr.Expr) -> List[expr.Expr]:
def get_constraints(aggregate: expr.Aggregate, field: expr.Variable) -> Sequence[expr.Expr]:
comp = self.__types[Field(field.name)]
assert isinstance(comp, mty.Composite)
result = expr.Equal(
expr.Mul(aggregate.length, comp.element_size),
expr.Size(field),
location=expression.location,
)
if isinstance(comp, mty.Sequence) and isinstance(comp.element_type, mty.Scalar):
return [
result,
*comp.element_type.constraints(name=comp.element_type.name, proof=True),
]
return [result]
scalar_types = [
(f.name, t)
for f, t in self.__types.items()
if isinstance(t, mty.Scalar)
and ID(f.name) not in self._qualified_enum_literals
and f.name not in ["Message", "Final"]
]
aggregate_constraints: List[expr.Expr] = []
for r in expression.findall(lambda x: isinstance(x, (expr.Equal, expr.NotEqual))):
assert isinstance(r, (expr.Equal, expr.NotEqual))
if isinstance(r.left, expr.Aggregate) and isinstance(r.right, expr.Variable):
aggregate_constraints.extend(get_constraints(r.left, r.right))
if isinstance(r.left, expr.Variable) and isinstance(r.right, expr.Aggregate):
aggregate_constraints.extend(get_constraints(r.right, r.left))
scalar_constraints = [
c
for n, t in scalar_types
for c in t.constraints(name=n, proof=True, same_package=False)
]
type_size_constraints = [
expr.Equal(expr.Size(l), t.size)
for l, t in self._type_literals.items()
if isinstance(t, mty.Scalar)
]
return [
*aggregate_constraints,
*scalar_constraints,
*type_size_constraints,
]
@classmethod
def message_constraints(cls) -> List[expr.Expr]:
return [
expr.Equal(expr.Mod(expr.First("Message"), expr.Number(8)), expr.Number(1)),
expr.Equal(expr.Mod(expr.Size("Message"), expr.Number(8)), expr.Number(0)),
]
def __validate(self) -> None:
type_fields = {*self.__types.keys(), INITIAL, FINAL}
structure_fields = {l.source for l in self.structure} | {l.target for l in self.structure}
self._validate_types(type_fields, structure_fields)
self._validate_initial_link()
self._validate_names(type_fields)
self.error.propagate()
self._validate_structure(structure_fields)
self._validate_link_aspects()
def _validate_types(self, type_fields: Set[Field], structure_fields: Set[Field]) -> None:
parameters = self.__types.keys() - structure_fields
for p in parameters:
parameter_type = self.__types[p]
if not isinstance(parameter_type, mty.Scalar):
self.error.extend(
[
(
"parameters must have a scalar type",
Subsystem.MODEL,
Severity.ERROR,
p.identifier.location,
)
]
)
elif isinstance(parameter_type, mty.Enumeration) and parameter_type.always_valid:
self.error.extend(
[
(
"always valid enumeration types not allowed as parameters",
Subsystem.MODEL,
Severity.ERROR,
p.identifier.location,
)
]
)
for f in structure_fields - type_fields:
self.error.extend(
[
(
f'missing type for field "{f.name}" in "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
f.identifier.location,
)
],
)
def _validate_initial_link(self) -> None:
initial_links = self.outgoing(INITIAL)
if len(initial_links) != 1:
self.error.extend(
[
(
f'ambiguous first field in "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
self.location,
),
*[
("duplicate", Subsystem.MODEL, Severity.INFO, l.target.identifier.location)
for l in self.outgoing(INITIAL)
if l.target.identifier.location
],
]
)
if initial_links[0].first != expr.UNDEFINED:
self.error.extend(
[
(
"illegal first aspect at initial link",
Subsystem.MODEL,
Severity.ERROR,
initial_links[0].first.location,
)
],
)
def _validate_names(self, type_fields: Set[Field]) -> None:
name_conflicts = [
(f, l)
for f in type_fields
for l in self._unqualified_enum_literals
if f.identifier == l
]
if name_conflicts:
conflicting_field, conflicting_literal = name_conflicts.pop(0)
self.error.extend(
[
(
f'name conflict for field "{conflicting_field.name}" in'
f' "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
conflicting_field.identifier.location,
),
(
"conflicting enumeration literal",
Subsystem.MODEL,
Severity.INFO,
conflicting_literal.location,
),
],
)
def _validate_structure(self, structure_fields: Set[Field]) -> None:
for f in structure_fields:
for l in self.structure:
if f in (INITIAL, l.target):
break
else:
self.__has_unreachable = True
self.error.extend(
[
(
f'unreachable field "{f.name}" in "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
f.identifier.location,
)
],
)
duplicate_links = defaultdict(list)
for link in self.structure:
duplicate_links[(link.source, link.target, link.condition)].append(link)
for links in duplicate_links.values():
if len(links) > 1:
self.error.extend(
[
(
f'duplicate link from "{links[0].source.identifier}"'
f' to "{links[0].target.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
links[0].source.identifier.location,
),
*[
(
"duplicate link",
Subsystem.MODEL,
Severity.INFO,
l.location,
)
for l in links
],
]
)
def _validate_link_aspects(self) -> None:
for link in self.structure:
exponentiations = itertools.chain.from_iterable(
e.findall(lambda x: isinstance(x, expr.Pow))
for e in [link.condition, link.first, link.size]
)
for e in exponentiations:
assert isinstance(e, expr.Pow)
variables = e.right.findall(lambda x: isinstance(x, expr.Variable))
if variables:
self.error.extend(
[
(
f'unsupported expression in "{self.identifier}"',
Subsystem.MODEL,
Severity.ERROR,
e.location,
),
*[
(
f'variable "{v}" in exponent',
Subsystem.MODEL,
Severity.INFO,
v.location,
)
for v in variables
],
]
)
if link.has_implicit_size:
if any(l.target != FINAL for l in self.outgoing(link.target)):
self.error.extend(
[
(
'"Message" must not be used in size aspects',
Subsystem.MODEL,
Severity.ERROR,
link.size.location,
),
]
)
else:
valid_definitions = (
[
expr.Add(expr.Last("Message"), -expr.Last(link.source.name)),
expr.Sub(expr.Last("Message"), expr.Last(link.source.name)),
]
if link.source != INITIAL
else [
expr.Size("Message"),
expr.Sub(expr.Last("Message"), expr.Last(INITIAL.name)),
]
)
if link.size not in valid_definitions:
self.error.extend(
[
(
'invalid use of "Message" in size aspect',
Subsystem.MODEL,
Severity.ERROR,
link.size.location,
),
(
"remove size aspect to define field with implicit size",
Subsystem.MODEL,
Severity.INFO,
link.size.location,
),
]
)
def __normalize(self) -> None:
"""
Normalize structure of message.
Qualify enumeration literals in conditions to prevent ambiguities. Add size expression for
fields with implicit size.
"""
def qualify_enum_literals(expression: expr.Expr) -> expr.Expr:
if (
isinstance(expression, expr.Variable)
and expression.identifier in self._unqualified_enum_literals
):
return expr.Variable(
self.package * expression.identifier,
negative=expression.negative,
type_=expression.type_,
location=expression.location,
)
return expression
for link in self.structure:
link.condition = link.condition.substituted(qualify_enum_literals)
if link.size == expr.UNDEFINED and link.target in self.__types:
t = self.__types[link.target]
if isinstance(t, (mty.Opaque, mty.Sequence)) and all(
l.target == FINAL for l in self.outgoing(link.target)
):
if link.source == INITIAL:
link.size = expr.Size(ID("Message", location=link.location))
else:
link.size = expr.Sub(
expr.Last("Message"),
expr.Last(link.source.identifier),
location=link.location,
)
def __compute_topological_sorting(self) -> Optional[Tuple[Field, ...]]:
"""Return fields topologically sorted (Kahn's algorithm)."""
result: Tuple[Field, ...] = ()
fields = [INITIAL]
visited = set()
while fields:
n = fields.pop(0)
result += (n,)
for e in self.outgoing(n):
visited.add(e)
if set(self.incoming(e.target)) <= visited:
fields.append(e.target)
if not self.__has_unreachable and set(self.structure) - visited:
self.error.extend(
[
(
f'structure of "{self.identifier}" contains cycle',
Subsystem.MODEL,
Severity.ERROR,
self.location,
)
],
)
# ISSUE: Componolit/RecordFlux#256
return None
return tuple(f for f in result if f not in [INITIAL, FINAL])
def __compute_definite_predecessors(self, final: Field) -> Tuple[Field, ...]:
return tuple(
f
for f in self.fields
if all(any(f == pf.source for pf in p) for p in self.paths(final))
)
def __compute_path_condition(self, field: Field) -> expr.Expr:
if field == INITIAL:
return expr.TRUE
return expr.Or(
*[
expr.And(self.__compute_path_condition(l.source), l.condition)
for l in self.incoming(field)
],
location=field.identifier.location,
)
class Message(AbstractMessage):
# pylint: disable=too-many-arguments
def __init__(
self,
identifier: StrID,
structure: Sequence[Link],
types: Mapping[Field, mty.Type],
checksums: Mapping[ID, Sequence[expr.Expr]] = None,
byte_order: ByteOrder = None,
location: Location = None,
error: RecordFluxError = None,
state: MessageState = None,
skip_proof: bool = False,
workers: int = 1,
) -> None:
super().__init__(
identifier, structure, types, checksums, byte_order, location, error, state
)
self._refinements: List["Refinement"] = []
self._skip_proof = skip_proof
self.__workers = workers
if not self.error.check() and not skip_proof:
self.verify()
self.error.propagate()
def verify(self) -> None:
if self.structure or self.types:
self.__verify_expression_types()
self.__verify_expressions()
self.__verify_checksums()
self.error.propagate()
self.__prove_conflicting_conditions()
self.__prove_reachability()
self.__prove_contradictions()
self.__prove_coverage()
self.__prove_overlays()
self.__prove_field_positions()
self.__prove_message_size()
self.error.propagate()
def copy(
self,
identifier: StrID = None,
structure: Sequence[Link] = None,
types: Mapping[Field, mty.Type] = None,
checksums: Mapping[ID, Sequence[expr.Expr]] = None,
byte_order: ByteOrder = None,
location: Location = None,
error: RecordFluxError = None,
) -> "Message":
return Message(
identifier if identifier else self.identifier,
structure if structure else copy(self.structure),
types if types else copy(self.types),
checksums if checksums else copy(self.checksums),
byte_order if byte_order else self.byte_order,
location if location else self.location,
error if error else self.error,
skip_proof=self._skip_proof,
)
def proven(self, skip_proof: bool = False, workers: int = 1) -> "Message":
return copy(self)
def is_possibly_empty(self, field: Field) -> bool:
if isinstance(self.types[field], mty.Scalar):
return False
for p in self.paths(FINAL):
if not any(l.target == field for l in p):
continue
empty_field = expr.Equal(expr.Size(field.name), expr.Number(0))
proof = self.__prove_path_property(empty_field, p)
if proof.result == expr.ProofResult.SAT:
return True
return False
def set_refinements(self, refinements: List["Refinement"]) -> None:
if any(r.pdu != self for r in refinements):
fatal_fail("setting refinements for different message", Subsystem.MODEL)
self._refinements = refinements
@property
def type_(self) -> rty.Message:
return rty.Message(
self.full_name,
{
(
*(p.name for p in self.parameters),
*(l.target.name for l in p if l.target != FINAL),
)
for p in self.paths(FINAL)
}
if self.structure
else set(),
{f.identifier: t.type_ for f, t in self._state.parameter_types.items()},
{f.identifier: t.type_ for f, t in self._state.field_types.items()},
[rty.Refinement(r.field.identifier, r.sdu.type_, r.package) for r in self._refinements],
self.is_definite,
)
@property
def has_fixed_size(self) -> bool:
return len(self.paths(FINAL)) <= 1 and not (
{v.identifier for l in self.structure for v in l.size.variables()}
- set(self._type_literals.keys())
)
@property
def has_implicit_size(self) -> bool:
return any(l.has_implicit_size for l in self.structure)
@property
def is_definite(self) -> bool:
"""
Return true if the message has an explicit size, no optional fields and no parameters.
Messages with a First or Last attribute in a size aspect are not yet supported and
therefore considered as not definite.
"""
return (
len(self.paths(FINAL)) <= 1
and not self.has_implicit_size
and all(
not l.size.findall(lambda x: isinstance(x, (expr.First, expr.Last)))
for l in self.structure
for v in l.size.variables()
)
and not self.parameters
)
def size(self, field_values: Mapping[Field, expr.Expr] = None) -> expr.Expr:
field_values = field_values if field_values else {}
def remove_variable_prefix(expression: expr.Expr) -> expr.Expr:
if isinstance(expression, expr.Variable) and expression.name.startswith("RFLX_"):
return expr.Variable(
expression.name[5:],
expression.negative,
expression.immutable,
expression.type_,
location=expression.location,
)
return expression
if not self.structure:
return expr.Number(0)
fields = set(field_values)
values = [
expr.Equal(expr.Variable(f.name), v, location=v.location)
for f, v in field_values.items()
]
aggregate_sizes = [
expr.Equal(expr.Size(f.name), expr.Number(len(v.elements) * 8), location=v.location)
for f, v in field_values.items()
if isinstance(v, expr.Aggregate)
]
composite_sizes = [
expr.Equal(
expr.Size(f.name),
expr.Size(
expr.Variable(
"RFLX_" + v.identifier,
type_=v.type_,
location=v.location,
)
),
)
for f, v in field_values.items()
if isinstance(self.types[f], mty.Composite) and isinstance(v, expr.Variable)
]
failures = []
for path in self.paths(FINAL):
if not self.has_fixed_size and fields != {
*self.parameters,
*(l.target for l in path if l.target != FINAL),
}:
continue
message_size = expr.Add(
*[
expr.Size(link.target.name)
for link in path
if link.target != FINAL and link.first == expr.UNDEFINED
]
)
link_expressions = [
fact
for link in path
for fact in self.__link_expression(link, ignore_implicit_sizes=True)
]
proof = expr.Equal(expr.Size("Message"), message_size).check(
[
*aggregate_sizes,
*composite_sizes,
*link_expressions,
*values,
*self.type_constraints(expr.TRUE),
]
)
if proof.result == expr.ProofResult.SAT:
return (
message_size.substituted(mapping=to_mapping(aggregate_sizes + composite_sizes))
.substituted(mapping=to_mapping(link_expressions))
.substituted(mapping=to_mapping(values))
.substituted(mapping=to_mapping(self.type_constraints(expr.TRUE)))
.substituted(remove_variable_prefix)
.simplified()
)
failures.append((path, proof.error))
error = RecordFluxError()
error.extend(
[
(
f"unable to calculate size for message \"{self.identifier}'("
+ ", ".join(f"{f.identifier} => {v}" for f, v in field_values.items())
+ ')"',
Subsystem.MODEL,
Severity.ERROR,
self.location,
)
],