/
generate-serializers.py
executable file
·1950 lines (1783 loc) · 89.5 KB
/
generate-serializers.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
#
# Copyright (C) 2022-2024 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import copy
import os
import re
import sys
# Supported type attributes:
#
# AdditionalEncoder - generate serializers for StreamConnectionEncoder in addition to IPC::Encoder.
# CreateUsing - use a custom function to call instead of the constructor or create.
# ConstructSubclass - use a subclass to construct the object. Do not include namespace.
# CustomHeader - don't include a header based on the struct/class name. Only needed for non-enum types.
# DisableMissingMemberCheck - do not check for attributes that are missed during serialization.
# Alias - this type is not a struct or class, but a typedef.
# Nested - this type is only serialized as a member of its parent, so work around the need for http://wg21.link/P0289 and don't forward declare it in the header.
# RefCounted - deserializer returns a std::optional<Ref<T>> instead of a std::optional<T>.
# LegacyPopulateFromEmptyConstructor - instead of calling a constructor with the members, call the empty constructor then insert the members one at a time.
# OptionSet - for enum classes, instead of only allowing deserialization of the exact values, allow deserialization of any bit combination of the values.
# RValue - serializer takes an rvalue reference, instead of an lvalue.
# WebKitPlatform - put serializer into a file built as part of WebKitPlatform
# CustomEncoder - Only generate the decoder, not the encoder.
# WebKitSecureCodingClass - For webkit_secure_coding declarations that need a custom way of establishing the Obj-C class to instantiate (e.g. softlinked frameworks)
#
# Supported member attributes:
#
# BitField - work around the need for http://wg21.link/P0572 and don't check that the serialization order matches the memory layout.
# EncodeRequestBody - Include the body of the WebCore::ResourceRequest when encoding (by default, it is omitted).
# Validator - additional C++ to validate the value when decoding
# NotSerialized - member is present in structure but intentionally not serialized.
# SecureCodingAllowed - ObjC classes to allow when decoding.
# OptionalTupleBits - This member stores bits of whether each following member is serialized. Attribute must be immediately before members with OptionalTupleBit.
# OptionalTupleBit - The name of the bit indicating whether this member is serialized.
# SupportWKKeyedCoder - For webkit_secure_coding types, in addition to the preferred property list code path, support SupportWKKeyedCoder
# Precondition - Used to fail early from a decoder, for example if a soft linked framework is not present to decode a member
class Template(object):
def __init__(self, template_type, namespace, name, enum_storage=None):
self.type = template_type
self.namespace = namespace
self.name = name
self.enum_storage = enum_storage
def forward_declaration(self):
if self.enum_storage:
return self.type + ' ' + self.name + ' : ' + self.enum_storage + ';'
return self.type + ' ' + self.name + ';'
def specialization(self):
return self.namespace + '::' + self.name
class SerializedType(object):
def __init__(self, struct_or_class, cf_type, namespace, name, parent_class_name, members, dictionary_members, condition, attributes, templates, other_metadata=None):
self.struct_or_class = struct_or_class
self.cf_type = cf_type
self.to_cf_method = None
self.from_cf_method = None
self.forward_declaration = None
self.custom_secure_coding_class = None
self.namespace = namespace
self.name = name
self.parent_class_name = parent_class_name
self.parent_class = None
self.members = members
self.dictionary_members = dictionary_members
self.alias = None
self.condition = condition
self.encoders = ['Encoder']
self.return_ref = False
self.construct_subclass = None
self.create_using = False
self.populate_from_empty_constructor = False
self.nested = False
self.rvalue = False
self.webkit_platform = False
self.members_are_subclasses = False
self.custom_encoder = False
self.support_wkkeyedcoder = False
self.disableMissingMemberCheck = False
if attributes is not None:
for attribute in attributes.split(', '):
if '=' in attribute:
key, value = attribute.split('=')
if key == 'AdditionalEncoder':
self.encoders.append(value)
if key == 'ConstructSubclass':
self.construct_subclass = value
if key == 'CreateUsing':
self.create_using = value
if key == 'Alias':
self.alias = value
if key == 'ToCFMethod':
self.to_cf_method = value
if key == 'FromCFMethod':
self.from_cf_method = value
if key == 'ForwardDeclaration':
self.forward_declaration = value
if key == 'WebKitSecureCodingClass':
self.custom_secure_coding_class = value
else:
if attribute == 'Nested':
self.nested = True
elif attribute == 'RefCounted':
self.return_ref = True
elif attribute == 'DisableMissingMemberCheck':
self.disableMissingMemberCheck = True
elif attribute == 'RValue':
self.rvalue = True
elif attribute == 'WebKitPlatform':
self.webkit_platform = True
elif attribute == 'LegacyPopulateFromEmptyConstructor':
self.populate_from_empty_constructor = True
elif attribute == 'CustomEncoder':
self.custom_encoder = True
elif attribute == 'SupportWKKeyedCoder':
self.support_wkkeyedcoder = True
self.templates = templates
if other_metadata:
if other_metadata == 'subclasses':
self.members_are_subclasses = True
if self.is_webkit_secure_coding_type():
self.namespace = 'WebKit'
self.webkit_platform = True
def namespace_and_name(self):
if self.cf_type is not None:
return self.cf_type + "Ref"
if self.namespace is None:
return self.name
return self.namespace + '::' + self.cpp_struct_or_class_name()
def namespace_if_not_wtf_and_name(self):
if self.namespace == 'WTF':
return self.name
if self.namespace is None:
return self.name
return self.namespace + '::' + self.cpp_struct_or_class_name()
def namespace_and_name_for_construction(self, specialization):
fulltype = None
if self.construct_subclass:
fulltype = self.namespace + '::' + self.construct_subclass
else:
fulltype = self.namespace_and_name()
if specialization:
fulltype = fulltype + '<' + specialization + '>'
return fulltype
def cf_wrapper_type(self):
return self.namespace + '::' + self.name
def name_declaration_for_serialized_type_info(self):
if self.cf_type is not None:
return self.cf_type + 'Ref'
if self.namespace == 'WTF':
if self.name != "UUID":
return self.name
return self.namespace_and_name()
def subclass_enum_name(self):
result = ""
if self.namespace:
result += self.namespace + "_"
return result + self.name + "_Subclass"
def function_name_for_enum(self):
return 'isValidEnum'
def can_assert_member_order_is_correct(self):
if self.disableMissingMemberCheck:
return False
for member in self.members:
if '()' in member.name:
return False
if '.' in member.name:
return False
return True
def members_for_serialized_type_info(self):
return self.serialized_members()
def serialized_members(self):
return list(filter(lambda member: 'NotSerialized' not in member.attributes, self.members))
def has_optional_tuple_bits(self):
if len(self.members) == 0:
return False
for member in self.members:
if 'OptionalTupleBits' in member.attributes:
return True
return False
def should_skip_forward_declare(self):
return self.nested or self.templates
def cpp_type_from_struct_or_class(self):
if self.is_webkit_secure_coding_type():
return 'class'
return self.struct_or_class
def cpp_struct_or_class_name(self):
if self.is_webkit_secure_coding_type():
return 'CoreIPC' + self.name
return self.name
def is_webkit_secure_coding_type(self):
return self.struct_or_class == 'webkit_secure_coding'
def wrapper_for_webkit_secure_coding_type(self):
copied_type = copy.copy(self)
copied_type.struct_or_class = 'class'
copied_type.name = self.cpp_struct_or_class_name()
copied_type.dictionary_members = None
return copied_type
class SerializedEnum(object):
def __init__(self, namespace, name, underlying_type, valid_values, condition, attributes):
self.namespace = namespace
self.name = name
self.underlying_type = underlying_type
self.valid_values = valid_values
self.condition = condition
self.attributes = attributes
def namespace_and_name(self):
if self.namespace is None:
return self.name
return self.namespace + '::' + self.name
def function_name(self):
if self.is_option_set():
return 'isValidOptionSet'
return 'isValidEnum'
def additional_template_parameter(self):
if self.is_option_set():
return ''
return ', void'
def parameter(self):
if self.is_option_set():
return 'OptionSet<' + self.namespace_and_name() + '>'
return self.underlying_type
def is_option_set(self):
return 'OptionSet' in self.attributes
def is_nested(self):
return 'Nested' in self.attributes
def is_webkit_platform(self):
return 'WebKitPlatform' in self.attributes
class MemberVariable(object):
def __init__(self, type, name, condition, attributes, namespace=None, is_subclass=False):
assert type == type.strip(), "MemberVariable(" + type + " " + name + ") has invalid type '" + type + "'"
assert name == name.strip(), "MemberVariable(" + type + " " + name + ") has invalid name '" + name + "'"
self.type = type
self.name = name
self.condition = condition
self.attributes = attributes
self.namespace = namespace
self.is_subclass = is_subclass
def optional_tuple_bit(self):
for attribute in self.attributes:
match = re.search(r'OptionalTupleBit=(.*)', attribute)
if match:
bit, = match.groups()
return bit
return None
def optional_tuple_bits(self):
for attribute in self.attributes:
if attribute == 'OptionalTupleBits':
return True
return False
def value_without_question_mark(self):
value = self.name
if self.value_is_optional():
value = value[:-1]
return value
def ns_type_enum_value(self):
value = self.value_without_question_mark()
if value.startswith('Dictionary'):
return 'Dictionary'
if value.startswith('Array'):
return 'Array'
return value
def array_contents(self):
value = self.value_without_question_mark()
if not value.startswith('Array'):
return None
match = re.search(r'(.*)<(.*)>', value)
if match:
array, contents = match.groups()
if contents == 'String':
return 'NSString'
if contents == 'Data':
return 'NSData'
return contents
return None
def dictionary_contents(self):
value = self.value_without_question_mark()
if not value.startswith('Dictionary'):
return None
match = re.search(r'(.*)<(.*)>', value)
if match:
dictionary, contents = match.groups()
match = re.search(r'(.*), (.*)', contents)
if match:
keys, values = match.groups()
assert keys == 'String'
return values
return None
def has_container_contents(self):
return self.dictionary_contents() is not None or self.array_contents() is not None
def ns_type(self):
value = self.value_without_question_mark()
if value == 'String':
return 'NSString'
if value.startswith('Dictionary'):
return 'NSDictionary'
if value == 'Data':
return 'NSData'
if value == 'Date':
return 'NSDate'
if value == 'Number':
return 'NSNumber'
if value == 'URL':
return 'NSURL'
if value == 'PersonNameComponents':
return 'NSPersonNameComponents'
if value.startswith('Array'):
return 'NSArray'
return value
def ns_type_pointer(self):
value = self.ns_type()
if value == 'SecTrustRef':
return value
return value + ' *'
def type_check(self):
value = self.ns_type()
if value == 'SecTrustRef':
return '(m_' + self.type + ' && CFGetTypeID((CFTypeRef)m_' + self.type + '.get()) == SecTrustGetTypeID())'
return '[m_' + self.type + ' isKindOfClass:IPC::getClass<' + value + '>()]'
def id_cast(self):
value = self.ns_type()
if value == 'SecTrustRef':
return '(id)'
return ''
def dictionary_type(self):
prefix = 'std::optional<' if self.value_is_optional() else ''
suffix = '>' if self.value_is_optional() else ''
if self.array_contents() is not None:
return prefix + 'Vector<RetainPtr<' + self.array_contents() + '>>' + suffix
if self.dictionary_contents() is not None:
return prefix + 'Vector<std::pair<String, RetainPtr<' + self.dictionary_contents() + '>>>' + suffix
return 'RetainPtr<' + self.ns_type() + '>'
def value_is_optional(self):
return self.name.endswith('?')
class EnumMember(object):
def __init__(self, name, condition):
self.name = name
self.condition = condition
class ConditionalForwardDeclaration(object):
def __init__(self, declaration, condition):
self.declaration = declaration
self.condition = condition
def __lt__(self, other):
if self.declaration != other.declaration:
return self.declaration < other.declaration
def condition_str(condition):
return "" if condition is None else condition
return condition_str(self.condition) < condition_str(other.condition)
def __eq__(self, other):
return other and self.declaration == other.declaration and self.condition == other.condition
def __hash__(self):
return hash((self.declaration, self.condition))
class ConditionalHeader(object):
def __init__(self, header, condition, webkit_platform=False, secure_coding=False):
self.header = header
self.condition = condition
self.webkit_platform = webkit_platform
self.secure_coding = secure_coding
def __lt__(self, other):
if self.header != other.header:
return self.header < other.header
def condition_str(condition):
return "" if condition is None else condition
return condition_str(self.condition) < condition_str(other.condition)
def __eq__(self, other):
return other and self.header == other.header and self.condition == other.condition and self.webkit_platform == other.webkit_platform
def __hash__(self):
return hash((self.header, self.condition))
class UsingStatement(object):
def __init__(self, name, alias, condition):
self.name = name
self.alias = alias
self.condition = condition
class ObjCWrappedType(object):
def __init__(self, ns_type, wrapper, condition):
self.ns_type = ns_type
self.wrapper = wrapper
self.condition = condition
def sanitize_string_for_variable_name(string):
return string.replace('()', '').replace('.', '')
_license_header = """/*
* Copyright (C) 2022-2023 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"""
def one_argument_coder_declaration_cf(type):
result = []
result.append('')
if type.condition is not None:
result.append('#if ' + type.condition)
name_with_template = type.namespace_and_name()
result.append('template<> struct ArgumentCoder<' + name_with_template + '> {')
for encoder in type.encoders:
result.append(' static void encode(' + encoder + '&, ' + name_with_template + ');')
result.append('};')
result.append('template<> struct ArgumentCoder<RetainPtr<' + name_with_template + '>> {')
for encoder in type.encoders:
result.append(' static void encode(' + encoder + '& encoder, const RetainPtr<' + name_with_template + '>& retainPtr)')
result.append(' {')
result.append(' ArgumentCoder<' + name_with_template + '>::encode(encoder, retainPtr.get());')
result.append(' }')
result.append(' static std::optional<RetainPtr<' + name_with_template + '>> decode(Decoder&);')
result.append('};')
if type.condition is not None:
result.append('#endif')
return result
def one_argument_coder_declaration(type, template_argument):
if type.cf_type is not None:
return one_argument_coder_declaration_cf(type)
result = []
result.append('')
if type.condition is not None:
result.append('#if ' + type.condition)
name_with_template = type.namespace_and_name()
if template_argument is not None:
name_with_template = name_with_template + '<' + template_argument.namespace + '::' + template_argument.name + '>'
result.append('template<> struct ArgumentCoder<' + name_with_template + '> {')
for encoder in type.encoders:
if type.cf_type is not None:
result.append(' static void encode(' + encoder + '&, ' + name_with_template + ');')
result.append(' static void encode(' + encoder + '& encoder, const RetainPtr<' + name_with_template + '>& retainPtr)')
result.append(' {')
result.append(' ArgumentCoder<' + name_with_template + '>::encode(encoder, retainPtr.get());')
result.append(' }')
elif type.rvalue:
result.append(' static void encode(' + encoder + '&, ' + name_with_template + '&&);')
else:
result.append(' static void encode(' + encoder + '&, const ' + name_with_template + '&);')
if type.cf_type is not None:
result.append(' static std::optional<RetainPtr<' + name_with_template + '>> decode(Decoder&);')
elif type.return_ref:
result.append(' static std::optional<Ref<' + name_with_template + '>> decode(Decoder&);')
else:
result.append(' static std::optional<' + name_with_template + '> decode(Decoder&);')
result.append('};')
if type.condition is not None:
result.append('#endif')
return result
def argument_coder_declarations(serialized_types, skip_nested):
result = []
for type in serialized_types:
if type.nested == skip_nested:
continue
if type.templates:
for template in type.templates:
result.extend(one_argument_coder_declaration(type, template))
else:
result.extend(one_argument_coder_declaration(type, None))
return result
def typenames(alias):
return ', '.join(['typename' for x in range(alias.count(',') + 1)])
def remove_template_parameters(alias):
match = re.search(r'(struct|class) (.*)<', alias)
assert match
return match.groups()[1]
def remove_alias_struct_or_class(alias):
match = re.search(r'(struct|class) (.*)', alias)
assert match
return match.groups()[1].replace(',', ', ')
def alias_struct_or_class(alias):
match = re.search(r'(struct|class) (.*)', alias)
assert match
return match.groups()[0]
def get_alias_namespace(alias):
match = re.search(r'[ ,()<>]+([A-Za-z0-9_]+)::[A-Za-z0-9_]+', alias)
if(match):
return match.groups()[0]
else:
return None
def generate_forward_declarations(serialized_types, serialized_enums, additional_forward_declarations):
result = []
result.append('')
serialized_enums_by_namespace = dict()
serialized_types_by_namespace = dict()
template_types_by_namespace = dict()
for enum in serialized_enums:
if enum.is_nested():
continue
if enum.namespace in serialized_enums_by_namespace:
serialized_enums_by_namespace[enum.namespace] += [enum, ]
else:
serialized_enums_by_namespace[enum.namespace] = [enum, ]
for type in serialized_types:
for template in type.templates:
if template.namespace in template_types_by_namespace:
template_types_by_namespace[template.namespace] += [template, ]
else:
template_types_by_namespace[template.namespace] = [template, ]
if type.should_skip_forward_declare():
continue
if type.alias is None and type.cf_type is not None:
continue
if type.namespace in serialized_types_by_namespace:
serialized_types_by_namespace[type.namespace] += [type, ]
else:
serialized_types_by_namespace[type.namespace] = [type, ]
all_namespaces = set(serialized_enums_by_namespace.keys())
all_namespaces = all_namespaces.union(set(serialized_types_by_namespace.keys()))
all_namespaces = all_namespaces.union(set(template_types_by_namespace.keys()))
for namespace in sorted(all_namespaces, key=lambda x: (x is None, x)):
if namespace is not None:
result.append('namespace ' + namespace + ' {')
for enum in serialized_enums_by_namespace.get(namespace, []):
if enum.condition is not None:
result.append('#if ' + enum.condition)
result.append('enum class ' + enum.name + ' : ' + enum.underlying_type + ';')
if enum.condition is not None:
result.append('#endif')
for type in serialized_types_by_namespace.get(namespace, []):
if type.condition is not None:
result.append('#if ' + type.condition)
if type.cf_type is None and type.alias is None:
result.append(type.cpp_type_from_struct_or_class() + ' ' + type.cpp_struct_or_class_name() + ';')
if type.condition is not None:
result.append('#endif')
for template in template_types_by_namespace.get(namespace, []):
result.append(template.forward_declaration())
if namespace is not None:
result.append('}')
result.append('')
for declaration in additional_forward_declarations:
if declaration.condition is not None:
result.append('#if ' + declaration.condition)
result.append(declaration.declaration + ';')
if declaration.condition is not None:
result.append('#endif')
for namespace in sorted(all_namespaces, key=lambda x: (x is None, x)):
for type in serialized_types_by_namespace.get(namespace, []):
if type.alias is not None:
if type.condition is not None:
result.append('#if ' + type.condition)
if namespace is not None:
result.append('namespace ' + namespace + ' {')
if namespace is None or get_alias_namespace(type.alias) is None or get_alias_namespace(type.alias) == type.namespace:
result.append('template<' + typenames(type.alias) + '> ' + alias_struct_or_class(type.alias) + ' ' + remove_template_parameters(type.alias) + ';')
result.append('using ' + type.name + ' = ' + remove_alias_struct_or_class(type.alias) + ';')
if namespace is not None:
result.append('}')
if type.condition is not None:
result.append('#endif')
return result
def generate_header(serialized_types, serialized_enums, additional_forward_declarations):
result = []
result.append(_license_header)
result.append('#pragma once')
result.append('')
for header in ['<wtf/ArgumentCoder.h>', '<wtf/OptionSet.h>', '<wtf/Ref.h>', '<wtf/RetainPtr.h>']:
result.append('#include ' + header)
result += generate_forward_declarations(serialized_types, serialized_enums, additional_forward_declarations)
result.append('')
result.append('namespace IPC {')
result.append('')
result.append('class Decoder;')
result.append('class Encoder;')
result.append('class StreamConnectionEncoder;')
result = result + argument_coder_declarations(serialized_types, True)
result.append('')
result.append('} // namespace IPC\n')
result.append('')
result.append('namespace WTF {')
result.append('')
for enum in serialized_enums:
if enum.is_nested():
continue
if enum.underlying_type == 'bool':
continue
if enum.condition is not None:
result.append('#if ' + enum.condition)
result.append('template<> bool ' + enum.function_name() + '<' + enum.namespace_and_name() + enum.additional_template_parameter() + '>(' + enum.parameter() + ');')
if enum.condition is not None:
result.append('#endif')
result.append('')
result.append('} // namespace WTF')
result.append('')
return '\n'.join(result)
def resolve_inheritance(serialized_types):
result = []
for serialized_type in serialized_types:
if serialized_type.parent_class_name is not None:
for possible_parent in serialized_types:
if possible_parent.namespace_and_name() == serialized_type.parent_class_name:
serialized_type.parent_class = possible_parent
break
result.append(serialized_type)
return result
def check_type_members(type, checking_parent_class):
result = []
if type.parent_class is not None:
result = check_type_members(type.parent_class, True)
for member in type.members:
if member.condition is not None:
result.append('#if ' + member.condition)
result.append(' static_assert(std::is_same_v<std::remove_cvref_t<decltype(instance.' + member.name + ')>, ' + member.type + '>);')
if member.condition is not None:
result.append('#endif')
for member in type.dictionary_members:
result.append(' static_assert(std::is_same_v<std::remove_cvref_t<decltype(instance.m_' + member.type + ')>, ' + member.dictionary_type() + '>);')
if type.can_assert_member_order_is_correct():
# FIXME: Add this check for types with parent classes, too.
if type.parent_class is None and not checking_parent_class:
result.append(' struct ShouldBeSameSizeAs' + type.name + ' : public VirtualTableAndRefCountOverhead<std::is_polymorphic_v<' + type.namespace_and_name() + '>, ' + ('true' if type.return_ref else 'false') + '> {')
for member in type.members:
if member.condition is not None:
result.append('#if ' + member.condition)
result.append(' ' + member.type + ' ' + member.name + (' : 1' if 'BitField' in member.attributes else '') + ';')
if member.condition is not None:
result.append('#endif')
for member in type.dictionary_members:
result.append(' ' + member.dictionary_type() + ' ' + member.type + ';')
result.append(' };')
result.append(' static_assert(sizeof(ShouldBeSameSizeAs' + type.name + ') == sizeof(' + type.namespace_and_name() + '));')
result.append(' static_assert(MembersInCorrectOrder < 0')
for member in type.members:
if 'BitField' in member.attributes:
continue
if member.condition is not None:
result.append('#if ' + member.condition)
result.append(' , offsetof(' + type.namespace_and_name() + ', ' + member.name + ')')
if member.condition is not None:
result.append('#endif')
for member in type.dictionary_members:
result.append(' , offsetof(' + type.namespace_and_name() + ', m_' + member.type + ')')
result.append(' >::value);')
if type.has_optional_tuple_bits():
serialized_members = type.serialized_members()
optional_tuple_state = None
for i in range(len(serialized_members)):
member = serialized_members[i]
if member.optional_tuple_bits():
result.append(' static_assert(static_cast<uint64_t>(' + serialized_members[i + 1].optional_tuple_bit() + ') == 1);')
result.append(' static_assert(BitsInIncreasingOrder<')
optional_tuple_state = 'begin'
elif member.optional_tuple_bit():
if member.condition is not None:
result.append('#if ' + member.condition)
result.append(' ' + (', ' if optional_tuple_state == 'middle' else '') + 'static_cast<uint64_t>(' + member.optional_tuple_bit() + ')')
if member.condition is not None:
result.append('#endif')
optional_tuple_state = 'middle'
elif optional_tuple_state == 'middle':
result.append(' >::value);')
optional_tuple_state = None
if optional_tuple_state == 'middle':
result.append(' >::value);')
optional_tuple_state = None
result.append('')
return result
def encode_cf_type(type):
result = []
if type.from_cf_method is not None:
result.append(' encoder << ' + type.from_cf_method + '(instance);')
else:
result.append(' encoder << ' + type.cf_wrapper_type() + ' { instance };')
return result
def encode_type(type):
if type.cf_type is not None:
return encode_cf_type(type)
result = []
if type.parent_class is not None:
result = result + encode_type(type.parent_class)
for member in type.serialized_members():
if member.condition is not None:
result.append('#if ' + member.condition)
if member.is_subclass:
result.append(' if (auto* subclass = dynamicDowncast<' + member.namespace + "::" + member.name + '>(instance)) {')
result.append(' encoder << ' + type.subclass_enum_name() + "::" + member.name + ";")
if type.rvalue:
result.append(' encoder << WTFMove(*subclass);')
else:
result.append(' encoder << *subclass;')
result.append(' return;')
result.append(' }')
elif member.optional_tuple_bits():
result.append(' encoder << instance.' + member.name + ';')
bits_variable_name = member.name
elif member.optional_tuple_bit() is not None:
result.append(' if (instance.' + bits_variable_name + ' & ' + member.optional_tuple_bit() + ')')
result.append(' encoder << instance.' + member.name + ';')
else:
if type.rvalue and '()' not in member.name:
if 'EncodeRequestBody' in member.attributes:
result.append(' RefPtr ' + member.name + 'Body = instance.' + member.name + '.httpBody();')
result.append(' encoder << WTFMove(instance.' + member.name + ');')
if 'EncodeRequestBody' in member.attributes:
result.append(' encoder << IPC::FormDataReference { WTFMove(' + member.name + 'Body) };')
else:
result.append(' encoder << instance.' + member.name + ';')
if 'EncodeRequestBody' in member.attributes:
result.append(' encoder << IPC::FormDataReference { instance.' + member.name + '.httpBody() };')
if member.condition is not None:
result.append('#endif')
for member in type.dictionary_members:
result.append(' encoder << instance.m_' + member.type + ';')
return result
def decode_cf_type(type):
result = []
result.append(' auto result = decoder.decode<' + type.cf_wrapper_type() + '>();')
result.append(' if (UNLIKELY(!decoder.isValid()))')
result.append(' return std::nullopt;')
cf_method = 'toCF'
if type.to_cf_method is not None:
result.append(' return ' + type.to_cf_method + ';')
else:
result.append(' return result->toCF();')
return result
def decode_type(type):
if type.cf_type is not None:
return decode_cf_type(type)
result = []
if type.parent_class is not None:
result = result + decode_type(type.parent_class)
if type.members_are_subclasses:
result.append(' auto type = decoder.decode<' + type.subclass_enum_name() + '>();')
result.append(' UNUSED_PARAM(type);')
result.append(' if (UNLIKELY(!decoder.isValid()))')
result.append(' return std::nullopt;')
result.append('')
if type.has_optional_tuple_bits() and type.populate_from_empty_constructor:
result.append(' ' + type.namespace_and_name() + ' result;')
for member in type.serialized_members():
if member.condition is not None:
result.append('#if ' + member.condition)
sanitized_variable_name = sanitize_string_for_variable_name(member.name)
r = re.compile("SecureCodingAllowed=\\[(.*)\\]")
decodable_classes = [r.match(m).groups()[0] for m in list(filter(r.match, member.attributes))]
if len(decodable_classes) == 1:
match = re.search("RetainPtr<(.*)>", member.type)
assert match
for attribute in member.attributes:
precondition = re.search(r'Precondition=\'(.*)\'', attribute)
if precondition:
condition, = precondition.groups()
result.append(' if (!(' + condition + '))')
result.append(' return std::nullopt;')
break
else:
condition = re.search(r'Precondition', attribute)
assert not condition
result.append(' auto ' + sanitized_variable_name + ' = decoder.decodeWithAllowedClasses<' + match.groups()[0] + '>({ ' + decodable_classes[0] + ' });')
elif member.is_subclass:
result.append(' if (type == ' + type.subclass_enum_name() + "::" + member.name + ') {')
typename = member.namespace + "::" + member.name
result.append(' auto result = decoder.decode<Ref<' + typename + '>>();')
result.append(' if (UNLIKELY(!decoder.isValid()))')
result.append(' return std::nullopt;')
result.append(' return WTFMove(*result);')
result.append(' }')
elif member.optional_tuple_bits():
bits_name = sanitized_variable_name
result.append(' auto ' + bits_name + ' = decoder.decode<' + member.type + '>();')
result.append(' if (!' + bits_name + ')')
result.append(' return std::nullopt;')
if type.populate_from_empty_constructor:
result.append(' result.' + member.name + ' = *' + bits_name + ';')
elif member.optional_tuple_bit() is not None:
if type.populate_from_empty_constructor:
result.append(' if (*' + bits_name + ' & ' + member.optional_tuple_bit() + ') {')
result.append(' if (auto deserialized = decoder.decode<' + member.type + '>())')
result.append(' result.' + sanitized_variable_name + ' = WTFMove(*deserialized);')
result.append(' else')
result.append(' return std::nullopt;')
result.append(' }')
else:
result.append('')
result.append(' ' + member.type + ' ' + sanitized_variable_name + ' { };')
result.append(' if (*' + bits_name + ' & ' + member.optional_tuple_bit() + ') {')
result.append(' if (auto deserialized = decoder.decode<' + member.type + '>())')
result.append(' ' + sanitized_variable_name + ' = WTFMove(*deserialized);')
result.append(' else')
result.append(' return std::nullopt;')
result.append(' }')
else:
assert len(decodable_classes) == 0
result.append(' auto ' + sanitized_variable_name + ' = decoder.decode<' + member.type + '>();')
if 'EncodeRequestBody' in member.attributes:
result.append(' if (' + sanitized_variable_name + ') {')
result.append(' if (auto ' + sanitized_variable_name + 'Body = decoder.decode<IPC::FormDataReference>())')
result.append(' ' + sanitized_variable_name + '->setHTTPBody(' + sanitized_variable_name + 'Body->takeData());')
result.append(' }')
for attribute in member.attributes:
match = re.search(r'Validator=\'(.*)\'', attribute)
if match:
validator, = match.groups()
result.append(' if (UNLIKELY(!decoder.isValid()))')
result.append(' return std::nullopt;')
result.append('')
result.append(' if (!(' + validator + '))')
result.append(' return std::nullopt;')
continue
else:
match = re.search(r'Validator', attribute)
assert not match
if member.condition is not None:
result.append('#endif')
for member in type.dictionary_members:
result.append(' auto ' + member.type + ' = decoder.decode<' + member.dictionary_type() + '>();')
result.append(' if (!' + member.type + ')')
result.append(' return std::nullopt;')
# FIXME: Add question marks to the serialization.in files and add these checks here:
# if not member.value_is_optional() and member.array_contents() is None and member.dictionary_contents() is None:
# result.append(' if (!*' + member.type + ')')
# result.append(' return std::nullopt;')
result.append('')
return result
def indent(indentation):
return ' ' * indentation
def construct_type(type, specialization, indentation):
result = []
fulltype = type.namespace_and_name_for_construction(specialization)
if type.create_using:
result.append(indent(indentation) + fulltype + '::' + type.create_using + '(')
elif type.return_ref:
result.append(indent(indentation) + fulltype + '::create(')
else:
result.append(indent(indentation) + fulltype + ' {')
if type.parent_class is not None:
result = result + construct_type(type.parent_class, specialization, indentation + 1)
if len(type.members) != 0:
result[-1] += ','
serialized_members = type.serialized_members()
for i in range(len(serialized_members)):
member = serialized_members[i]
if member.condition is not None:
result.append('#if ' + member.condition)
result.append(indent(indentation + 1) + 'WTFMove(' + ('' if member.optional_tuple_bit() else '*') + sanitize_string_for_variable_name(member.name) + ')' + ('' if i == len(serialized_members) - 1 else ','))
if member.condition is not None:
result.append('#endif')
for i in range(len(type.dictionary_members)):
member = type.dictionary_members[i]
result.append(indent(indentation + 1) + 'WTFMove(*' + member.type + ')' + (',' if i < len(type.dictionary_members) - 1 else ''))
if type.create_using or type.return_ref:
result.append(indent(indentation) + ')')
else:
result.append(indent(indentation) + '}')
return result
def generate_one_impl(type, template_argument):
result = []
name_with_template = type.namespace_and_name()
if template_argument is not None:
name_with_template = name_with_template + '<' + template_argument.namespace + '::' + template_argument.name + '>'
if type.condition is not None:
result.append('#if ' + type.condition)
if type.members_are_subclasses:
result.append('enum class ' + type.subclass_enum_name() + " : IPC::EncodedVariantIndex {")
for idx in range(0, len(type.members)):
member = type.members[idx]
if member.condition is not None:
result.append('#if ' + member.condition)
if idx == 0:
result.append(' ' + member.name)
else: