forked from signalapp/Signal-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProtoWrappers.py
executable file
·1791 lines (1469 loc) · 66.8 KB
/
ProtoWrappers.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
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import datetime
import argparse
import re
git_repo_path = os.path.abspath(subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).strip())
proto_syntax = None
def lower_camel_case(name):
result = name
# We have at least two segments, we'll have to split them up
if '_' in name:
splits = name.split('_')
splits = [captialize_first_letter(split.lower()) for split in splits]
splits[0] = splits[0].lower()
result = ''.join(splits)
# This name is all caps, lowercase it
elif name.isupper():
result = name.lower()
return supress_adjacent_capital_letters(result)
def camel_case(name):
result = name
splits = name.split('_')
splits = [captialize_first_letter(split) for split in splits]
result = ''.join(splits)
return supress_adjacent_capital_letters(result)
def captialize_first_letter(name):
if name.isupper():
name = name.lower()
return name[0].upper() + name[1:]
# The generated code for "Apple Swift Protos" suppresses
# adjacent capital letters in lower_camel_case.
def supress_adjacent_capital_letters(name):
chars = []
lastWasUpper = False
for char in name:
if lastWasUpper:
char = char.lower()
chars.append(char)
lastWasUpper = (char.upper() == char)
result = ''.join(chars)
if result.endswith('Id'):
result = result[:-2] + 'ID'
if result.endswith('Url'):
result = result[:-3] + 'URL'
return result
def swift_type_for_proto_primitive_type(proto_type):
if proto_type == 'string':
return 'String'
elif proto_type == 'uint64':
return 'UInt64'
elif proto_type == 'uint32':
return 'UInt32'
elif proto_type == 'fixed64':
return 'UInt64'
elif proto_type == 'bool':
return 'Bool'
elif proto_type == 'bytes':
return 'Data'
else:
return None
def is_swift_primitive_type(proto_type):
return proto_type in ('String', 'UInt64', 'UInt32', 'UInt64', 'Bool', 'Data')
# Provides conext for writing an indented block surrounded by braces.
#
# e.g.
#
# with BracedContext('class Foo', writer) as writer:
# with BracedContext('func bar() -> Bool', writer) as writer:
# return true
#
# Produces:
#
# class Foo {
# func bar() -> Bool {
# return true
# }
# }
#
class BracedContext:
def __init__(self, line, writer):
self.writer = writer
writer.add('%s {' % line)
def __enter__(self):
self.writer.push_indent()
return self.writer
def __exit__(self, *args):
self.writer.pop_indent()
self.writer.add('}')
class WriterContext:
def __init__(self, proto_name, swift_name, parent=None):
self.proto_name = proto_name
self.swift_name = swift_name
self.parent = parent
self.name_map = {}
class LineWriter:
def __init__(self, args):
self.contexts = []
# self.indent = 0
self.lines = []
self.args = args
self.current_indent = 0
def braced(self, line):
return BracedContext(line, self)
def push_indent(self):
self.current_indent = self.current_indent + 1
def pop_indent(self):
self.current_indent = self.current_indent - 1
if self.current_indent < 0:
raise Exception('Invalid indentation')
def all_context_proto_names(self):
return [context.proto_name for context in self.contexts]
def current_context(self):
return self.contexts[-1]
def indent(self):
return self.current_indent
# return len(self.contexts)
def push_context(self, proto_name, swift_name):
self.contexts.append(WriterContext(proto_name, swift_name))
self.push_indent()
def pop_context(self):
self.contexts.pop()
self.pop_indent()
def add(self, line):
self.lines.append((' ' * self.indent()) + line)
def add_raw(self, line):
self.lines.append(line)
def extend(self, text):
for line in text.split('\n'):
self.add(line)
def join(self):
lines = [line.rstrip() for line in self.lines]
return '\n'.join(lines)
def rstrip(self):
lines = self.lines
while len(lines) > 0 and len(lines[-1].strip()) == 0:
lines = lines[:-1]
self.lines = lines
def newline(self):
self.add('')
def add_objc(self):
if proto_syntax == 'proto2':
self.add('@objc ')
class BaseContext(object):
def __init__(self):
self.parent = None
self.proto_name = None
def inherited_proto_names(self):
if self.parent is None:
return []
if self.proto_name is None:
return []
return self.parent.inherited_proto_names() + [self.proto_name,]
def derive_swift_name(self):
names = self.inherited_proto_names()
return self.args.wrapper_prefix + ''.join(names)
def derive_wrapped_swift_name(self):
names = self.inherited_proto_names()
return self.args.proto_prefix + '_' + '.'.join(names)
def qualified_proto_name(self):
names = self.inherited_proto_names()
return '.'.join(names)
def children(self):
return []
def descendents(self):
result = []
for child in self.children():
result.append(child)
result.extend(child.descendents())
return result
def siblings(self):
result = []
if self.parent is not None:
result = self.parent.children()
return result
def ancestors(self):
result = []
if self.parent is not None:
result.append(self.parent)
result.extend(self.parent.ancestors())
return result
def context_for_proto_type(self, field):
should_deep_search = '.' in field.proto_type
for candidate in self.all_known_contexts(should_deep_search=should_deep_search):
if candidate.proto_name == field.proto_type:
return candidate
if candidate.qualified_proto_name() == field.proto_type:
return candidate
if candidate.derive_swift_name() == field.proto_type:
return candidate
return None
def all_known_contexts(self,should_deep_search=False):
if should_deep_search:
root_ancestor = self.ancestors()[-1]
return root_ancestor.descendents()
candidates = []
candidates.extend(self.descendents())
candidates.extend(self.siblings())
for ancestor in self.ancestors():
if ancestor.proto_name is None:
# Ignore the root context
continue
candidates.append(ancestor)
candidates.extend(ancestor.siblings())
return candidates
def base_swift_type_for_field(self, field):
swift_type = swift_type_for_proto_primitive_type(field.proto_type)
if swift_type is not None:
return swift_type
else:
matching_context = self.context_for_proto_type(field)
if matching_context is not None:
return matching_context.swift_name
else:
# Failure
return field.proto_type
def swift_type_for_field(self, field, suppress_optional=False):
base_type = self.base_swift_type_for_field(field)
if field.rules == 'optional':
if suppress_optional:
return base_type
can_be_optional = self.can_field_be_optional(field)
if can_be_optional:
return '%s?' % base_type
else:
return base_type
elif field.rules == 'required':
return base_type
elif field.rules == 'repeated':
return '[%s]' % base_type
else:
raise Exception('Unknown field type')
def is_field_primitive(self, field):
return field.proto_type in ('uint64',
'uint32',
'fixed64',
'bool', )
def can_field_be_optional(self, field):
if self.is_field_primitive(field):
return not field.is_required
# if field.proto_type == 'uint64':
# return False
# elif field.proto_type == 'uint32':
# return False
# elif field.proto_type == 'fixed64':
# return False
# elif field.proto_type == 'bool':
# return False
# elif self.is_field_an_enum(field):
if self.is_field_an_enum(field):
return True
else:
return True
def is_field_an_enum(self, field):
matching_context = self.context_for_proto_type(field)
if matching_context is not None:
if type(matching_context) is EnumContext:
return True
return False
def is_field_oneof(self, field):
matching_context = self.context_for_proto_type(field)
if matching_context is not None:
if type(matching_context) is OneOfContext:
return True
return False
def is_field_a_proto(self, field):
matching_context = self.context_for_proto_type(field)
if matching_context is not None:
if type(matching_context) is MessageContext:
return True
return False
def can_field_be_optional_objc(self, field):
return self.can_field_be_optional(field) and not self.is_field_primitive(field) and not self.is_field_an_enum(field)
def default_value_for_field(self, field):
if field.rules == 'repeated':
return '[]'
if field.default_value is not None and len(field.default_value) > 0:
return field.default_value
if field.rules == 'optional':
can_be_optional = self.can_field_be_optional(field)
if can_be_optional:
return 'nil'
if field.proto_type == 'uint64':
return '0'
elif field.proto_type == 'uint32':
return '0'
elif field.proto_type == 'fixed64':
return '0'
elif field.proto_type == 'bool':
return 'false'
elif self.is_field_an_enum(field):
# TODO: Assert that rules is empty.
enum_context = self.context_for_proto_type(field)
return enum_context.default_value()
return None
class FileContext(BaseContext):
def __init__(self, args):
BaseContext.__init__(self)
self.args = args
self.messages = []
self.enums = []
def children(self):
return self.enums + self.messages
def prepare(self):
for child in self.children():
child.prepare()
def generate(self, writer):
writer.extend('''//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalCoreKit''')
if proto_syntax == 'proto3':
writer.add('import SwiftProtobuf')
writer.newline()
writer.extend('''
// WARNING: This code is generated. Only edit within the markers.
'''.strip())
writer.newline()
writer.invalid_protobuf_error_name = '%sError' % self.args.wrapper_prefix
writer.extend(('''
public enum %s: Error {
case invalidProtobuf(description: String)
}
''' % writer.invalid_protobuf_error_name).strip())
writer.newline()
for child in self.children():
child.generate(writer)
class MessageField:
def __init__(self, name, index, rules, proto_type, default_value, sort_index, is_required):
self.name = name
self.index = index
self.rules = rules
self.proto_type = proto_type
self.default_value = default_value
self.sort_index = sort_index
self.is_required = is_required
def has_accessor_name(self):
name = 'has' + self.name_swift[0].upper() + self.name_swift[1:]
if name == 'hasId':
# TODO: I'm not sure why "Apple Swift Proto" code formats the
# the name in this way.
name = 'hasID'
elif name == 'hasUrl':
# TODO: I'm not sure why "Apple Swift Proto" code formats the
# the name in this way.
name = 'hasURL'
return name
class MessageContext(BaseContext):
def __init__(self, args, parent, proto_name):
BaseContext.__init__(self)
self.args = args
self.parent = parent
self.proto_name = proto_name
self.messages = []
self.enums = []
self.oneofs = []
self.field_map = {}
def fields(self):
fields = self.field_map.values()
fields = sorted(fields, key=lambda f: f.sort_index)
return fields
def field_indices(self):
return [field.index for field in self.fields()]
def field_names(self):
return [field.name for field in self.fields()]
def children(self):
return self.enums + self.messages + self.oneofs
def prepare(self):
self.swift_name = self.derive_swift_name()
self.swift_builder_name = "%sBuilder" % self.swift_name
for child in self.children():
child.prepare()
def generate(self, writer):
for child in self.messages:
child.generate(writer)
for child in self.enums:
child.generate(writer)
for child in self.oneofs:
child.generate(writer)
writer.add('// MARK: - %s' % self.swift_name)
writer.newline()
writer.add_objc()
writer.add('public class %s: NSObject {' % self.swift_name)
writer.newline()
writer.push_context(self.proto_name, self.swift_name)
wrapped_swift_name = self.derive_wrapped_swift_name()
# Prepare fields
explict_fields = []
implict_fields = []
uuid_field = None
e164_field = None
for field in self.fields():
field.type_swift = self.swift_type_for_field(field)
field.type_swift_not_optional = self.swift_type_for_field(field, suppress_optional=True)
field.name_swift = lower_camel_case(field.name)
is_explicit = False
if field.is_required:
is_explicit = True
elif self.is_field_a_proto(field):
is_explicit = True
if is_explicit:
explict_fields.append(field)
else:
implict_fields.append(field)
# See if we need to add SignalServiceAddress helpers
if field.name.endswith('Uuid') and field.proto_type == 'string':
uuid_field = field
elif field.name.endswith('E164') and field.proto_type == 'string':
e164_field = field
# Ensure that no enum are required.
if proto_syntax == 'proto2' and self.is_field_an_enum(field) and field.is_required:
raise Exception('Enum fields cannot be required: %s.%s' % ( self.proto_name, field.name, ))
self.generate_builder(writer)
writer.add('fileprivate let proto: %s' % wrapped_swift_name )
writer.newline()
# Property Declarations
if len(explict_fields) > 0:
for field in explict_fields:
type_name = field.type_swift_not_optional if field.is_required else field.type_swift
writer.add_objc()
writer.add('public let %s: %s' % (field.name_swift, type_name))
if (not field.is_required) and field.rules != 'repeated' and (not self.is_field_a_proto(field)):
writer.add_objc()
writer.add('public var %s: Bool {' % field.has_accessor_name() )
writer.push_indent()
writer.add('return proto.%s' % field.has_accessor_name() )
writer.pop_indent()
writer.add('}')
writer.newline()
if len(implict_fields) > 0:
for field in implict_fields:
if field.rules == 'optional':
can_be_optional = not self.is_field_primitive(field)
if can_be_optional:
def write_field_getter(is_objc_accessible, is_required_optional):
if is_required_optional:
writer.add('// This "unwrapped" accessor should only be used if the "has value" accessor has already been checked.')
if is_objc_accessible:
writer.add_objc()
writer.add('public var unwrapped%s: %s {' % ( camel_case(field.name_swift), field.type_swift_not_optional, ))
writer.push_indent()
writer.add('if !%s {' % field.has_accessor_name() )
writer.push_indent()
writer.add('// TODO: We could make this a crashing assert.')
writer.add('owsFailDebug("Unsafe unwrap of missing optional: %s.%s.")' % ( self.proto_name, field.name_swift, ) )
writer.pop_indent()
writer.add('}')
else:
if is_objc_accessible:
writer.add_objc()
writer.add('public var %s: %s? {' % ( field.name_swift, field.type_swift_not_optional, ))
writer.push_indent()
writer.add('guard %s else {' % field.has_accessor_name() )
writer.push_indent()
writer.add('return nil')
writer.pop_indent()
writer.add('}')
if self.is_field_an_enum(field):
enum_context = self.context_for_proto_type(field)
writer.add('return %s(proto.%s)' % ( enum_context.wrap_func_name(), field.name_swift, ) )
elif self.is_field_oneof(field):
oneof_context = self.context_for_proto_type(field)
writer.add('guard let %s = proto.%s else {' % ( field.name_swift, field.name_swift, ))
writer.push_indent()
writer.add('owsFailDebug("%s was unexpectedly nil")' % field.name_swift )
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.add('guard let unwrapped%s = try? %s(%s) else {' % ( camel_case(field.name_swift), oneof_context.wrap_func_name(), field.name_swift, ))
writer.push_indent()
writer.add('owsFailDebug("failed to unwrap %s")' % field.name_swift )
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.add('return unwrapped%s' % camel_case(field.name_swift) )
else:
writer.add('return proto.%s' % field.name_swift )
writer.pop_indent()
writer.add('}')
if self.is_field_an_enum(field):
write_field_getter(is_objc_accessible=False, is_required_optional=False)
write_field_getter(is_objc_accessible=True, is_required_optional=True)
elif self.is_field_oneof(field):
write_field_getter(is_objc_accessible=False, is_required_optional=False)
else:
write_field_getter(is_objc_accessible=True, is_required_optional=False)
else:
writer.add_objc()
writer.add('public var %s: %s {' % (field.name_swift, field.type_swift_not_optional))
writer.push_indent()
if self.is_field_an_enum(field):
enum_context = self.context_for_proto_type(field)
writer.add('return %s(proto.%s)' % ( enum_context.wrap_func_name(), field.name_swift, ) )
else:
writer.add('return proto.%s' % field.name_swift )
writer.pop_indent()
writer.add('}')
writer.add_objc()
writer.add('public var %s: Bool {' % field.has_accessor_name() )
writer.push_indent()
if proto_syntax == 'proto3':
# TODO: We might want to return false for unknown/0 enum?
if field.proto_type in ['bytes', 'string']:
writer.add('return !proto.%s.isEmpty' % field.name_swift )
else:
writer.add('return true')
else:
writer.add('return proto.%s' % field.has_accessor_name() )
writer.pop_indent()
writer.add('}')
writer.newline()
elif field.rules == 'repeated':
writer.add_objc()
writer.add('public var %s: %s {' % (field.name_swift, field.type_swift_not_optional))
writer.push_indent()
writer.add('return proto.%s' % field.name_swift )
writer.pop_indent()
writer.add('}')
writer.newline()
else:
writer.add_objc()
writer.add('public var %s: %s {' % (field.name_swift, field.type_swift_not_optional))
writer.push_indent()
if self.is_field_an_enum(field):
enum_context = self.context_for_proto_type(field)
writer.add('return %s(proto.%s)' % ( enum_context.unwrap_func_name(), field.name_swift, ) )
elif self.is_field_oneof(field):
oneof_context = self.context_for_proto_type(field)
writer.add('return %s(proto.%s)' % ( oneof_context.unwrap_func_name(), field.name_swift, ) )
else:
writer.add('return proto.%s' % field.name_swift )
writer.pop_indent()
writer.add('}')
writer.newline()
if uuid_field and e164_field and not args.skip_address_helpers:
accessor_prefix = uuid_field.name.replace('Uuid', '')
address_accessor = accessor_prefix + 'Address'
address_has_accessor = 'hasValid' + accessor_prefix[0].upper() + accessor_prefix[1:]
# hasValidAddress
writer.add_objc()
writer.add('public var %s: Bool {' % address_has_accessor)
writer.push_indent()
writer.add('return %s != nil' % address_accessor)
writer.pop_indent()
writer.add('}')
# address accessor
writer.add_objc()
writer.add('public var %s: SignalServiceAddress? {' % address_accessor)
writer.push_indent()
writer.add('guard %s || %s else { return nil }' % (e164_field.has_accessor_name(), uuid_field.has_accessor_name()))
writer.newline()
writer.add('let uuidString: String? = {')
writer.push_indent()
writer.add('guard %s else { return nil }' % uuid_field.has_accessor_name())
writer.newline()
writer.add('guard let %s = %s else {' % (uuid_field.name_swift, uuid_field.name_swift))
writer.push_indent()
writer.add('owsFailDebug("%s was unexpectedly nil")' % uuid_field.name_swift)
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('return %s' % uuid_field.name_swift)
writer.pop_indent()
writer.add('}()')
writer.newline()
writer.add('let phoneNumber: String? = {')
writer.push_indent()
writer.add('guard %s else {' % e164_field.has_accessor_name())
writer.push_indent()
writer.add('// Shouldn’t happen in prod yet')
writer.add('assert(FeatureFlags.allowUUIDOnlyContacts)')
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('guard let %s = %s else {' % (e164_field.name_swift, e164_field.name_swift))
writer.push_indent()
writer.add('owsFailDebug("%s was unexpectedly nil")' % e164_field.name_swift)
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('guard !%s.isEmpty else {' % e164_field.name_swift)
writer.push_indent()
writer.add('owsFailDebug("%s was unexpectedly empty")' % e164_field.name_swift)
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('return %s' % e164_field.name_swift)
writer.pop_indent()
writer.add('}()')
writer.newline()
writer.add('let address = SignalServiceAddress(uuidString: uuidString, phoneNumber: phoneNumber)')
writer.add('guard address.isValid else {')
writer.push_indent()
writer.add('owsFailDebug("address was unexpectedly invalid")')
writer.add('return nil')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('return address')
writer.pop_indent()
writer.add('}')
writer.newline()
# Initializer
initializer_parameters = []
initializer_parameters.append('proto: %s' % wrapped_swift_name)
initializer_prefix = 'private init('
for field in explict_fields:
type_name = field.type_swift_not_optional if field.is_required else field.type_swift
parameter = '%s: %s' % (field.name_swift, type_name)
parameter = '\n' + ' ' * len(initializer_prefix) + parameter
initializer_parameters.append(parameter)
initializer_parameters = ', '.join(initializer_parameters)
writer.extend('%s%s) {' % ( initializer_prefix, initializer_parameters, ) )
writer.push_indent()
writer.add('self.proto = proto')
for field in explict_fields:
writer.add('self.%s = %s' % (field.name_swift, field.name_swift))
writer.pop_indent()
writer.add('}')
writer.newline()
# serializedData() func
writer.extend(('''
@objc
public func serializedData() throws -> Data {
return try self.proto.serializedData()
}
''').strip())
writer.newline()
# parseData() func
writer.add_objc()
writer.add('public class func parseData(_ serializedData: Data) throws -> %s {' % self.swift_name)
writer.push_indent()
writer.add('let proto = try %s(serializedData: serializedData)' % ( wrapped_swift_name, ) )
writer.add('return try parseProto(proto)')
writer.pop_indent()
writer.add('}')
writer.newline()
# parseData() func
writer.add('fileprivate class func parseProto(_ proto: %s) throws -> %s {' % ( wrapped_swift_name, self.swift_name, ) )
writer.push_indent()
for field in explict_fields:
if field.is_required:
if proto_syntax == 'proto2':
writer.add('guard proto.%s else {' % field.has_accessor_name() )
writer.push_indent()
writer.add('throw %s.invalidProtobuf(description: "\(logTag) missing required field: %s")' % ( writer.invalid_protobuf_error_name, field.name_swift, ) )
writer.pop_indent()
writer.add('}')
if self.is_field_an_enum(field):
# TODO: Assert that rules is empty.
enum_context = self.context_for_proto_type(field)
writer.add('let %s = %s(proto.%s)' % ( field.name_swift, enum_context.wrap_func_name(), field.name_swift, ) )
elif self.is_field_a_proto(field):
writer.add('let %s = try %s.parseProto(proto.%s)' % (field.name_swift, self.base_swift_type_for_field(field), field.name_swift)),
else:
writer.add('let %s = proto.%s' % ( field.name_swift, field.name_swift, ) )
writer.newline()
continue
default_value = self.default_value_for_field(field)
if default_value is None:
writer.add('var %s: %s' % (field.name_swift, field.type_swift))
else:
writer.add('var %s: %s = %s' % (field.name_swift, field.type_swift, default_value))
if field.rules == 'repeated':
if self.is_field_an_enum(field):
enum_context = self.context_for_proto_type(field)
writer.add('%s = proto.%s.map { %s($0) }' % ( field.name_swift, field.name_swift, enum_context.wrap_func_name(), ) )
elif self.is_field_a_proto(field):
writer.add('%s = try proto.%s.map { try %s.parseProto($0) }' % ( field.name_swift, field.name_swift, self.base_swift_type_for_field(field), ) )
else:
writer.add('%s = proto.%s' % ( field.name_swift, field.name_swift, ) )
else:
writer.add('if proto.%s {' % field.has_accessor_name() )
writer.push_indent()
if self.is_field_an_enum(field):
# TODO: Assert that rules is empty.
enum_context = self.context_for_proto_type(field)
writer.add('%s = %s(proto.%s)' % ( field.name_swift, enum_context.wrap_func_name(), field.name_swift, ) )
elif self.is_field_a_proto(field):
writer.add('%s = try %s.parseProto(proto.%s)' % (field.name_swift, self.base_swift_type_for_field(field), field.name_swift)),
else:
writer.add('%s = proto.%s' % ( field.name_swift, field.name_swift, ) )
writer.pop_indent()
writer.add('}')
writer.newline()
writer.add('// MARK: - Begin Validation Logic for %s -' % self.swift_name)
writer.newline()
# Preserve existing validation logic.
if self.swift_name in args.validation_map:
validation_block = args.validation_map[self.swift_name]
if validation_block:
writer.add_raw(validation_block)
writer.newline()
writer.add('// MARK: - End Validation Logic for %s -' % self.swift_name)
writer.newline()
initializer_prefix = 'let result = %s(' % self.swift_name
initializer_arguments = []
initializer_arguments.append('proto: proto')
for field in explict_fields:
argument = '%s: %s' % (field.name_swift, field.name_swift)
argument = '\n' + ' ' * len(initializer_prefix) + argument
initializer_arguments.append(argument)
initializer_arguments = ', '.join(initializer_arguments)
writer.extend('%s%s)' % ( initializer_prefix, initializer_arguments, ) )
writer.add('return result')
writer.pop_indent()
writer.add('}')
writer.newline()
# description
writer.add_objc()
writer.add('public override var debugDescription: String {')
writer.push_indent()
writer.add('return "\(proto)"')
writer.pop_indent()
writer.add('}')
writer.newline()
writer.pop_context()
writer.rstrip()
writer.add('}')
writer.newline()
self.generate_debug_extension(writer)
def generate_debug_extension(self, writer):
writer.add('#if DEBUG')
writer.newline()
with writer.braced('extension %s' % self.swift_name) as writer:
writer.add_objc()
with writer.braced('public func serializedDataIgnoringErrors() -> Data?') as writer:
writer.add('return try! self.serializedData()')
writer.newline()
with writer.braced('extension %s.%s' % ( self.swift_name, self.swift_builder_name )) as writer:
writer.add_objc()
with writer.braced('public func buildIgnoringErrors() -> %s?' % self.swift_name) as writer:
writer.add('return try! self.build()')
writer.newline()
writer.add('#endif')
writer.newline()
def generate_builder(self, writer):
wrapped_swift_name = self.derive_wrapped_swift_name()
writer.add('// MARK: - %s' % self.swift_builder_name)
writer.newline()
# Required Fields
required_fields = [field for field in self.fields() if field.is_required]
required_init_params = []
required_init_args = []
if len(required_fields) > 0:
for field in required_fields:
if field.rules == 'repeated':
param_type = '[' + self.base_swift_type_for_field(field) + ']'
else:
param_type = self.base_swift_type_for_field(field)
required_init_params.append('%s: %s' % ( field.name_swift, param_type) )
required_init_args.append('%s: %s' % ( field.name_swift, field.name_swift) )
# Convenience accessor.
writer.add_objc()
with writer.braced('public class func builder(%s) -> %s' % (
', '.join(required_init_params),
self.swift_builder_name,
)) as writer:
writer.add('return %s(%s)' % (self.swift_builder_name, ', '.join(required_init_args), ))
writer.newline()
# asBuilder()
writer.add('// asBuilder() constructs a builder that reflects the proto\'s contents.')
writer.add_objc()
with writer.braced('public func asBuilder() -> %s' % (
self.swift_builder_name,
)) as writer:
writer.add('let builder = %s(%s)' % (self.swift_builder_name, ', '.join(required_init_args), ))
for field in self.fields():
if field.is_required:
continue
accessor_name = field.name_swift
accessor_name = 'set' + accessor_name[0].upper() + accessor_name[1:]
can_be_optional = not self.is_field_primitive(field)
if field.rules == 'repeated':
writer.add('builder.%s(%s)' % ( accessor_name, field.name_swift, ))
elif can_be_optional:
writer.add('if let _value = %s {' % field.name_swift )
writer.push_indent()
writer.add('builder.%s(_value)' % ( accessor_name, ))
writer.pop_indent()
writer.add('}')
else:
writer.add('if %s {' % field.has_accessor_name() )
writer.push_indent()
writer.add('builder.%s(%s)' % ( accessor_name, field.name_swift, ))
writer.pop_indent()
writer.add('}')
writer.add('return builder')
writer.newline()
writer.add_objc()
writer.add('public class %s: NSObject {' % self.swift_builder_name)
writer.newline()
writer.push_context(self.proto_name, self.swift_name)
writer.add('private var proto = %s()' % wrapped_swift_name)
writer.newline()
# Initializer
writer.add_objc()
writer.add('fileprivate override init() {}')
writer.newline()
# Required-Field Initializer
if len(required_fields) > 0:
# writer.add('// Initializer for required fields')
writer.add_objc()
writer.add('fileprivate init(%s) {' % ', '.join(required_init_params))
writer.push_indent()
writer.add('super.init()')
writer.newline()
for field in required_fields:
accessor_name = field.name_swift
accessor_name = 'set' + accessor_name[0].upper() + accessor_name[1:]
writer.add('%s(%s)' % ( accessor_name, field.name_swift, ) )
writer.pop_indent()
writer.add('}')
writer.newline()
# Setters
for field in self.fields():
if field.rules == 'repeated':
# Add
accessor_name = field.name_swift
accessor_name = 'add' + accessor_name[0].upper() + accessor_name[1:]
writer.add_objc()
writer.add('public func %s(_ valueParam: %s) {' % ( accessor_name, self.base_swift_type_for_field(field), ))
writer.push_indent()
writer.add('var items = proto.%s' % ( field.name_swift, ) )
if self.is_field_an_enum(field):
enum_context = self.context_for_proto_type(field)
writer.add('items.append(%s(valueParam))' % enum_context.unwrap_func_name() )
elif self.is_field_oneof(field):
oneof_context = self.context_for_proto_type(field)
writer.add('items.append(%s(valueParam))' % oneof_context.unwrap_func_name() )
elif self.is_field_a_proto(field):
writer.add('items.append(valueParam.proto)')
else:
writer.add('items.append(valueParam)')
writer.add('proto.%s = items' % ( field.name_swift, ) )
writer.pop_indent()
writer.add('}')