-
Notifications
You must be signed in to change notification settings - Fork 6
/
message.py
3607 lines (3188 loc) · 134 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
from __future__ import annotations
import itertools
from collections import defaultdict
from collections.abc import Iterable, Mapping, Sequence
from concurrent.futures import ProcessPoolExecutor
from copy import copy
from dataclasses import dataclass, field as dataclass_field
from enum import Enum
from functools import cached_property, partial
from typing import Callable, Optional, Union
import rflx.typing_ as rty
from rflx import expr, expr_proof
from rflx.common import Base, indent, indent_next, unique, verbose_repr
from rflx.const import MP_CONTEXT
from rflx.error import are_all_locations_present, fail, fatal_fail
from rflx.expr import similar_fields
from rflx.identifier import ID, StrID
from rflx.model.top_level_declaration import TopLevelDeclaration
from rflx.rapidflux import Annotation, ErrorEntry, Location, RecordFluxError, Severity
from . import type_decl
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: object) -> bool:
if isinstance(other, self.__class__):
return self.identifier < other.identifier
return NotImplemented
@property
def name(self) -> str:
return str(self.identifier)
@property
def affixed_name(self) -> str:
return f"F_{self.name}"
INITIAL = Field(ID("Initial", location=Location((1, 1))))
FINAL = Field(ID("Final", location=Location((1, 1))))
@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")]))
class Message(type_decl.TypeDecl):
def __init__( # noqa: PLR0913
self,
identifier: StrID,
structure: Sequence[Link],
types: Mapping[Field, type_decl.TypeDecl],
checksums: Optional[Mapping[ID, Sequence[expr.Expr]]] = None,
byte_order: Optional[Union[ByteOrder, Mapping[Field, ByteOrder]]] = None,
location: Optional[Location] = None,
skip_verification: bool = False,
workers: int = 1,
) -> None:
assert not types if not structure else True
super().__init__(identifier, location)
self.error.propagate()
if not structure:
structure = [Link(INITIAL, FINAL)]
self._structure = sorted(structure)
self._checksums = checksums or {}
self._byte_order = {}
self._field_types = {}
self._parameter_types = {}
self._first: dict[Link, tuple[Field, expr.Expr]] = {}
dependencies = _dependencies(types)
self._unqualified_enum_literals = type_decl.unqualified_enum_literals(
dependencies,
self.package,
)
self._qualified_enum_literals = type_decl.qualified_enum_literals(dependencies)
self._type_names = type_decl.qualified_type_names(dependencies)
self._paths_cache: dict[Field, set[tuple[Link, ...]]] = {}
self._definite_predecessors_cache: dict[Field, tuple[Field, ...]] = {}
self._path_condition_cache: dict[Field, expr.Expr] = {}
try:
if not self.is_null:
self._has_unreachable = self._validate(self._structure, types)
self._structure, self._checksums = self._normalize(
self._structure,
types,
self._checksums,
)
fields = self._compute_topological_sorting(self._has_unreachable)
if fields:
# The fields of `types` are used to preserve the locations of the field
# definitions. `fields` cannot be used directly, as it contains the field
# identifiers of link targets.
ft = {f: (f, t) for f, t in types.items()}
self._field_types = dict(ft[f] for f in fields)
self._parameter_types = dict(ft[f] for f in types if f not in fields)
self._set_types()
byte_order = byte_order if byte_order else ByteOrder.HIGH_ORDER_FIRST
if not isinstance(byte_order, dict):
assert isinstance(byte_order, ByteOrder)
self._byte_order = {f: byte_order for f in self.fields}
else:
assert all(f in byte_order for f in self.fields)
assert (
all(f in self.fields for f in byte_order) if not self._has_unreachable else True
)
self._byte_order = byte_order
except RecordFluxError:
pass
self.error.propagate()
self._refinements: list[Refinement] = []
self._skip_verification = skip_verification
self._workers = workers
if not self.error.has_errors() and not skip_verification:
self._verify()
self._check_identifiers(structure, types)
self.error.propagate()
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 self.is_null:
return f"type {self.name} is null message"
parameters = "; ".join(
[
f"{parameter_field.identifier} : {parameter_type_identifier}"
for parameter_field, parameter_type in self.parameter_types.items()
for parameter_type_identifier in (parameter_type.qualified_identifier,)
],
)
if parameters:
parameters = f" ({parameters})"
fields = ""
field_list = [INITIAL, *self.fields]
for i, field in enumerate(field_list):
if field != INITIAL:
fields += "\n" if fields else ""
field_type_identifier = self.types[field].qualified_identifier
fields += f"{field.name} : {field_type_identifier}"
outgoing = self.outgoing(field)
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 field == INITIAL:
fields += "null"
fields += "\n" + indent("\n".join(str(o) for o in outgoing), 3)
if fields:
fields += ";"
checksum_aspect = ""
if self.checksums:
checksums = ", ".join(
[
f'{identifier} => ({", ".join(str(e) for e in expressions)})'
for identifier, expressions in self.checksums.items()
],
)
checksum_aspect = f"Checksum => ({checksums})"
aspects = ""
if checksum_aspect:
aspects = f" with\n{indent(checksum_aspect, 6)}"
return (
f"type {self.name}{parameters} is\n message\n{indent(fields, 6)}\n end message"
f"{aspects}"
)
@property
def is_null(self) -> bool:
return self._structure == [Link(INITIAL, FINAL)] and not self.types
@property
def direct_dependencies(self) -> list[type_decl.TypeDecl]:
return [*self.types.values(), self]
@property
def dependencies(self) -> list[type_decl.TypeDecl]:
return [*_dependencies(self.types), self]
@property
def byte_order(self) -> Mapping[Field, ByteOrder]:
return self._byte_order
def copy( # noqa: PLR0913
self,
identifier: Optional[StrID] = None,
structure: Optional[Sequence[Link]] = None,
types: Optional[Mapping[Field, type_decl.TypeDecl]] = None,
checksums: Optional[Mapping[ID, Sequence[expr.Expr]]] = None,
byte_order: Optional[Union[ByteOrder, Mapping[Field, ByteOrder]]] = None,
location: Optional[Location] = None,
skip_verification: Optional[bool] = 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 copy(self.byte_order),
location if location else self.location,
skip_verification if skip_verification else self._skip_verification,
)
@property
def parameters(self) -> tuple[Field, ...]:
return tuple(self._parameter_types or {})
@property
def fields(self) -> tuple[Field, ...]:
"""Return fields topologically sorted."""
return tuple(self._field_types or {})
@property
def all_fields(self) -> tuple[Field, ...]:
return (INITIAL, *self.fields, FINAL)
@property
def parameter_types(self) -> Mapping[Field, type_decl.TypeDecl]:
"""Return parameters and corresponding types."""
return self._parameter_types
@property
def field_types(self) -> Mapping[Field, type_decl.TypeDecl]:
"""Return fields and corresponding types topologically sorted."""
return self._field_types
@property
def structure(self) -> Sequence[Link]:
return self._structure
@property
def types(self) -> Mapping[Field, type_decl.TypeDecl]:
"""Return parameters, fields and corresponding types topologically sorted."""
return {**self._parameter_types, **self._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."""
try:
return self._definite_predecessors_cache[field]
except KeyError:
result = tuple(
f
for f in self.fields
if all(any(f == pf.source for pf in p) for p in self.paths(field))
)
self._definite_predecessors_cache[field] = result
return result
def path_condition(self, field: Field) -> expr.Expr:
"""Return conjunction of all conditions on path from INITIAL to field."""
try:
return self._path_condition_cache[field]
except KeyError:
if field == INITIAL:
return expr.TRUE
result = expr.Or(
*[
expr.And(
self.path_condition(l.source),
l.condition,
location=l.condition.location,
)
for l in self.incoming(field)
],
location=field.identifier.location,
).simplified()
self._path_condition_cache[field] = result
return result
def field_size_opt(self, field: Field) -> Optional[expr.Number]:
"""Return field size if field size is fixed and None 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, type_decl.Scalar):
return field_type.size
sizes = [
l.size.substituted(mapping=to_mapping(self.message_constraints)).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
return None
def field_size(self, field: Field) -> expr.Number:
"""Return field size if field size is fixed and fail otherwise."""
result = self.field_size_opt(field)
if result is not None:
return result
fail(
f'unable to calculate size of field "{field.name}" of message "{self.identifier}"',
Severity.ERROR,
field.identifier.location,
)
def paths(self, field: Field) -> set[tuple[Link, ...]]:
try:
return self._paths_cache[field]
except KeyError:
if field == INITIAL:
return set()
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) -> Message:
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, v.identifier.location),
location=v.location,
)
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 type_decl.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()},
}
checksums = (
{prefix + i: [prefixed_expression(e) for e in e] for i, e in self.checksums.items()}
if self.checksums
else self.checksums
)
byte_order = {Field(prefix + f.identifier): t for f, t in self.byte_order.items()}
return self.copy(
structure=structure,
types=types,
checksums=checksums,
byte_order=byte_order,
skip_verification=True,
)
def typed_expression(
self,
expression: expr.Expr,
types: Mapping[Field, type_decl.TypeDecl],
) -> expr.Expr:
return typed_expression(expression, types, self._qualified_enum_literals, self._type_names)
@cached_property
def message_constraints(self) -> list[expr.Expr]:
return message_constraints(self.types, self._qualified_enum_literals, self._type_names)
def aggregate_constraints(self, expression: expr.Expr) -> list[expr.Expr]:
return aggregate_constraints(expression, self.types)
def is_possibly_empty(self, field: Field) -> bool:
if isinstance(self.types[field], type_decl.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_proof.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")
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 not self.is_null
else set()
),
{f.identifier: t.type_ for f, t in self._parameter_types.items()},
{f.identifier: t.type_ for f, t in self._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_names.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 condition or size aspect are not yet supported
and therefore considered as not definite. This is also the case for messages containing
sequences.
"""
return (
len(self.paths(FINAL)) <= 1
and not self.has_implicit_size
and all(
not l.condition.findall(lambda x: isinstance(x, (expr.First, expr.Last)))
for l in self.structure
for v in l.condition.variables()
)
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
and not any(isinstance(t, type_decl.Sequence) for t in self.types.values())
)
def size(
self,
field_values: Optional[Mapping[Field, expr.Expr]] = None,
message_instance: Optional[ID] = None,
subpath: bool = False,
) -> expr.Expr:
"""
Determine the size of the message based on the given field values.
If field values are represented by variables, the returned size expression may contain
if-expressions to represent these dependencies. Only message paths which contain all given
fields are considered. The evaluation of the returned size expression may result in a size
greater than zero, even if the field values do not lead to a valid message.
The message fields can be prefixed by the message instance.
The size calculation can be restricted to the size of a subpath. The subpath is defined by
the given field values.
"""
field_values = field_values if field_values else {}
if subpath:
if not field_values:
return expr.Number(0)
fields = list(field_values)
possible_paths = [
p
for p in sorted(self.paths(FINAL))
if any(
fields == [l.target for l in p[i : len(fields) + i]]
for i in range(len(p) - len(fields) + 1)
)
]
if not possible_paths:
subpath_str = " -> ".join(f.name for f in fields)
fail(
f'unable to calculate size of invalid subpath "{subpath_str}"'
f' of message "{self.identifier}"',
Severity.ERROR,
self.location,
)
else:
if self.is_null:
return expr.Number(0)
fields = list(self.fields)
possible_paths = [
path
for path in sorted(self.paths(FINAL))
if not (
set(field_values)
- set(self.parameters)
- {l.target for l in path if l.target != FINAL}
)
]
def add_message_prefix(expression: expr.Expr) -> expr.Expr:
if (
message_instance
and isinstance(expression, expr.Variable)
and Field(expression.identifier) in self.types
):
return expr.Selected(
expr.Variable(
message_instance,
type_=self.type_,
location=message_instance.location,
),
expression.identifier,
type_=expression.type_,
location=expression.location,
)
return expression
def remove_variable_prefix(expression: expr.Expr) -> expr.Expr:
"""
Remove prefix from variables.
The prefix is used to prevent name conflicts between field values and field names.
"""
if isinstance(expression, expr.Variable) and expression.name.startswith("RFLX_"):
return expression.copy(identifier=expression.name[5:])
if (
isinstance(expression, expr.Selected)
and isinstance(expression.prefix, expr.Variable)
and expression.prefix.name.startswith("RFLX_")
):
return expression.copy(
prefix=expression.prefix.copy(identifier=expression.prefix.name[5:]),
)
return expression
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 = []
for f, v in field_values.items():
if isinstance(self.types[f], type_decl.Composite):
if isinstance(v, expr.Variable):
composite_sizes.append(
expr.Equal(
expr.Size(f.name),
expr.Size(v.copy(identifier="RFLX_" + v.identifier)),
),
)
if isinstance(v, expr.Selected) and isinstance(v.prefix, expr.Variable):
composite_sizes.append(
expr.Equal(
expr.Size(f.name),
expr.Size(
v.copy(
prefix=v.prefix.copy(identifier="RFLX_" + v.prefix.identifier),
),
),
),
)
facts: list[expr.Expr] = [*values, *aggregate_sizes, *composite_sizes]
type_constraints = to_mapping(self._type_size_constraints())
definite_fields = set.intersection(*[{l.target for l in path} for path in possible_paths])
optional_fields = set(fields) - definite_fields
conditional_field_size = []
for field in fields:
locations = [
l.condition.location for l in self.incoming(field) if l.first != expr.UNDEFINED
]
overlay_condition = expr.Not(
expr.Or(*[l.condition for l in self.incoming(field) if l.first != expr.UNDEFINED]),
location=Location.merge(locations),
).simplified()
paths_to_field = sorted(
{
path[
: {f: i for i, f in enumerate(l.target for l in path if l.target != FINAL)}[
field
]
+ 1
]
for path in possible_paths
if any(l.target == field for l in path)
},
)
for path in paths_to_field:
link_size_expressions = [
fact for link in path for fact in self._link_size_constraints(link)
]
path_conditions = [l.condition for l in path if l.condition != expr.TRUE]
path_condition = (
expr.And(
*path_conditions,
overlay_condition,
location=Location.merge([c.location for c in path_conditions]),
)
.substituted(mapping=to_mapping(link_size_expressions + facts))
.substituted(mapping=type_constraints)
.substituted(add_message_prefix)
.substituted(remove_variable_prefix)
.simplified()
)
field_size = (
expr.Size(expr.Variable(field.name, type_=self.types[field].type_))
.substituted(mapping=to_mapping(link_size_expressions + facts))
.substituted(mapping=type_constraints)
.substituted(add_message_prefix)
.substituted(remove_variable_prefix)
)
conditional_field_size.append(
(
(
expr.TRUE
if len(paths_to_field) == 1
and (
path_condition == expr.TRUE
or (field not in optional_fields and overlay_condition == expr.TRUE)
)
else path_condition
),
field_size,
),
)
return (
expr.Add(
*[
(
expr.IfExpr([(path_condition, field_size)], expr.Number(0))
if path_condition != expr.TRUE
else field_size
)
for path_condition, groups in itertools.groupby(
sorted(conditional_field_size),
lambda x: x[0],
)
for field_size in [expr.Add(*(s for _, s in groups))]
],
)
.substituted(mapping=to_mapping(values))
.simplified()
)
def max_size(self) -> expr.Number:
if self.is_null:
return expr.Number(0)
if self.has_implicit_size:
fail(
"unable to calculate maximum size of message with implicit size",
Severity.ERROR,
self.location,
)
max_size = expr.Number(0)
for path in self.paths(FINAL):
max_size = max(max_size, self._max_value(expr.Size("Message"), path))
return max_size
def max_field_sizes(self) -> dict[Field, expr.Number]:
if self.is_null:
return {}
if self.has_implicit_size:
fail(
"unable to calculate maximum field sizes of message with implicit size",
Severity.ERROR,
self.location,
)
result = {f: expr.Number(0) for f in self.fields}
for path in self.paths(FINAL):
for l in path[:-1]:
result[l.target] = max(
result[l.target],
self._max_value(expr.Size(l.target.name), path),
)
return result
def link_first(self, link: Link) -> tuple[Field, expr.Expr]:
"""
Express position of link target based on previous links.
Compute a pair (node, distance) to express the position of `link.target`,
assuming `link` was followed. The meaning is
link.target'first = node'first + distance
The distance is an expression that might contain references to sizes of
other fields, using `expr.Size(fld.affixed_name)`. These references are
to be replaced by the size of the corresponding field.
"""
if link not in self._first:
result = self._compute_first(link)
self._first[link] = result
return result
return self._first[link]
def field_first(self, fld: Field) -> tuple[Field, expr.Expr]:
"""
Express position of field based on predecessor fields.
Compute a pair (node, distance) to express the position of `fld`. See
the comment of `link_first` for the exact meaning of the distance and
contents of the distance expression. This function returns (fld, 0) if
`fld` has several incoming links.
"""
incoming = [l for l in self.structure if l.target == fld]
if len(incoming) == 1:
return self.link_first(incoming[0])
return (fld, expr.Number(0))
def _type_size_constraints(self) -> list[expr.Expr]:
return _type_size_constraints(self._type_names)
def _validate(
self,
structure: Sequence[Link],
types: Mapping[Field, type_decl.TypeDecl],
) -> bool:
type_fields = {*types, INITIAL, FINAL}
structure_fields = {l.source for l in structure} | {l.target for l in structure}
self._validate_types(types, type_fields, structure_fields)
self._validate_initial_link()
self._validate_names(type_fields)
self.error.propagate()
has_unreachable = self._validate_structure(structure_fields)
self._validate_link_aspects()
return has_unreachable
def _validate_types(
self,
types: Mapping[Field, type_decl.TypeDecl],
type_fields: set[Field],
structure_fields: set[Field],
) -> None:
parameters = type_fields - structure_fields - {INITIAL, FINAL}
for f, t in types.items():
if f in structure_fields and not isinstance(
t,
(type_decl.Scalar, type_decl.Composite, Message),
):
self.error.extend(
[
ErrorEntry(
"message fields must have a scalar or composite type",
Severity.ERROR,
f.identifier.location,
),
],
)
if f in parameters:
if not isinstance(t, type_decl.Scalar):
assert f.identifier.location is not None
additionnal_annotations = []
if not (
type_decl.is_builtin_type(t.identifier)
or type_decl.is_internal_type(t.identifier)
):
assert t.identifier.location is not None
additionnal_annotations.append(
Annotation(
"type declared here",
Severity.NOTE,
t.identifier.location,
),
)
self.error.extend(
rty.check_type_instance(
t.type_,
(rty.Enumeration, rty.AnyInteger),
location=f.identifier.location,
additionnal_annotations=additionnal_annotations,
).entries,
)
elif isinstance(t, type_decl.Enumeration) and t.always_valid:
self.error.push(
ErrorEntry(
"always valid enumeration types not allowed as parameters",
Severity.ERROR,
f.identifier.location,
),
)
for f in structure_fields - type_fields:
self.error.push(
ErrorEntry(
f'missing type for field "{f.name}"',
Severity.ERROR,
f.identifier.location,
),
)
def _validate_initial_link(self) -> None:
initial_links = self.outgoing(INITIAL)
if any(l.first != expr.UNDEFINED for l in initial_links):
self.error.extend(
[
ErrorEntry(
"illegal first aspect on initial link",
Severity.ERROR,
l.first.location,
)
for l in initial_links
if l.first != expr.UNDEFINED
],
)
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)
assert conflicting_literal.location is not None
self.error.push(
ErrorEntry(
f'name conflict for field "{conflicting_field.name}" in'
f' "{self.identifier}"',
Severity.ERROR,
conflicting_field.identifier.location,