-
Notifications
You must be signed in to change notification settings - Fork 212
/
generate_packets.py
executable file
·2513 lines (2155 loc) · 80.8 KB
/
generate_packets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# 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.4 and up. Please leave it so.
# It might also run under older versions, but no such guarantees are made.
import re
import argparse
from pathlib import Path
from contextlib import contextmanager
from functools import partial
from itertools import chain, combinations
###################### Parsing Command Line Arguments ######################
### Script configuration
# See get_argparser for what each of these does
# Keep initial values in sync with argparser defaults
is_verbose = False
lazy_overwrite = False
generate_stats = False
generate_logs = True
use_log_macro = "log_packet_detailed"
fold_bool_into_header = True
def config_script(args):
"""Update script configuration from the given argument namespace.
args should be a namespace of a shape like those
produced by get_argparser().parse_args()"""
global lazy_overwrite, is_verbose
global generate_stats, generate_logs, use_log_macro
global fold_bool_into_header
is_verbose = args.verbose
lazy_overwrite = args.lazy_overwrite
generate_stats = args.gen_stats
generate_logs = args.log_macro is not None
use_log_macro = args.log_macro
fold_bool_into_header = args.fold_bool
def file_path(s):
"""Parse the given path and check basic validity."""
path = Path(s)
if path.is_reserved() or not path.name:
raise ValueError("not a valid file path: %r" % s)
if path.exists() and not path.is_file():
raise ValueError("not a file: %r" % s)
return path
def get_argparser():
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(
"Output paths",
"The following parameters decide which output files are generated,"
" and where the generated code is written.",
)
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 make 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")
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 path_args:
paths.add_argument(option, dest = dest, type = file_path,
help = "output path for %s" % canonical)
return parser
def verbose(s):
if is_verbose:
print(s)
####################### File access helper functions #######################
def write_disclaimer(f):
f.write('''
/****************************************************************************
* THIS FILE WAS GENERATED *
* Script: common/generate_packets.py *
* Input: common/networking/packets.def *
* DO NOT CHANGE THIS FILE *
****************************************************************************/
''')
@contextmanager
def wrap_header(file, header_name, cplusplus=True):
"""Add multiple inclusion protection to the given file. If cplusplus
is given (default), also add code for `extern "C" {}` wrapping"""
name = "FC__%s_H" % header_name.upper()
file.write("""
#ifndef {name}
#define {name}
""".format(name = name))
if cplusplus:
file.write("""
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
""")
yield
if cplusplus:
file.write("""
#ifdef __cplusplus
}
#endif /* __cplusplus */
""")
file.write("""
#endif /* {name} */
""".format(name = name))
@contextmanager
def fc_open(path):
"""Open a file for writing and write disclaimer.
If enabled, lazily overwrites the given file."""
path = Path(path) # no-op if path is already a Path object
verbose("writing %s" % path)
if lazy_overwrite:
open_fun = lazy_overwrite_open
else:
open_fun = partial(Path.open, mode = "w")
with open_fun(path) as file:
write_disclaimer(file)
yield file
verbose("done writing %s" % path)
def read_text(path, allow_missing=True):
"""Load all text from the file at the given path
If allow_missing is True, return the empty string if the file does not
exist. Otherwise, raise FileNotFoundException as per open()."""
path = Path(path)
if allow_missing and not path.exists():
return ""
with path.open() as file:
return file.read()
def files_equal(path_a, path_b):
"""Return whether the contents of two text files are identical"""
return read_text(path_a) == read_text(path_b)
@contextmanager
def lazy_overwrite_open(path, suffix=".tmp"):
"""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
verbose("lazy: using %s" % tmp_path)
with tmp_path.open("w") as file:
yield file
if path.exists() and files_equal(tmp_path, path):
verbose("lazy: no change, deleting...")
tmp_path.unlink()
else:
verbose("lazy: content changed, replacing...")
tmp_path.replace(path)
######################### General helper functions #########################
# Taken from https://docs.python.org/3.4/library/itertools.html#itertools-recipes
def powerset(iterable):
"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))
def prefix(prefix, text):
"""Prepend prefix to every line of text"""
return "\n".join(prefix + line for line in text.split("\n"))
# matches an entire field definition line (type, fields and flag info)
FIELDS_LINE_PATTERN = re.compile(r"^\s*(\S+(?:\(.*\))?)\s+([^;()]*)\s*;\s*(.*)\s*$")
# matches a field type (dataio type and struct/public type)
TYPE_INFO_PATTERN = re.compile(r"^(.*)\((.*)\)$")
# matches a dataio type with float factor
FLOAT_FACTOR_PATTERN = re.compile(r"^(\D+)(\d+)$")
# matches a 2D-array field definition (name, first array size, second array size)
ARRAY_2D_PATTERN = re.compile(r"^(.*)\[(.*)\]\[(.*)\]$")
# matches a 1D-array field definition (name, array size)
ARRAY_1D_PATTERN = re.compile(r"^(.*)\[(.*)\]$")
# matches an add-cap flag (optional capability)
ADD_CAP_PATTERN = re.compile(r"^add-cap\((.*)\)$")
# matches a remove-cap flag (optional capability)
REMOVE_CAP_PATTERN = re.compile(r"^remove-cap\((.*)\)$")
# Parses a line of the form "COORD x, y; key" and returns a list of
# Field objects. types is a dict mapping type aliases to their meaning
def parse_fields(line, types):
mo = FIELDS_LINE_PATTERN.fullmatch(line)
if mo is None:
raise ValueError("invalid field definition: %r" % line)
type_text, fields_, flags = (i.strip() for i in mo.groups(""))
# analyze type
# FIXME: no infinite loop detection
while type_text in types:
type_text = types[type_text]
typeinfo={}
mo = TYPE_INFO_PATTERN.fullmatch(type_text)
if mo is None:
raise ValueError("malformed or undefined type: %r" % type_text)
typeinfo["dataio_type"],typeinfo["struct_type"]=mo.groups()
if typeinfo["struct_type"]=="float":
mo = FLOAT_FACTOR_PATTERN.fullmatch(typeinfo["dataio_type"])
if mo is None:
raise ValueError("float type without float factor: %r" % type_text)
typeinfo["dataio_type"]=mo.group(1)
typeinfo["float_factor"]=int(mo.group(2))
# analyze fields
fields=[]
for i in fields_.split(","):
i=i.strip()
t={}
def f(x):
arr=x.split(":")
if len(arr)==1:
return [x,x,x]
elif len(arr) == 2:
arr.append("old->"+arr[1])
arr[1]="real_packet->"+arr[1]
return arr
else:
raise ValueError("Invalid array size declaration: %r" % x)
mo = ARRAY_2D_PATTERN.fullmatch(i)
if mo:
t["name"]=mo.group(1)
t["is_array"]=2
t["array_size1_d"],t["array_size1_u"],t["array_size1_o"]=f(mo.group(2))
t["array_size2_d"],t["array_size2_u"],t["array_size2_o"]=f(mo.group(3))
else:
mo = ARRAY_1D_PATTERN.fullmatch(i)
if mo:
t["name"]=mo.group(1)
t["is_array"]=1
t["array_size_d"],t["array_size_u"],t["array_size_o"]=f(mo.group(2))
else:
t["name"]=i
t["is_array"]=0
fields.append(t)
# analyze flags
flaginfo={}
arr = [
stripped
for flag in flags.split(",")
for stripped in (flag.strip(),)
if stripped
]
flaginfo["is_key"]=("key" in arr)
if flaginfo["is_key"]: arr.remove("key")
flaginfo["diff"]=("diff" in arr)
if flaginfo["diff"]: arr.remove("diff")
adds=[]
removes=[]
remaining=[]
for i in arr:
mo = ADD_CAP_PATTERN.fullmatch(i)
if mo:
adds.append(mo.group(1))
continue
mo = REMOVE_CAP_PATTERN.fullmatch(i)
if mo:
removes.append(mo.group(1))
continue
remaining.append(i)
if len(adds) + len(removes) > 1:
raise ValueError("A field can only have one add-cap or remove-cap: %s" % line)
if remaining:
raise ValueError("unrecognized flags in field declaration: %s" % " ".join(remaining))
if adds:
flaginfo["add_cap"]=adds[0]
else:
flaginfo["add_cap"]=""
if removes:
flaginfo["remove_cap"]=removes[0]
else:
flaginfo["remove_cap"]=""
return [Field(fieldinfo, typeinfo, flaginfo) for fieldinfo in fields]
# Class for a field (part of a packet). It has a name, serveral types,
# flags and some other attributes.
class Field:
def __init__(self, fieldinfo, typeinfo, flaginfo):
self.name = fieldinfo["name"]
self.is_array = fieldinfo["is_array"]
if self.is_array == 2:
self.array_size1_d = fieldinfo["array_size1_d"]
self.array_size1_u = fieldinfo["array_size1_u"]
self.array_size1_o = fieldinfo["array_size1_o"]
self.array_size2_d = fieldinfo["array_size2_d"]
self.array_size2_u = fieldinfo["array_size2_u"]
self.array_size2_o = fieldinfo["array_size2_o"]
elif self.is_array == 1:
self.array_size_d = fieldinfo["array_size_d"]
self.array_size_u = fieldinfo["array_size_u"]
self.array_size_o = fieldinfo["array_size_o"]
self.dataio_type = typeinfo["dataio_type"]
self.struct_type = typeinfo["struct_type"]
self.float_factor = typeinfo.get("float_factor")
self.is_struct = self.struct_type.startswith("struct")
self.is_key = flaginfo["is_key"]
self.diff = flaginfo["diff"]
self.add_cap = flaginfo["add_cap"]
self.remove_cap = flaginfo["remove_cap"]
# Helper function for the dictionary variant of the % operator
# ("%(name)s"%dict) or str.format ("{name}".format(**dict)).
def get_dict(self, vars_):
result=self.__dict__.copy()
result.update(vars_)
return result
def get_handle_type(self):
if self.dataio_type=="string" or self.dataio_type=="estring":
return "const char *"
if self.dataio_type=="worklist":
return "const %s *"%self.struct_type
if self.is_array:
return "const %s *"%self.struct_type
return self.struct_type+" "
# Returns code which is used in the declaration of the field in
# the packet struct.
def get_declar(self):
if self.is_array==2:
return "{self.struct_type} {self.name}[{self.array_size1_d}][{self.array_size2_d}]".format(self = self)
if self.is_array:
return "{self.struct_type} {self.name}[{self.array_size_d}]".format(self = self)
else:
return "{self.struct_type} {self.name}".format(self = self)
# Returns code which copies the arguments of the direct send
# functions in the packet struct.
def get_fill(self):
if self.dataio_type=="worklist":
return " worklist_copy(&real_packet->{self.name}, {self.name});".format(self = self)
if self.is_array==0:
return " real_packet->{self.name} = {self.name};".format(self = self)
if self.dataio_type=="string" or self.dataio_type=="estring":
return " sz_strlcpy(real_packet->{self.name}, {self.name});".format(self = self)
if self.is_array==1:
return """ {{
int i;
for (i = 0; i < {self.array_size_u}; i++) {{
real_packet->{self.name}[i] = {self.name}[i];
}}
}}""".format(self = self)
return repr(self.__dict__)
# Returns code which sets "differ" by comparing the field
# instances of "old" and "readl_packet".
def get_cmp(self):
if self.dataio_type=="memory":
return " differ = (memcmp(old->{self.name}, real_packet->{self.name}, {self.array_size_d}) != 0);".format(self = self)
if self.dataio_type=="bitvector":
return " differ = !BV_ARE_EQUAL(old->{self.name}, real_packet->{self.name});".format(self = self)
if self.dataio_type in ["string", "estring"] and self.is_array==1:
return " differ = (strcmp(old->{self.name}, real_packet->{self.name}) != 0);".format(self = self)
if self.dataio_type == "cm_parameter":
return " differ = !cm_are_parameter_equal(&old->{self.name}, &real_packet->{self.name});".format(self = self)
if self.is_struct and self.is_array==0:
return " differ = !are_{self.dataio_type}s_equal(&old->{self.name}, &real_packet->{self.name});".format(self = self)
if not self.is_array:
return " differ = (old->{self.name} != real_packet->{self.name});".format(self = self)
if self.dataio_type=="string" or self.dataio_type=="estring":
c = "strcmp(old->{self.name}[i], real_packet->{self.name}[i]) != 0".format(self = self)
array_size_u = self.array_size1_u
array_size_o = self.array_size1_o
elif self.is_struct:
c = "!are_{self.dataio_type}s_equal(&old->{self.name}[i], &real_packet->{self.name}[i])".format(self = self)
array_size_u = self.array_size_u
array_size_o = self.array_size_o
else:
c = "old->{self.name}[i] != real_packet->{self.name}[i]".format(self = self)
array_size_u = self.array_size_u
array_size_o = self.array_size_o
return """
{{
differ = ({array_size_o} != {array_size_u});
if (!differ) {{
int i;
for (i = 0; i < {array_size_u}; i++) {{
if ({c}) {{
differ = TRUE;
break;
}}
}}
}}
}}""".format(c = c, array_size_u = array_size_u, array_size_o = array_size_o)
@property
def folded_into_head(self):
return (
fold_bool_into_header
and self.struct_type == "bool"
and not self.is_array
)
# Returns a code fragment which updates the bit of the this field
# in the "fields" bitvector. The bit is either a "content-differs"
# bit or (for bools which gets folded in the header) the actual
# value of the bool.
def get_cmp_wrapper(self, i, pack):
if self.folded_into_head:
if pack.is_info != "no":
cmp = self.get_cmp()
differ_part = '''
if (differ) {
different++;
}
'''
else:
cmp = ""
differ_part = ""
b = "packet->{self.name}".format(self = self)
return cmp + differ_part + ''' if (%s) {
BV_SET(fields, %d);
}
'''%(b,i)
else:
cmp = self.get_cmp()
if pack.is_info != "no":
return '''%s
if (differ) {
different++;
BV_SET(fields, %d);
}
'''%(cmp, i)
else:
return '''%s
if (differ) {
BV_SET(fields, %d);
}
'''%(cmp, i)
# Returns a code fragment which will put this field if the
# content has changed. Does nothing for bools-in-header.
def get_put_wrapper(self,packet,i,deltafragment):
if fold_bool_into_header and self.struct_type=="bool" and \
not self.is_array:
return " /* field {i:d} is folded into the header */\n".format(i = i)
put=self.get_put(deltafragment)
if packet.gen_log:
f = ' {packet.log_macro}(" field \'{self.name}\' has changed");\n'.format(packet = packet, self = self)
else:
f=""
if packet.gen_stats:
s = " stats_{packet.name}_counters[{i:d}]++;\n".format(packet = packet, i = i)
else:
s=""
return """ if (BV_ISSET(fields, {i:d})) {{
{f}{s} {put}
}}
""".format(i = i, f = f, s = s, put = put)
# Returns code which put this field.
def get_put(self,deltafragment):
return """#ifdef FREECIV_JSON_CONNECTION
field_addr.name = \"{self.name}\";
#endif /* FREECIV_JSON_CONNECTION */
""".format(self = self) \
+ self.get_put_real(deltafragment);
# The code which put this field before it is wrapped in address adding.
def get_put_real(self,deltafragment):
if self.dataio_type=="bitvector":
return "DIO_BV_PUT(&dout, &field_addr, packet->{self.name});".format(self = self)
if self.struct_type=="float" and not self.is_array:
return " DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}, {self.float_factor:d});".format(self = self)
if self.dataio_type in ["worklist", "cm_parameter"]:
return " DIO_PUT({self.dataio_type}, &dout, &field_addr, &real_packet->{self.name});".format(self = self)
if self.dataio_type in ["memory"]:
return " DIO_PUT({self.dataio_type}, &dout, &field_addr, &real_packet->{self.name}, {self.array_size_u});".format(self = self)
arr_types=["string","estring","city_map"]
if (self.dataio_type in arr_types and self.is_array==1) or \
(self.dataio_type not in arr_types and self.is_array==0):
return " DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name});".format(self = self)
if self.is_struct:
if self.is_array==2:
c = "DIO_PUT({self.dataio_type}, &dout, &field_addr, &real_packet->{self.name}[i][j]);".format(self = self)
else:
c = "DIO_PUT({self.dataio_type}, &dout, &field_addr, &real_packet->{self.name}[i]);".format(self = self)
array_size_u = self.array_size_u
elif self.dataio_type=="string" or self.dataio_type=="estring":
c = "DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}[i]);".format(self = self)
array_size_u=self.array_size1_u
elif self.struct_type=="float":
if self.is_array==2:
c = " DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}[i][j], {self.float_factor:d});".format(self = self)
else:
c = " DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}[i], {self.float_factor:d});".format(self = self)
array_size_u = self.array_size_u
else:
if self.is_array==2:
c = "DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}[i][j]);".format(self = self)
else:
c = "DIO_PUT({self.dataio_type}, &dout, &field_addr, real_packet->{self.name}[i]);".format(self = self)
array_size_u = self.array_size_u
if deltafragment and self.diff and self.is_array == 1:
return """
{{
int i;
#ifdef FREECIV_JSON_CONNECTION
int count = 0;
for (i = 0; i < {self.array_size_u}; i++) {{
if (old->{self.name}[i] != real_packet->{self.name}[i]) {{
count++;
}}
}}
/* Create the array. */
DIO_PUT(farray, &dout, &field_addr, count + 1);
/* Enter array. */
field_addr.sub_location = plocation_elem_new(0);
count = 0;
#endif /* FREECIV_JSON_CONNECTION */
fc_assert({self.array_size_u} < 255);
for (i = 0; i < {self.array_size_u}; i++) {{
if (old->{self.name}[i] != real_packet->{self.name}[i]) {{
#ifdef FREECIV_JSON_CONNECTION
/* Next diff array element. */
field_addr.sub_location->number = count - 1;
/* Create the diff array element. */
DIO_PUT(farray, &dout, &field_addr, 2);
/* Enter diff array element (start at the index address). */
field_addr.sub_location->sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
DIO_PUT(uint8, &dout, &field_addr, i);
#ifdef FREECIV_JSON_CONNECTION
/* Content address. */
field_addr.sub_location->sub_location->number = 1;
#endif /* FREECIV_JSON_CONNECTION */
{c}
#ifdef FREECIV_JSON_CONNECTION
/* Exit diff array element. */
free(field_addr.sub_location->sub_location);
field_addr.sub_location->sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}
}}
#ifdef FREECIV_JSON_CONNECTION
field_addr.sub_location->number = count - 1;
/* Create the diff array element. */
DIO_PUT(farray, &dout, &field_addr, {self.array_size_u});
/* Enter diff array element. Point to index address. */
field_addr.sub_location->sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
DIO_PUT(uint8, &dout, &field_addr, 255);
#ifdef FREECIV_JSON_CONNECTION
/* Exit diff array element. */
free(field_addr.sub_location->sub_location);
field_addr.sub_location->sub_location = NULL;
/* Exit array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}""".format(self = self, c = c)
if self.is_array == 2 and self.dataio_type != "string" \
and self.dataio_type != "estring":
return """
{{
int i, j;
#ifdef FREECIV_JSON_CONNECTION
/* Create the outer array. */
DIO_PUT(farray, &dout, &field_addr, {self.array_size1_u});
/* Enter the outer array. */
field_addr.sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
for (i = 0; i < {self.array_size1_u}; i++) {{
#ifdef FREECIV_JSON_CONNECTION
/* Next inner array (an element in the outer array). */
field_addr.sub_location->number = i;
/* Create the inner array. */
DIO_PUT(farray, &dout, &field_addr, {self.array_size2_u});
/* Enter the inner array. */
field_addr.sub_location->sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
for (j = 0; j < {self.array_size2_u}; j++) {{
#ifdef FREECIV_JSON_CONNECTION
/* Next element (in the inner array). */
field_addr.sub_location->sub_location->number = j;
#endif /* FREECIV_JSON_CONNECTION */
{c}
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit the inner array. */
free(field_addr.sub_location->sub_location);
field_addr.sub_location->sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit the outer array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}""".format(self = self, c = c)
else:
return """
{{
int i;
#ifdef FREECIV_JSON_CONNECTION
/* Create the array. */
DIO_PUT(farray, &dout, &field_addr, {array_size_u});
/* Enter the array. */
field_addr.sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
for (i = 0; i < {array_size_u}; i++) {{
#ifdef FREECIV_JSON_CONNECTION
/* Next array element. */
field_addr.sub_location->number = i;
#endif /* FREECIV_JSON_CONNECTION */
{c}
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}""".format(c = c, array_size_u = array_size_u)
# Returns a code fragment which will get the field if the
# "fields" bitvector says so.
def get_get_wrapper(self,packet,i,deltafragment):
get=self.get_get(deltafragment)
if fold_bool_into_header and self.struct_type=="bool" and \
not self.is_array:
return " real_packet->{self.name} = BV_ISSET(fields, {i:d});\n".format(self = self, i = i)
get=prefix(" ",get)
if packet.gen_log:
f = " {packet.log_macro}(\" got field '{self.name}'\");\n".format(self = self, packet = packet)
else:
f=""
return """ if (BV_ISSET(fields, {i:d})) {{
{f}{get}
}}
""".format(i = i, f = f, get = get)
# Returns code which get this field.
def get_get(self,deltafragment):
return """#ifdef FREECIV_JSON_CONNECTION
field_addr.name = \"{self.name}\";
#endif /* FREECIV_JSON_CONNECTION */
""".format(self = self) \
+ self.get_get_real(deltafragment);
# The code which get this field before it is wrapped in address adding.
def get_get_real(self,deltafragment):
if self.struct_type=="float" and not self.is_array:
return """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}, {self.float_factor:d})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
if self.dataio_type=="bitvector":
return """if (!DIO_BV_GET(&din, &field_addr, real_packet->{self.name})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
if self.dataio_type in ["string","estring","city_map"] and \
self.is_array!=2:
return """if (!DIO_GET({self.dataio_type}, &din, &field_addr, real_packet->{self.name}, sizeof(real_packet->{self.name}))) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
if self.is_struct and self.is_array==0:
return """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
if not self.is_array:
if self.struct_type in ["int","bool"]:
return """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
else:
return """{{
int readin;
if (!DIO_GET({self.dataio_type}, &din, &field_addr, &readin)) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}
real_packet->{self.name} = readin;
}}""".format(self = self)
if self.is_struct:
if self.is_array==2:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i][j])) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
else:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i])) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
elif self.dataio_type=="string" or self.dataio_type=="estring":
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, real_packet->{self.name}[i], sizeof(real_packet->{self.name}[i]))) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
elif self.struct_type=="float":
if self.is_array==2:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i][j], {self.float_factor:d})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
else:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i], {self.float_factor:d})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
elif self.is_array==2:
if self.struct_type in ["int","bool"]:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i][j])) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
else:
c = """{{
int readin;
if (!DIO_GET({self.dataio_type}, &din, &field_addr, &readin)) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}
real_packet->{self.name}[i][j] = readin;
}}""".format(self = self)
elif self.struct_type in ["int","bool"]:
c = """if (!DIO_GET({self.dataio_type}, &din, &field_addr, &real_packet->{self.name}[i])) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self)
else:
c = """{{
int readin;
if (!DIO_GET({self.dataio_type}, &din, &field_addr, &readin)) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}
real_packet->{self.name}[i] = readin;
}}""".format(self = self)
if self.is_array==2:
array_size_u=self.array_size1_u
array_size_d=self.array_size1_d
else:
array_size_u=self.array_size_u
array_size_d=self.array_size_d
if not self.diff or self.dataio_type=="memory":
if array_size_u != array_size_d:
extra = """
if ({array_size_u} > {array_size_d}) {{
RECEIVE_PACKET_FIELD_ERROR({self.name}, ": truncation array");
}}""".format(self = self, array_size_u = array_size_u, array_size_d = array_size_d)
else:
extra=""
if self.dataio_type=="memory":
return """{extra}
if (!DIO_GET({self.dataio_type}, &din, &field_addr, real_packet->{self.name}, {array_size_u})) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}""".format(self = self, array_size_u = array_size_u, extra = extra)
elif self.is_array==2 and self.dataio_type!="string" \
and self.dataio_type!="estring":
return """
{{
int i, j;
#ifdef FREECIV_JSON_CONNECTION
/* Enter outer array. */
field_addr.sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
{extra}
for (i = 0; i < {self.array_size1_u}; i++) {{
#ifdef FREECIV_JSON_CONNECTION
/* Update address of outer array element (inner array). */
field_addr.sub_location->number = i;
/* Enter inner array. */
field_addr.sub_location->sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
for (j = 0; j < {self.array_size2_u}; j++) {{
#ifdef FREECIV_JSON_CONNECTION
/* Update address of element in inner array. */
field_addr.sub_location->sub_location->number = j;
#endif /* FREECIV_JSON_CONNECTION */
{c}
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit inner array. */
free(field_addr.sub_location->sub_location);
field_addr.sub_location->sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit outer array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}""".format(self = self, c = c, extra = extra)
else:
return """
{{
int i;
#ifdef FREECIV_JSON_CONNECTION
/* Enter array. */
field_addr.sub_location = plocation_elem_new(0);
#endif /* FREECIV_JSON_CONNECTION */
{extra}
for (i = 0; i < {array_size_u}; i++) {{
#ifdef FREECIV_JSON_CONNECTION
field_addr.sub_location->number = i;
#endif /* FREECIV_JSON_CONNECTION */
{c}
}}
#ifdef FREECIV_JSON_CONNECTION
/* Exit array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
}}""".format(array_size_u = array_size_u, c = c, extra = extra)
elif deltafragment and self.diff and self.is_array == 1:
return """
{{
#ifdef FREECIV_JSON_CONNECTION
int count;
/* Enter array. */
field_addr.sub_location = plocation_elem_new(0);
for (count = 0;; count++) {{
int i;
field_addr.sub_location->number = count;
/* Enter diff array element (start at the index address). */
field_addr.sub_location->sub_location = plocation_elem_new(0);
#else /* FREECIV_JSON_CONNECTION */
while (TRUE) {{
int i;
#endif /* FREECIV_JSON_CONNECTION */
if (!DIO_GET(uint8, &din, &field_addr, &i)) {{
RECEIVE_PACKET_FIELD_ERROR({self.name});
}}
if (i == 255) {{
#ifdef FREECIV_JSON_CONNECTION
/* Exit diff array element. */
free(field_addr.sub_location->sub_location);
field_addr.sub_location->sub_location = NULL;
/* Exit diff array. */
free(field_addr.sub_location);
field_addr.sub_location = NULL;
#endif /* FREECIV_JSON_CONNECTION */
break;
}}
if (i > {array_size_u}) {{
RECEIVE_PACKET_FIELD_ERROR({self.name},