Repository navigation
Expand file tree
/
Copy pathgenerate_packets.py
More file actions
executable file
·4534 lines (3675 loc) · 145 KB
/
Copy pathgenerate_packets.py
File metadata and controls
executable file
·4534 lines (3675 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Freeciv - Copyright (C) 2003 - Raimar Falke
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# This script runs under Python 3.6 and up. Please leave it so.
# It might also run under older versions, but no such guarantees are made.
import re
import argparse
import sys
from pathlib import Path
from contextlib import contextmanager, ExitStack
from functools import partial
from itertools import chain, combinations, takewhile, zip_longest
from enum import Enum
from abc import ABC, abstractmethod
try:
from functools import cache
except ImportError:
from functools import lru_cache
cache = lru_cache(None)
del lru_cache
import typing
T_co = typing.TypeVar("T_co", covariant = True)
###################### Parsing Command Line Arguments ######################
def file_path(s: "str | Path") -> Path:
"""Parse the given path and check basic validity."""
path = Path(s)
if path.is_reserved() or not path.name:
raise ValueError(f"not a valid file path: {s!r}")
if path.exists() and not path.is_file():
raise ValueError(f"not a file: {s!r}")
return path
class ScriptConfig:
"""Contains configuration info for the script's execution, along with
functions closely tied to that configuration"""
def_paths: "list[Path]"
"""Paths to definition files, in load order"""
common_header_path: "Path | None"
"""Output path for the common header, or None if that should not
be generated"""
common_impl_path: "Path | None"
"""Output path for the common implementation, or None if that
should not be generated"""
server_header_path: "Path | None"
"""Output path for the server header, or None if that should not
be generated"""
server_impl_path: "Path | None"
"""Output path for the server implementation, or None if that
should not be generated"""
client_header_path: "Path | None"
"""Output path for the client header, or None if that should not
be generated"""
client_impl_path: "Path | None"
"""Output path for the client implementation, or None if that
should not be generated"""
verbose: bool
"""Whether to enable verbose logging"""
lazy_overwrite: bool
"""Whether to lazily overwrite output files"""
gen_stats: bool
"""Whether to generate delta stats code"""
log_macro: "str | None"
"""The macro used for log calls, or None if no log calls should
be generated"""
fold_bool: bool
"""Whether to fold boolean fields into the packet header"""
@staticmethod
def get_argparser() -> argparse.ArgumentParser:
"""Construct an argument parser for a packet generation script"""
parser = argparse.ArgumentParser(
description = "Generate packet-related code from packets.def",
add_help = False, # we'll add a help option explicitly
)
# Argument groups
# Note the order:
# We want the path arguments to show up *first* in the help text
paths = parser.add_argument_group(
"Input and output paths",
"The following parameters decide which files to read and write."
" Omitting an output path will not generate that file.",
)
script = parser.add_argument_group(
"Script configuration",
"The following parameters change how the script operates.",
)
output = parser.add_argument_group(
"Output configuration",
"The following parameters change the amount of output.",
)
protocol = parser.add_argument_group(
"Protocol configuration",
"The following parameters CHANGE the protocol."
" You have been warned.",
)
# Individual arguments
# Note the order:
# We want the path arguments to show up *last* in the usage summary
script.add_argument("-h", "--help", action = "help",
help = "show this help message and exit")
script.add_argument("-v", "--verbose", action = "store_true",
help = "enable log messages during code generation")
# When enabled: Only overwrite existing output files when they
# actually changed. This prevents the build system from rebuilding all
# dependents in cases where that wouldn't even be necessary.
script.add_argument("--lazy-overwrite", action = "store_true",
help = "only overwrite output files when their"
" contents actually changed")
output.add_argument("-s", "--gen-stats", action = "store_true",
help = "generate code reporting packet usage"
" statistics; call delta_stats_report to get these")
logs = output.add_mutually_exclusive_group()
logs.add_argument("-l", "--log-macro", default = "log_packet_detailed",
help = "use the given macro for generated log calls")
logs.add_argument("-L", "--no-logs", dest = "log_macro",
action = "store_const", const = None,
help = "disable generating log calls")
protocol.add_argument("-B", "--no-fold-bool",
dest = "fold_bool", action = "store_false",
help = "explicitly encode boolean values in the"
" packet body, rather than folding them into the"
" packet header")
output_path_args = (
# (dest, option, canonical path)
("common_header_path", "--common-h", "common/packets_gen.h"),
("common_impl_path", "--common-c", "common/packets_gen.c"),
("client_header_path", "--client-h", "client/packhand_gen.h"),
("client_impl_path", "--client-c", "client/packhand_gen.c"),
("server_header_path", "--server-h", "server/hand_gen.h"),
("server_impl_path", "--server-c", "server/hand_gen.c"),
)
for dest, option, canonical in output_path_args:
paths.add_argument(option, dest = dest, type = file_path,
help = f"output path for {canonical}")
paths.add_argument("def_paths", metavar = "def_path",
nargs = "+", type = file_path,
help = "paths to your packets.def file")
return parser
def __init__(self, args: "typing.Sequence[str] | None" = None):
__class__.get_argparser().parse_args(args, namespace = self)
def log_verbose(self, *args):
"""Print the given arguments iff verbose logging is enabled"""
if self.verbose:
print(*args)
@property
def _root_path(self) -> "Path | None":
"""Root Freeciv path, if we can find it."""
path = Path(__file__).absolute()
root = path.parent.parent
if path != root / "common" / "generate_packets.py":
self.log_verbose("Warning: couldn't find Freeciv root path")
return None
return root
def _relative_path(self, path: Path) -> Path:
"""Find the relative path from the Freeciv root to the given path.
Return the path unmodified if it's outside the Freeciv root, or if
the Freeciv root could not be found."""
root = self._root_path
if root is not None:
try:
return path.absolute().relative_to(root)
except ValueError:
self.log_verbose(f"Warning: path {path} outside of Freeciv root")
return path
@property
def _script_path(self) -> Path:
"""Relative path of the executed script. Under normal circumstances,
this will be common/generate_packets.py, but it may differ when this
module is imported from another script."""
return self._relative_path(Path(sys.argv[0]))
def _write_disclaimer(self, f: typing.TextIO):
f.write(f"""\
/**************************************************************************
* THIS FILE WAS GENERATED *
* Script: {self._script_path!s:63} *
""")
for path in self.def_paths:
f.write(f"""\
* Input: {self._relative_path(path)!s:63} *
""")
f.write(f"""\
* DO NOT CHANGE THIS FILE *
**************************************************************************/
""")
@contextmanager
def _wrap_header(self, file: typing.TextIO, header_name: str) -> typing.Iterator[None]:
"""Add multiple inclusion protection to the given file"""
name = f"FC__{header_name.upper()}_H"
file.write(f"""\
#ifndef {name}
#define {name}
""")
yield
file.write(f"""\
#endif /* {name} */
""")
@contextmanager
def _wrap_cplusplus(self, file: typing.TextIO) -> typing.Iterator[None]:
"""Add code for `extern "C" {}` wrapping"""
file.write(f"""\
#ifdef __cplusplus
extern "C" {{
#endif /* __cplusplus */
""")
yield
file.write(f"""\
#ifdef __cplusplus
}}
#endif /* __cplusplus */
""")
@contextmanager
def open_write(self, path: "str | Path", wrap_header: "str | None" = None, cplusplus: bool = True) -> typing.Iterator[typing.TextIO]:
"""Open a file for writing and write disclaimer.
If enabled, lazily overwrites the given file.
If wrap_header is given, add multiple inclusion protection; if
cplusplus is also given (default), also add code for `extern "C"`
wrapping."""
path = Path(path) # no-op if path is already a Path object
self.log_verbose(f"writing {path}")
with ExitStack() as stack:
if self.lazy_overwrite:
file = stack.enter_context(self.lazy_overwrite_open(path))
else:
file = stack.enter_context(path.open("w"))
self._write_disclaimer(file)
if wrap_header is not None:
stack.enter_context(self._wrap_header(file, wrap_header))
if cplusplus:
stack.enter_context(self._wrap_cplusplus(file))
yield file
self.log_verbose(f"done writing {path}")
@contextmanager
def lazy_overwrite_open(self, path: "str | Path", suffix: str = ".tmp") -> typing.Iterator[typing.TextIO]:
"""Open a file for writing, but only actually overwrite it if the new
content differs from the old content.
This creates a temporary file by appending the given suffix to the given
file path. In the event of an error, this temporary file might remain in
the target file's directory."""
path = Path(path)
tmp_path = path.with_name(path.name + suffix)
# if tmp_path already exists, assume it's left over from a previous,
# failed run and can be overwritten without trouble
self.log_verbose(f"lazy: using {tmp_path}")
with tmp_path.open("w") as file:
yield file
if path.exists() and files_equal(tmp_path, path):
self.log_verbose("lazy: no change, deleting...")
tmp_path.unlink()
else:
self.log_verbose("lazy: content changed, replacing...")
tmp_path.replace(path)
################### General helper functions and classes ###################
def files_equal(path_a: "str | Path", path_b: "str | Path") -> bool:
"""Return whether the contents of two text files are identical"""
with open(path_a) as file_a, open(path_b) as file_b:
return all(a == b for a, b in zip_longest(file_a, file_b))
# Taken from https://docs.python.org/3.4/library/itertools.html#itertools-recipes
def powerset(iterable: typing.Iterable[T_co]) -> "typing.Iterator[tuple[T_co, ...]]":
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
INSERT_PREFIX_PATTERN: "typing.Final" = re.compile(r"^(?!#|$)", re.MULTILINE)
"""Matches the beginning of nonempty lines that are not preprocessor
directives, i.e. don't start with a #"""
def prefix(prefix: str, text: str) -> str:
"""Prepend prefix to every line of text, except blank lines and those
starting with #"""
return INSERT_PREFIX_PATTERN.sub(prefix, text)
class Location:
"""Roughly represents a location in memory for the generated code;
outside of recursive field types like arrays, this will usually just be
a field of a packet, but it serves to concisely handle the recursion."""
# placeholder that will clearly be an error if it accidentally
# shows up in generated code
_PACKET = "#error gen_packet$"
_INDICES = "ijk"
name: str
"""The name associated with this location; used in log messages."""
_location: str
"""The actual location as used in code, including placeholders for
where the packet name goes"""
depth: int
"""The array nesting depth of this location; used to determine index
variable names."""
json_depth: int
"""The total sub-location nesting depth of the JSON field address
for this location"""
def __init__(self, name: str, *, location: "str | None" = None,
depth: int = 0, json_depth: "int | None" = None):
self.name = name
self._location = location if location is not None else self._PACKET + name
self.depth = depth
self.json_depth = json_depth if json_depth is not None else depth
@classmethod
@cache
def constant(cls, location: str, name: str = "(unknown)") -> "Location":
"""Construct a Location not dependent on the packet"""
assert cls._PACKET not in location
return cls(name, location = location)
def replace(self, new_location: str) -> "Location":
"""Return the given string as a new Location with the same metadata
as self"""
return type(self)(
name = self.name,
location = new_location,
depth = self.depth,
json_depth = self.json_depth,
)
def deeper(self, new_location: str, json_step: int = 1) -> "Location":
"""Return the given string as a new Location with the same name as
self and incremented depth"""
return type(self)(
name = self.name,
location = new_location,
depth = self.depth + 1,
json_depth = self.json_depth + json_step,
)
def sub_full(self, json_step: int = 1) -> "Location":
"""Like self.sub, but with the option to step the JSON nesting
depth by a different amount."""
return self.deeper(f"{self}[{self.index}]", json_step)
@property
def index(self) -> str:
"""The index name for the current depth"""
if self.depth > len(self._INDICES):
return self._INDICES[0] + str(self.depth) # i3, i4, i5...
return self._INDICES[self.depth]
@property
def sub(self) -> "Location":
"""A location one level deeper with the current index subscript
added to the end.
`field` ~> `field[i]` ~> `field[i][j]` etc."""
return self.sub_full()
@property
def json_subloc(self) -> str:
"""The plocation (JSON field address) to the sub-location
of this location's corresponding field address"""
return "field_addr.sub_location" + self.json_depth * "->sub_location"
def __matmul__(self, packet: "str | None") -> str:
"""self @ packet
Code fragment of this location in the given packet, or in local
variables if packet is None"""
packet = f"{packet}->" if packet is not None else ""
return self._location.replace(self._PACKET, packet)
def __str__(self) -> str:
return self._location
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.name}(depth={self.depth}, json_depth={self.json_depth}) {self @ 'PACKET'}>"
def __eq__(self, other) -> bool:
if other is self:
return True
if not isinstance(other, __class__):
return NotImplemented
return (
self.name == other.name
and self._location == other._location
and self.depth == other.depth
and self.json_depth == other.json_depth
)
def __hash__(self) -> int:
return hash((__class__, self.name, self._location, self.depth, self.json_depth))
#################### Components of a packets definition ####################
class FieldFlags:
"""Information about flags of a given Field. Multiple Field objects can
share one FieldFlags instance, e.g. when defined on the same line."""
ADD_CAP_PATTERN = re.compile(r"^add-cap\(([^()]+)\)$")
"""Matches an add-cap flag (optional capability)"""
REMOVE_CAP_PATTERN = re.compile(r"^remove-cap\(([^()]+)\)$")
"""Matches a remove-cap flag (optional capability)"""
is_key: bool = False
"""Whether the field is a key field"""
diff: bool = False
"""Whether the field should be deep-diffed for transmission"""
add_caps: "set[str]"
"""The capabilities required to enable the field"""
remove_caps: "set[str]"
"""The capabilities that disable the field"""
@classmethod
@cache
def parse(cls, flags_text: str) -> "FieldFlags":
"""Parse a FieldFlags object from a comma-separated flag line"""
return cls(
stripped
for flag in flags_text.split(",")
for stripped in (flag.strip(),)
if stripped
)
def __init__(self, flag_texts: typing.Iterable[str]):
self.add_caps = set()
self.remove_caps = set()
for flag in flag_texts:
if flag == "key":
self.is_key = True
continue
if flag == "diff":
self.diff = True
continue
mo = __class__.ADD_CAP_PATTERN.fullmatch(flag)
if mo is not None:
self.add_caps.add(mo.group(1))
continue
mo = __class__.REMOVE_CAP_PATTERN.fullmatch(flag)
if mo is not None:
self.remove_caps.add(mo.group(1))
continue
raise ValueError(f"unrecognized flag in field declaration: {flag}")
contradictions = self.add_caps & self.remove_caps
if contradictions:
raise ValueError("cannot have same capabilities as both add-cap and remove-cap: " + ", ".join(contradictions))
class SizeInfo:
"""Information about size along one dimension of an array or other sized
field type. Contains both the declared / maximum size, and the actual
used size (if different)."""
ARRAY_SIZE_PATTERN = re.compile(r"^([^:]+)(?:\:([^:]+))?$")
"""Matches an array size declaration (without the brackets)
Groups:
- the declared / maximum size
- the field name for the actual size (optional)"""
declared: Location
"""Maximum size; used in declarations"""
actual: Location
"""Location of the field to use for the actual size."""
@classmethod
@cache
def parse(cls, size_text) -> "SizeInfo":
"""Parse the given array size text (without brackets)"""
mo = cls.ARRAY_SIZE_PATTERN.fullmatch(size_text)
if mo is None:
raise ValueError(f"invalid array size declaration: [{size_text}]")
return cls(*mo.groups())
def __init__(self, declared: str, actual: "str | Location | None"):
self.declared = Location.constant(declared)
if actual is None:
self.actual = self.declared
elif isinstance(actual, Location):
self.actual = actual
else:
self.actual = Location(actual)
@property
def constant(self) -> bool:
"""Whether the actual size doesn't change"""
# Only check whether we were initialized with no actual size;
# we're ignoring the possibility of a constant custom actual size
return self.actual is self.declared
def size_check_get(self, field_name: str, packet: str) -> str:
"""Generate a code snippet checking whether the received size is in
range when receiving a packet."""
if self.constant:
return ""
return f"""\
if ({self.actual @ packet} > {self.declared}) {{
RECEIVE_PACKET_FIELD_ERROR({field_name}, ": array truncated");
}}
"""
def size_check_index(self, field_name: str, packet: str) -> str:
"""Generate a code snippet asserting that indices can be correctly
transmitted for array-diff."""
if self.constant:
return f"""\
FC_STATIC_ASSERT({self.declared} <= MAX_UINT16, packet_array_too_long_{field_name});
"""
else:
return f"""\
fc_assert({self.actual @ packet} <= MAX_UINT16);
"""
def index_put(self, packet: str, index: str) -> str:
"""Generate a code snippet writing the given value to the network
output, encoded as the appropriate index type"""
if self.constant:
return f"""\
#if {self.declared} <= MAX_UINT8
e |= DIO_PUT(uint8, &dout, &field_addr, {index});
#else
e |= DIO_PUT(uint16, &dout, &field_addr, {index});
#endif
"""
else:
return f"""\
if ({self.actual @ packet} <= MAX_UINT8) {{
e |= DIO_PUT(uint8, &dout, &field_addr, {index});
}} else {{
e |= DIO_PUT(uint16, &dout, &field_addr, {index});
}}
"""
def index_get(self, packet: str, location: Location) -> str:
"""Generate a code snippet reading the next index from the
network input decoded as the correct type"""
if self.constant:
return f"""\
#if {self.declared} <= MAX_UINT8
if (!DIO_GET(uint8, &din, &field_addr, &{location.index})) {{
#else
if (!DIO_GET(uint16, &din, &field_addr, &{location.index})) {{
#endif
RECEIVE_PACKET_FIELD_ERROR({location.name});
}}
"""
else:
return f"""\
if (({self.actual @ packet} <= MAX_UINT8)
? !DIO_GET(uint8, &din, &field_addr, &{location.index})
: !DIO_GET(uint16, &din, &field_addr, &{location.index})) {{
RECEIVE_PACKET_FIELD_ERROR({location.name});
}}
"""
def __str__(self) -> str:
if self.constant:
return f"{self.declared}"
elif self.actual.name != self.actual @ None:
# custom location
return "*"
else:
return f"{self.declared}:{self.actual.name}"
def __eq__(self, other) -> bool:
if other is self:
return True
if not isinstance(other, __class__):
return NotImplemented
return (self.declared == other.declared
and self.actual == other.actual)
def __hash__(self) -> int:
return hash((__class__, self.declared, self.actual))
class RawFieldType(ABC):
"""Abstract base class (ABC) for classes representing types defined in a
packets definition file. These types may require the addition of a size
in order to be usable; see the array() method and the FieldType class."""
@abstractmethod
def array(self, size: SizeInfo) -> "FieldType":
"""Add an array size to this field type, either to make a type which
needs a size fully usable, or to make an array type with self as
the element type."""
raise NotImplementedError
@abstractmethod
def __str__(self) -> str:
return super().__str__()
def __repr__(self) -> str:
return f"<{self.__class__.__name__} {self}>"
FieldTypeConstructor: "typing.TypeAlias" = typing.Callable[[str, str], RawFieldType]
class TypeRegistry:
"""Determines what Python class to use for field types based on their
dataio type and public type."""
TYPE_INFO_PATTERN = re.compile(r"^([^()]*)\(([^()]*)\)$")
"""Matches a field type.
Groups:
- dataio type
- public type (aka struct type)"""
dataio_types: "dict[str, FieldTypeConstructor]"
"""Dictionary mapping dataio types to the constructor used for
field types with that dataio type.
This is the primary factor deciding what constructor to use for a
given field type."""
dataio_patterns: "dict[typing.Pattern[str], FieldTypeConstructor]"
"""Dictionary mapping RegEx patterns to the constructor used for
field types whose dataio type matches that pattern.
Matches are cached in self.dataio_types."""
public_types: "dict[str, FieldTypeConstructor]"
"""Like self.dataio_types, but for public types.
This is only checked if there are no matches in self.dataio_types
and self.dataio_patterns."""
public_patterns: "dict[typing.Pattern[str], FieldTypeConstructor]"
"""Like self.dataio_patterns, but for public types.
Matches are cached in self.public_types."""
fallback: FieldTypeConstructor
"""Fallback constructor used when there are no matches for either
dataio type or public type."""
@staticmethod
def _resolve(
key: str,
direct: "dict[str, FieldTypeConstructor]",
patterns: "dict[typing.Pattern[str], FieldTypeConstructor]",
fallback: FieldTypeConstructor
) -> FieldTypeConstructor:
"""Helper function. Figures out which constructor to use for a given
key (dataio type or public type), and caches the result."""
try:
return direct[key]
except KeyError:
pass
for pat, ctor in patterns.items():
mo = pat.fullmatch(key)
if mo is not None:
# cache the match
direct[key] = ctor
return ctor
# cache that there was no match
direct[key] = fallback
return fallback
def __init__(self, fallback: FieldTypeConstructor):
self.dataio_types = {}
self.dataio_patterns = {}
self.public_types = {}
self.public_patterns = {}
self.fallback = fallback
def parse(self, type_text: str) -> RawFieldType:
"""Parse a single field type"""
mo = __class__.TYPE_INFO_PATTERN.fullmatch(type_text)
if mo is None:
raise ValueError(f"malformed type or undefined alias: {type_text!r}")
return self(*mo.groups())
def __call__(self, dataio_type: str, public_type: str) -> RawFieldType:
ctor = self._resolve(dataio_type, self.dataio_types, self.dataio_patterns, self._by_public)
return ctor(dataio_type, public_type)
def _by_public(self, dataio_type: str, public_type: str) -> RawFieldType:
ctor = self._resolve(public_type, self.public_types, self.public_patterns, self.fallback)
return ctor(dataio_type, public_type)
class NeedSizeType(RawFieldType):
"""Helper class for field types that require a size to be usable."""
dataio_type: str
"""The dataio type passed to self.cls"""
public_type: str
"""The public type passed to self.cls"""
cls: typing.Callable[[str, str, SizeInfo], "FieldType"]
"""The field type constructed when adding a size to this type"""
def __init__(self, dataio_type: str, public_type: str, cls: typing.Callable[[str, str, SizeInfo], "FieldType"]):
self.dataio_type = dataio_type
self.public_type = public_type
self.cls = cls
def array(self, size: SizeInfo) -> "FieldType":
"""Add an array size to make a usable type."""
return self.cls(self.dataio_type, self.public_type, size)
def __str__(self) -> str:
return f"{self.dataio_type}({self.public_type})"
class FieldType(RawFieldType):
"""Abstract base class (ABC) for classes representing type information
usable for fields of a packet"""
foldable: bool = False
"""Whether a field of this type can be folded into the packet header"""
complex: bool = False
"""Whether a field of this type needs special handling when initializing,
copying or destroying the packet struct"""
@cache
def array(self, size: SizeInfo) -> "FieldType":
"""Construct a FieldType for an array with element type self and the
given size"""
if f"{size.declared}" == "*":
raise ValueError(f"vectors not supported for field type {self}")
return ArrayType(self, size)
@abstractmethod
def get_code_declaration(self, location: Location) -> str:
"""Generate a code snippet declaring a field with this type in a
packet struct."""
raise NotImplementedError
@abstractmethod
def get_code_param(self, location: Location) -> str:
"""Generate a code fragment declaring a parameter with this type for
a handle function.
See also self.get_code_handle_arg()"""
raise NotImplementedError
def get_code_handle_arg(self, location: Location, packet: str) -> str:
"""Generate a code fragment passing an argument with this type to a
handle function.
See also self.get_code_param()"""
return f"{location @ packet}"
def get_code_init(self, location: Location, packet: str) -> str:
"""Generate a code snippet initializing a field of this type in the
packet struct, after the struct has already been zeroed.
Subclasses must override this if self.complex is True"""
if self.complex:
raise ValueError(f"default get_code_init implementation called for field {location.name} with complex type {self!r}")
# no work needed
return ""
def get_code_copy(self, location: Location, dest: str, src: str) -> str:
"""Generate a code snippet deep-copying a field of this type from
one packet struct to another that has already been initialized.
Subclasses must override this if self.complex is True"""
if self.complex:
raise ValueError(f"default get_code_copy implementation called for field {location.name} with complex type {self!r}")
return f"""\
{location @ dest} = {location @ src};
"""
def get_code_fill(self, location: Location, packet: str) -> str:
"""Generate a code snippet shallow-copying a value of this type from
dsend arguments into a packet struct."""
return f"""\
{location @ packet} = {location @ None};
"""
def get_code_free(self, location: Location, packet: str) -> str:
"""Generate a code snippet deinitializing a field of this type in
the packet struct before it gets destroyed.
Subclasses must override this if self.complex is True"""
if self.complex:
raise ValueError(f"default get_code_free implementation called for field {location.name} with complex type {self!r}")
# no work needed
return ""
@abstractmethod
def get_code_hash(self, location: Location, packet: str) -> str:
"""Generate a code snippet factoring a field of this type into a
hash computation's `result`."""
raise NotImplementedError
@abstractmethod
def get_code_cmp(self, location: Location, new: str, old: str) -> str:
"""Generate a code snippet comparing a field of this type between
the given packets and setting `differ` accordingly. The `old`
packet is one we know to have been initialized by our own code."""
raise NotImplementedError
@abstractmethod
def get_code_put(self, location: Location, packet: str, diff_packet: "str | None" = None) -> str:
"""Generate a code snippet writing a field of this type to the
dataio stream."""
raise NotImplementedError
@abstractmethod
def get_code_get(self, location: Location, packet: str, deep_diff: bool = False) -> str:
"""Generate a code snippet reading a field of this type from the
dataio stream."""
raise NotImplementedError
def _compat_keys(self, location: Location, packet: str):
"""Internal helper function. Yield keys to compare for
type compatibility. See is_type_compatible()"""
yield self.get_code_declaration(location)
yield self.get_code_param(location)
yield self.get_code_handle_arg(location, packet)
yield self.get_code_fill(location, packet)
yield self.complex
if self.complex:
yield self.get_code_init(location, packet)
yield self.get_code_free(location, packet)
def is_type_compatible(self, other: "FieldType") -> bool:
"""Determine whether two field types can be used interchangeably as
part of the packet struct, i.e. differ in dataio transmission only"""
if other is self:
return True
loc = Location("compat_test_field_name")
pak = "compat_test_packet_name"
return all(
a == b
for a, b in zip_longest(
self._compat_keys(loc, pak),
other._compat_keys(loc, pak),
)
)
class BasicType(FieldType):
"""Type information for a field without any specialized treatment"""
dataio_type: str
"""How fields of this type are transmitted over network"""
public_type: str
"""How fields of this type are represented in C code"""
def __init__(self, dataio_type: str, public_type: str):
self.dataio_type = dataio_type
self.public_type = public_type
def get_code_declaration(self, location: Location) -> str:
return f"""\
{self.public_type} {location @ None};
"""
def get_code_param(self, location: Location) -> str:
return f"{self.public_type} {location @ None}"
def get_code_hash(self, location: Location, packet: str) -> str:
raise ValueError(f"hash not supported for type {self} in field {location.name}")
def get_code_cmp(self, location: Location, new: str, old: str) -> str:
return f"""\
differ = ({location @ old} != {location @ new});
"""
def get_code_put(self, location: Location, packet: str, diff_packet: "str | None" = None) -> str:
return f"""\
e |= DIO_PUT({self.dataio_type}, &dout, &field_addr, {location @ packet});
"""
def get_code_get(self, location: Location, packet: str, deep_diff: bool = False) -> str:
return f"""\
if (!DIO_GET({self.dataio_type}, &din, &field_addr, &{location @ packet})) {{
RECEIVE_PACKET_FIELD_ERROR({location.name});
}}
"""
def __str__(self) -> str:
return f"{self.dataio_type}({self.public_type})"
DEFAULT_REGISTRY: "typing.Final" = TypeRegistry(BasicType)
"""The default type registry used by a PacketsDefinition when no other
registry is given."""
class IntType(BasicType):
"""Type information for an integer field"""
TYPE_PATTERN = re.compile(r"^[su]int\d+$")
"""Matches an int dataio type"""
@typing.overload
def __init__(self, dataio_info: str, public_type: str): ...
@typing.overload
def __init__(self, dataio_info: "re.Match[str]", public_type: str): ...
def __init__(self, dataio_info: "str | re.Match[str]", public_type: str):
if isinstance(dataio_info, str):
mo = self.TYPE_PATTERN.fullmatch(dataio_info)
if mo is None:
raise ValueError("not a valid int type")
dataio_info = mo
dataio_type = dataio_info.group(0)
super().__init__(dataio_type, public_type)
def get_code_hash(self, location: Location, packet: str) -> str:
return f"""\
result += {location @ packet};
"""
def get_code_get(self, location: Location, packet: str, deep_diff: bool = False) -> str:
if self.public_type in ("int", "bool"):
# read directly
return super().get_code_get(location, packet, deep_diff)
# read indirectly to make sure coercions between different integer
# types happen correctly
return f"""\
{{
int readin;
if (!DIO_GET({self.dataio_type}, &din, &field_addr, &readin)) {{
RECEIVE_PACKET_FIELD_ERROR({location.name});
}}
{location @ packet} = readin;
}}
"""