-
Notifications
You must be signed in to change notification settings - Fork 25
/
codegen.py
executable file
·1789 lines (1549 loc) · 74.6 KB
/
codegen.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
# mypy: allow-any-generics
from __future__ import print_function
import itertools
import os
import re
import sys
import google.protobuf
PR_V = str(google.protobuf.__version__)
assert PR_V.split(".") >= "3.13.0".split("."), "python %s:%s: protobuf %s version not supported" % (sys.version, sys.executable, PR_V)
from collections import defaultdict, namedtuple, OrderedDict
from contextlib import contextmanager
from typing import (
Any,
DefaultDict,
Dict,
Iterator,
List,
Optional,
Set,
Text,
Tuple,
Union,
)
from google.protobuf.compiler import plugin_pb2 as plugin
from google.protobuf.descriptor_pb2 import (
DescriptorProto,
EnumDescriptorProto,
EnumValueDescriptorProto,
FieldDescriptorProto,
FieldOptions,
FileDescriptorProto,
OneofDescriptorProto,
SourceCodeInfo,
)
from google.protobuf.message import Message
from proto.github.com.gogo.protobuf.gogoproto import gogo_pb2
from proto.rust import extensions_pb2
# Proto type -> (RustType, ImplsEq, ImplsCopy))
PRIMITIVE_TYPES = {
FieldDescriptorProto.TYPE_FLOAT: ("f32", False, True),
FieldDescriptorProto.TYPE_DOUBLE: ("f64", False, True),
FieldDescriptorProto.TYPE_INT32: ("i32", True, True),
FieldDescriptorProto.TYPE_INT64: ("i64", True, True),
FieldDescriptorProto.TYPE_UINT32: ("u32", True, True),
FieldDescriptorProto.TYPE_UINT64: ("u64", True, True),
FieldDescriptorProto.TYPE_SINT32: ("::pb_jelly::Signed32", True, True),
FieldDescriptorProto.TYPE_SINT64: ("::pb_jelly::Signed64", True, True),
FieldDescriptorProto.TYPE_FIXED32: ("::pb_jelly::Fixed32", True, True),
FieldDescriptorProto.TYPE_FIXED64: ("::pb_jelly::Fixed64", True, True),
FieldDescriptorProto.TYPE_SFIXED32: ("::pb_jelly::Sfixed32", True, True),
FieldDescriptorProto.TYPE_SFIXED64: ("::pb_jelly::Sfixed64", True, True),
FieldDescriptorProto.TYPE_BOOL: ("bool", True, True),
FieldDescriptorProto.TYPE_STRING: ("::std::string::String", True, False),
FieldDescriptorProto.TYPE_BYTES: ("::std::vec::Vec<u8>", True, False),
}
BLOB_TYPE = "::pb_jelly::Lazy<::blob_pb::WrappedBlob>"
VEC_SLICE_TYPE = "::pb_jelly::Lazy<::blob_pb::VecSlice>"
LAZY_BYTES_TYPE = "::pb_jelly::Lazy<::bytes::Bytes>"
# pull out `x` from every instance of `::x::y::z`, but not `y` or `z`
CRATE_NAME_REGEX = re.compile(r"(?:^|\W)::(\w+)(?:::\w+)*")
# Keywords in rust which cannot be module names.
RESERVED_KEYWORDS = {
"as",
"break",
"const",
"continue",
"crate",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop",
"match",
"mod",
"move",
"mut",
"pub",
"ref",
"return",
"Self",
"self",
"static",
"struct",
"super",
"trait",
"true",
"type",
"unsafe",
"use",
"where",
"while",
"abstract",
"alignof",
"become",
"box",
"do",
"final",
"macro",
"offsetof",
"override",
"priv",
"proc",
"pure",
"sizeof",
"typeof",
"unsized",
"virtual",
"yield",
}
# SourceCodeLocation is defined by `message Location` here
# https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto
SourceCodeLocation = List[int]
ProtoTypes = Union[FileDescriptorProto, EnumDescriptorProto, DescriptorProto]
WalkRet = Tuple[
List[Tuple[List[Text], EnumDescriptorProto, SourceCodeLocation]],
List[Tuple[List[Text], DescriptorProto, SourceCodeLocation]],
]
ModTree = DefaultDict[Text, DefaultDict]
def camelcase(underscored: Text) -> Text:
return "".join(s.capitalize() for s in underscored.split("_"))
class StringIO(object):
def __init__(self) -> None:
self.contents: List[Text] = []
def write(self, s: Text) -> None:
self.contents.append(s)
def getvalue(self) -> Text:
return "".join(self.contents)
class RustType(object):
def __init__(self, ctx: 'Context', proto_file: FileDescriptorProto, msg_type: DescriptorProto, field: FieldDescriptorProto) -> None:
self.ctx = ctx
self.proto_file = proto_file
self.field = field
self.is_proto3 = proto_file.syntax == "proto3"
self.oneof = (
field.HasField("oneof_index") and msg_type.oneof_decl[field.oneof_index]
)
def default(self, msg_name: Text) -> Text:
if self.oneof:
if oneof_nullable(self.oneof):
return "None"
else:
return self.oneof_val(msg_name, "::std::default::Default::default()")
# Proto 3 doesn't have configurable default values.
if not self.is_proto3 and self.field.default_value != "":
if self.field.type == FieldDescriptorProto.TYPE_STRING:
return 'Some("%s".into())' % self.field.default_value
if self.field.type == FieldDescriptorProto.TYPE_BYTES:
return 'Some(b"%s".to_vec())' % self.field.default_value
if self.field.type in PRIMITIVE_TYPES:
typ_name = PRIMITIVE_TYPES[self.field.type][0]
if "::pb" in typ_name:
return "Some(%s(%s))" % (typ_name, self.field.default_value)
if typ_name.startswith("f") and "." not in self.field.default_value:
return "Some(%s.)" % self.field.default_value
return "Some(%s)" % self.field.default_value
if self.field.type == FieldDescriptorProto.TYPE_ENUM:
proto_type = self.ctx.find(self.field.type_name)
crate, mod_parts = self.ctx.crate_from_proto_filename(
self.proto_file.name
)
value = (
proto_type.rust_name(crate, mod_parts)
+ "::"
+ self.field.default_value
)
return "Some(%s)" % value
typ = FieldDescriptorProto.Type.Name(self.field.type)
raise RuntimeError(
"Default not supported on field {} of type {!r}".format(
self.field.name, typ
)
)
return "::std::default::Default::default()"
def is_length_delimited(self) -> bool:
length_delimited_types = [
FieldDescriptorProto.TYPE_MESSAGE,
FieldDescriptorProto.TYPE_STRING,
FieldDescriptorProto.TYPE_BYTES,
]
return self.field.type in length_delimited_types
def wire_format(self) -> Text:
if self.is_length_delimited():
return "LengthDelimited"
fixed64_types = [
FieldDescriptorProto.TYPE_DOUBLE,
FieldDescriptorProto.TYPE_FIXED64,
FieldDescriptorProto.TYPE_SFIXED64,
]
fixed32_types = [
FieldDescriptorProto.TYPE_FLOAT,
FieldDescriptorProto.TYPE_FIXED32,
FieldDescriptorProto.TYPE_SFIXED32,
]
if self.field.type in fixed64_types:
return "Fixed64"
if self.field.type in fixed32_types:
return "Fixed32"
return "Varint"
def is_grpc_slices(self) -> bool:
return (
self.field.type == FieldDescriptorProto.TYPE_BYTES
and self.field.options.Extensions[extensions_pb2.grpc_slices]
)
def is_blob(self) -> bool:
return (
self.field.type == FieldDescriptorProto.TYPE_BYTES
and self.field.options.ctype == FieldOptions.CORD
)
def is_lazy_bytes(self) -> bool:
return (
self.field.type == FieldDescriptorProto.TYPE_BYTES
and self.field.options.Extensions[extensions_pb2.zero_copy]
)
def is_boxed(self) -> bool:
return (
self.field.type == FieldDescriptorProto.TYPE_MESSAGE
and self.field.options.Extensions[extensions_pb2.box_it]
)
def has_custom_type(self) -> bool:
return self.field.options.HasExtension(extensions_pb2.type)
def custom_type(self) -> Text:
return self.field.options.Extensions[extensions_pb2.type]
def is_nullable(self) -> bool:
if self.field.type in PRIMITIVE_TYPES and self.is_proto3:
# Primitive types in proto3 are never nullable on the wire - as
# they cannot actually be represented on the wire as null
# rather they are represented as 0-value ("" or 0)
return False
if self.field.options.HasExtension(gogo_pb2.nullable):
return self.field.options.Extensions[gogo_pb2.nullable]
return (
not self.is_proto3 or self.field.type == FieldDescriptorProto.TYPE_MESSAGE
)
def is_empty_oneof_field(self) -> bool:
assert self.oneof
return self.field.type_name == ".google.protobuf.Empty"
def can_be_packed(self) -> bool:
# Return true if incoming messages could be packed on the wire
return self.field.label == FieldDescriptorProto.LABEL_REPEATED and self.wire_format() in (
"Varint",
"Fixed64",
"Fixed32",
)
def should_serialize_packed(self) -> bool:
return self.can_be_packed() and (self.field.options.packed or self.is_proto3)
def is_repeated(self) -> bool:
return self.field.label == FieldDescriptorProto.LABEL_REPEATED
def set_method(self) -> Tuple[Text, Text]:
assert not self.is_repeated()
if self.field.type == FieldDescriptorProto.TYPE_FLOAT:
return "f32", "v"
elif self.field.type == FieldDescriptorProto.TYPE_DOUBLE:
return "f64", "v"
elif self.field.type == FieldDescriptorProto.TYPE_INT32:
return "i32", "v"
elif self.field.type == FieldDescriptorProto.TYPE_INT64:
return "i64", "v"
elif self.field.type == FieldDescriptorProto.TYPE_UINT32:
return "u32", "v"
elif self.field.type == FieldDescriptorProto.TYPE_UINT64:
return "u64", "v"
elif self.field.type == FieldDescriptorProto.TYPE_SINT32:
return "i32", "::pb_jelly::Signed32(v)"
elif self.field.type == FieldDescriptorProto.TYPE_SINT64:
return "i64", "::pb_jelly::Signed64(v)"
elif self.field.type == FieldDescriptorProto.TYPE_FIXED64:
return "u64", "::pb_jelly::Fixed64(v)"
elif self.field.type == FieldDescriptorProto.TYPE_SFIXED64:
return "i64", "::pb_jelly::Sfixed64(v)"
elif self.field.type == FieldDescriptorProto.TYPE_FIXED32:
return "u32", "::pb_jelly::Fixed32(v)"
elif self.field.type == FieldDescriptorProto.TYPE_SFIXED32:
return "i32", "::pb_jelly::Sfixed32(v)"
elif self.field.type == FieldDescriptorProto.TYPE_BOOL:
return "bool", "v"
elif self.field.type == FieldDescriptorProto.TYPE_STRING:
return "::std::string::String", "v"
elif self.field.type == FieldDescriptorProto.TYPE_BYTES:
if self.is_blob():
return BLOB_TYPE, "v"
elif self.is_grpc_slices():
return VEC_SLICE_TYPE, "v"
elif self.is_lazy_bytes():
return LAZY_BYTES_TYPE, "v"
else:
return "::std::vec::Vec<u8>", "v"
elif self.field.type == FieldDescriptorProto.TYPE_ENUM:
return self.rust_type(), "v"
elif self.field.type == FieldDescriptorProto.TYPE_MESSAGE:
if self.is_boxed():
return "Box<%s>" % self.rust_type(), "v"
else:
return self.rust_type(), "v"
raise AssertionError("Unexpected field type")
def take_method(self) -> Tuple[Optional[Text], Optional[Text]]:
assert not self.is_repeated()
has_take_method = [
FieldDescriptorProto.TYPE_STRING,
FieldDescriptorProto.TYPE_BYTES,
FieldDescriptorProto.TYPE_MESSAGE,
]
if not self.field.type in has_take_method:
return None, None
expr = "self.%s.take().unwrap_or_default()" % self.field.name
if self.field.type == FieldDescriptorProto.TYPE_STRING:
return "::std::string::String", expr
elif self.field.type == FieldDescriptorProto.TYPE_BYTES:
if self.is_blob():
return BLOB_TYPE, expr
elif self.is_grpc_slices():
return VEC_SLICE_TYPE, expr
elif self.is_lazy_bytes():
return LAZY_BYTES_TYPE, expr
else:
return "::std::vec::Vec<u8>", expr
elif self.field.type == FieldDescriptorProto.TYPE_ENUM:
return self.rust_type(), expr
elif self.field.type == FieldDescriptorProto.TYPE_MESSAGE:
if self.is_boxed():
return "Box<%s>" % self.rust_type(), expr
else:
return self.rust_type(), expr
raise AssertionError("Unexpected field type")
def get_method(self) -> Tuple[Text, Text]:
assert not self.is_repeated()
name = self.field.name
if self.field.type == FieldDescriptorProto.TYPE_FLOAT:
return "f32", "self.%s.unwrap_or(0.)" % name
elif self.field.type == FieldDescriptorProto.TYPE_DOUBLE:
return "f64", "self.%s.unwrap_or(0.)" % name
elif self.field.type == FieldDescriptorProto.TYPE_INT32:
return "i32", "self.%s.unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_INT64:
return "i64", "self.%s.unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_UINT32:
return "u32", "self.%s.unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_UINT64:
return "u64", "self.%s.unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_SINT32:
return "i32", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_SINT64:
return "i64", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_FIXED64:
return "u64", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_SFIXED64:
return "i64", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_FIXED32:
return "u32", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_SFIXED32:
return "i32", "self.%s.map(|v| v.0).unwrap_or(0)" % name
elif self.field.type == FieldDescriptorProto.TYPE_BOOL:
return "bool", "self.%s.unwrap_or(false)" % name
elif self.field.type == FieldDescriptorProto.TYPE_STRING:
return (
"&str",
'self.%s.as_ref().map(|ref s| s.as_str()).unwrap_or("")' % name,
)
elif self.field.type == FieldDescriptorProto.TYPE_BYTES:
assert not (
self.is_blob() or self.is_grpc_slices() or self.is_lazy_bytes()
), "Can't generate get method for lazy field"
return "&[u8]", "self.%s.as_ref().map(|v| &**v).unwrap_or(&[])" % name
elif self.field.type == FieldDescriptorProto.TYPE_ENUM:
return self.rust_type(), "self.%s.unwrap_or_default()" % name
elif self.field.type == FieldDescriptorProto.TYPE_MESSAGE:
deref = (
"" if not self.is_boxed() else ".map(|v| ::std::ops::Deref::deref(v))"
)
return (
"&" + self.rust_type(),
"self.%s.as_ref()%s.unwrap_or(&%s_default)"
% (name, deref, self.rust_type()),
)
raise AssertionError("Unexpected field type")
def rust_type(self) -> Text:
typ = self.field.type
if self.has_custom_type():
return self.custom_type()
if self.is_blob():
return BLOB_TYPE
if self.is_grpc_slices():
return VEC_SLICE_TYPE
if self.is_lazy_bytes():
return LAZY_BYTES_TYPE
if typ in PRIMITIVE_TYPES:
return PRIMITIVE_TYPES[typ][0]
if (
typ == FieldDescriptorProto.TYPE_MESSAGE
or typ == FieldDescriptorProto.TYPE_ENUM
):
if self.field.type_name[0] != ".":
raise RuntimeError("We only support fully qualified type names")
proto_type = self.ctx.find(self.field.type_name)
crate, mod_parts = self.ctx.crate_from_proto_filename(self.proto_file.name)
return proto_type.rust_name(crate, mod_parts)
raise RuntimeError(
"Unsupported type: {!r}".format(FieldDescriptorProto.Type.Name(typ))
)
def __str__(self) -> str:
rust_type = self.rust_type()
if self.is_repeated():
return "::std::vec::Vec<%s>" % rust_type # type: ignore[return-value]
elif self.is_nullable() and self.is_boxed():
return "::std::option::Option<::std::boxed::Box<%s>>" % str(rust_type)
elif self.is_boxed():
return "::std::boxed::Box<%s>" % rust_type # type: ignore[return-value]
elif self.is_nullable():
return "::std::option::Option<%s>" % rust_type # type: ignore[return-value]
else:
return str(rust_type)
def oneof_field_match(self, var: Text) -> Text:
if self.is_empty_oneof_field():
return camelcase(self.field.name)
else:
return "%s(%s)" % (camelcase(self.field.name), var)
def oneof_val(self, msg_name: Text, var: Text) -> Text:
assert self.oneof
oneofv = "%s::%s" % (
oneof_msg_name(msg_name, self.oneof),
self.oneof_field_match(var),
)
if oneof_nullable(self.oneof):
oneofv = "Some(%s)" % oneofv
return oneofv
def oneof_msg_name(parent_msg_name: Text, oneof: OneofDescriptorProto) -> Text:
return "%s_%s" % (parent_msg_name, camelcase(oneof.name))
def oneof_nullable(oneof: OneofDescriptorProto) -> bool:
return (
not oneof.options.HasExtension(extensions_pb2.nullable)
or oneof.options.Extensions[extensions_pb2.nullable]
)
def enum_err_if_default_or_unknown(enum: EnumDescriptorProto) -> bool:
return (
enum.options.HasExtension(extensions_pb2.err_if_default_or_unknown)
and enum.options.Extensions[extensions_pb2.err_if_default_or_unknown]
)
@contextmanager
def block(ctx: 'CodeWriter', header: Text) -> Iterator[None]:
ctx.write("%s {" % header)
ctx.indentation += 1
yield
ctx.indentation -= 1
ctx.write("}")
@contextmanager
def field_iter(ctx: 'CodeWriter', var: Text, msg_name: Text, msg_type: DescriptorProto, field: FieldDescriptorProto) -> Iterator[None]:
typ = ctx.rust_type(msg_type, field)
if typ.oneof:
# For oneofs, we always emit, even if the primitive field is set to a 0 value
# This is so we can distinguish which field of oneof is set.
with block(
ctx,
"if let %s = self.%s"
% (typ.oneof_val(msg_name, "ref " + var), typ.oneof.name),
):
if typ.is_empty_oneof_field():
ctx.write(
"let %s: &%s = &::std::default::Default::default();"
% (var, typ.rust_type())
)
yield
elif (
field.type == FieldDescriptorProto.TYPE_MESSAGE
and not typ.is_nullable()
and not typ.is_repeated()
):
# Always emit messages explicitly marked as non-nullable
with block(ctx, ""):
ctx.write("let %s = &self.%s;" % (var, field.name))
yield
elif (
field.type == FieldDescriptorProto.TYPE_ENUM
and not typ.is_repeated()
and enum_err_if_default_or_unknown(ctx.ctx.find(field.type_name).typ)
):
# The default value (as considered by proto) doesn't appear in the generated enum and
# doesn't map to .default(). All of the values that actually get generated need to get
# encoded.
ctx.write("let %s = &self.%s;" % (var, field.name))
yield
elif not typ.is_nullable() and not typ.is_repeated():
# For proto3, we remove the Option for primitive fields.
# We only run internal code if the primitive field is non-default for proto3
# Rather than looping, we set the variable once and run the inner code once
with block(
ctx,
"if self.%s != <%s as ::std::default::Default>::default()"
% (field.name, typ),
):
if typ.is_boxed():
ctx.write("let %s = &*self.%s;" % (var, field.name))
else:
ctx.write("let %s = &self.%s;" % (var, field.name))
yield
else:
# This iterates through Vec and the Option<> type for optional fieldds
with block(ctx, "for %s in &self.%s" % (var, field.name)):
if typ.is_boxed():
ctx.write("let %s = &**%s;" % (var, var))
yield
class CodeWriter(object):
def __init__(self, ctx: 'Context', proto_file: FileDescriptorProto, crate: Text, mod_parts: List[Text]) -> None:
self.ctx = ctx
self.proto_file = proto_file
self.crate = crate
self.mod_parts = mod_parts
self.indentation = 0
self.content = StringIO()
self.is_proto3 = proto_file and proto_file.syntax == "proto3"
if proto_file and proto_file.options.Extensions[extensions_pb2.serde_derive]:
self.derive_serde = True
else:
self.derive_serde = False
# See https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto#L727
# for context on this beast
if proto_file is not None:
self.source_code_info_by_scl = {
tuple(location.path): location
for location in proto_file.source_code_info.location
}
def write(self, s: Text) -> None:
if s == "":
self.content.write("\n")
return
for _ in range(self.indentation):
self.content.write(" ")
self.content.write(s)
self.content.write("\n")
def write_line_broken_text_with_prefix(self, text_block: Text, prefix: Text) -> None:
if not text_block:
return
for l in text_block.rstrip().split("\n"):
if l:
self.write(u"{}{}".format(prefix, l))
else:
self.write("")
def write_comments(self, sci_loc: Optional[SourceCodeInfo.Location]) -> None:
if sci_loc is None:
return
for leading_detached_comment in sci_loc.leading_detached_comments:
self.write_line_broken_text_with_prefix(leading_detached_comment, "//")
self.write("")
if sci_loc.leading_comments is not None:
self.write_line_broken_text_with_prefix(sci_loc.leading_comments, "///")
# Trailing comments also go in the header - to make sure it gets into the docstring
if sci_loc.trailing_comments is not None:
self.write_line_broken_text_with_prefix(sci_loc.trailing_comments, "///")
def rust_type(self, msg_type: DescriptorProto, field: FieldDescriptorProto) -> RustType:
return RustType(self.ctx, self.proto_file, msg_type, field)
def gen_closed_enum(self, name: Text, enum_variants: List[Tuple[int, EnumValueDescriptorProto]], scl: SourceCodeLocation) -> None:
# Generate a closed enum
self.write_comments(self.source_code_info_by_scl.get(tuple(scl)))
if self.derive_serde:
self.write(
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Deserialize, Serialize)]"
)
else:
self.write(
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]"
)
self.write("#[repr(i32)]")
with block(self, "pub enum " + name):
for idx, value in enum_variants:
vfn = EnumDescriptorProto.VALUE_FIELD_NUMBER # type: ignore
self.write_comments(
self.source_code_info_by_scl.get(tuple(scl + [vfn, idx]))
)
self.write("%s = %s," % (value.name, value.number))
with block(self, "impl " + name):
self.write(
"pub const KNOWN_VARIANTS: [%s; %s] = [%s];"
% (
name,
len(enum_variants),
", ".join(
"%s::%s" % (name, value.name) for _, value in enum_variants
),
)
)
with block(self, "impl ::std::default::Default for " + name):
with block(self, "fn default() -> Self"):
# It's not actually clear what to do in this case. We take the first-defined
# value that isn't 0-valued.
for _, value in enum_variants:
self.write("%s::%s" % (name, value.name))
break
with block(self, "impl From<%s> for i32" % name):
with block(self, "fn from(v: %s) -> i32" % name):
with block(self, "match v"):
for _, value in enum_variants:
self.write("%s::%s => %s," % (name, value.name, value.number))
with block(self, "impl ::std::convert::TryFrom<i32> for %s" % name):
self.write("type Error = i32;")
with block(self, "fn try_from(v: i32) -> ::std::result::Result<Self, i32>"):
with block(self, "match v"):
for _, value in enum_variants:
self.write(
"%s => Ok(%s::%s)," % (value.number, name, value.name)
)
self.write("_ => Err(v),")
with block(self, "impl ::pb_jelly::ProtoEnum for " + name):
pass
with block(self, "impl ::pb_jelly::ClosedProtoEnum for " + name):
with block(self, "fn name(self) -> &'static str"):
with block(self, "match self"):
for _, value in enum_variants:
self.write('%s::%s => "%s",' % (name, value.name, value.name))
def gen_open_enum(self, name: Text, enum_variants: List[Tuple[int, EnumValueDescriptorProto]], scl: SourceCodeLocation) -> None:
closed_name = name + "_Closed"
# Generate an open enum
self.write_comments(self.source_code_info_by_scl.get(tuple(scl)))
if self.derive_serde:
self.write(
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]"
)
else:
self.write("#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]")
self.write("#[repr(transparent)]")
self.write("pub struct %s(i32);" % name)
with block(self, "impl " + name):
for idx, value in enum_variants:
vfn = EnumDescriptorProto.VALUE_FIELD_NUMBER # type: ignore
self.write_comments(
self.source_code_info_by_scl.get(tuple(scl + [vfn, idx]))
)
self.write(
"pub const %s: %s = %s(%s);"
% (value.name, name, name, value.number)
)
self.write(
"pub const KNOWN_VARIANTS: [%s; %s] = [%s];"
% (
name,
len(enum_variants),
", ".join(
"%s::%s" % (name, value.name) for _, value in enum_variants
),
)
)
with block(self, "pub const fn value(self) -> i32"):
self.write("self.0")
with block(
self,
"pub fn into_known(self) -> ::std::option::Option<%s>" % closed_name,
):
with block(self, "match self"):
for _, value in enum_variants:
self.write(
"%s::%s => Some(%s::%s),"
% (name, value.name, closed_name, value.name)
)
self.write("_ => None,")
with block(self, "impl ::std::default::Default for " + name):
with block(self, "fn default() -> Self"):
# Under proto2, the default value is the first defined.
# Under proto3, the default value is the 0-valued variant, but it's required to
# be defined first.
self.write("%s::%s" % (name, enum_variants[0][1].name))
with block(self, "impl From<%s> for i32" % name):
with block(self, "fn from(v: %s) -> i32" % name):
self.write("v.0")
with block(self, "impl From<i32> for %s" % name):
with block(self, "fn from(v: i32) -> %s" % name):
self.write("%s(v)" % name)
with block(self, "impl From<%s> for %s" % (closed_name, name)):
with block(self, "fn from(v: %s) -> %s" % (closed_name, name)):
self.write("%s(v as i32)" % name)
with block(self, "impl ::pb_jelly::ProtoEnum for " + name):
pass
with block(self, "impl ::pb_jelly::OpenProtoEnum for " + name):
with block(self, "fn name(self) -> ::std::option::Option<&'static str>"):
with block(self, "match self"):
for _, value in enum_variants:
self.write(
'%s::%s => Some("%s"),' % (name, value.name, value.name)
)
self.write("_ => None,")
with block(self, "fn is_known(self) -> bool"):
with block(self, "match self"):
for _, value in enum_variants:
self.write("%s::%s => true," % (name, value.name))
self.write("_ => false,")
with block(self, "impl ::std::fmt::Debug for " + name):
with block(
self,
"fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result",
):
self.write("use ::pb_jelly::OpenProtoEnum;")
with block(self, "match self.name()"):
self.write('Some(s) => write!(f, "{}", s),')
self.write('None => write!(f, "Unknown({})", self.0),')
self.gen_closed_enum(closed_name, enum_variants, scl)
def gen_enum(self, path: List[Text], enum_type: EnumDescriptorProto, scl: SourceCodeLocation) -> None:
assert self.indentation == 0
name = "_".join(path + [enum_type.name])
if enum_err_if_default_or_unknown(enum_type):
self.gen_closed_enum(
name, [x for x in enumerate(enum_type.value) if x[1].number != 0], scl
)
else:
self.gen_open_enum(name, list(enumerate(enum_type.value)), scl)
def gen_msg(self, path: List[Text], msg_type: DescriptorProto, scl: SourceCodeLocation) -> None:
assert self.indentation == 0
name = "_".join(path + [msg_type.name])
# Adjust some field names
for field in msg_type.field:
if field.name in RESERVED_KEYWORDS:
field.name = field.name + "_"
for oneof in msg_type.oneof_decl:
if oneof.name in RESERVED_KEYWORDS:
oneof.name = oneof.name + "_"
oneof_fields: DefaultDict[Text, List[FieldDescriptorProto]] = defaultdict(
list
)
derives = ["Clone", "Debug", "PartialEq"]
if self.derive_serde:
derives.extend(["Deserialize", "Serialize"])
fq_msg = (self.proto_file.name, name)
if self.ctx.impls_by_msg[fq_msg].Eq:
derives.extend(["Eq", "PartialOrd", "Ord", "Hash"])
if self.ctx.impls_by_msg[fq_msg].Copy:
derives.append("Copy")
self.write_comments(self.source_code_info_by_scl.get(tuple(scl)))
self.write("#[derive(%s)]" % ", ".join(sorted(derives)))
with block(self, "pub struct " + name):
for idx, field in enumerate(msg_type.field):
ffn = DescriptorProto.FIELD_FIELD_NUMBER # type: ignore
self.write_comments(
self.source_code_info_by_scl.get(tuple(scl + [ffn, idx]))
)
typ = self.rust_type(msg_type, field)
if typ.oneof:
oneof_fields[typ.oneof.name].append(field)
else:
self.write("pub %s: %s," % (field.name, typ))
for oneof in msg_type.oneof_decl:
if oneof_nullable(oneof):
self.write(
"pub %s: ::std::option::Option<%s>,"
% (oneof.name, oneof_msg_name(name, oneof))
)
else:
self.write(
"pub %s: %s," % (oneof.name, oneof_msg_name(name, oneof))
)
if msg_type.options.Extensions[extensions_pb2.preserve_unrecognized]:
self.write("pub _unrecognized: Vec<u8>,")
# Generate any oneof enum structs
for oneof in msg_type.oneof_decl:
self.write("#[derive(%s)]" % ", ".join(sorted(derives)))
with block(self, "pub enum " + oneof_msg_name(name, oneof)):
for oneof_field in oneof_fields[oneof.name]:
typ = self.rust_type(msg_type, oneof_field)
self.write("%s," % typ.oneof_field_match(typ.rust_type()))
if not self.is_proto3:
with block(self, "impl " + name):
for field in msg_type.field:
typ = self.rust_type(msg_type, field)
if typ.oneof:
continue
if typ.is_repeated():
with block(
self,
"pub fn set_%s(&mut self, v: ::std::vec::Vec<%s>)"
% (field.name, typ.rust_type()),
):
self.write("self.%s = v;" % field.name)
with block(
self,
"pub fn take_%s(&mut self) -> ::std::vec::Vec<%s>"
% (field.name, typ.rust_type()),
):
self.write(
"::std::mem::replace(&mut self.%s, ::std::vec::Vec::new())"
% field.name
)
with block(
self,
"pub fn get_%s(&self) -> &[%s]"
% (field.name, typ.rust_type()),
):
self.write("&self.%s" % field.name)
with block(
self,
"pub fn mut_%s(&mut self) -> &mut ::std::vec::Vec<%s>"
% (field.name, typ.rust_type()),
):
self.write("&mut self." + field.name)
elif typ.is_nullable():
with block(self, "pub fn has_%s(&self) -> bool" % field.name):
self.write("self.%s.is_some()" % field.name)
input_type, input_expr = typ.set_method()
with block(
self,
"pub fn set_%s(&mut self, v: %s)"
% (field.name, input_type),
):
self.write("self.%s = Some(%s);" % (field.name, input_expr))
return_type, return_expr = typ.take_method()
if return_type is not None and return_expr is not None:
with block(
self,
"pub fn take_%s(&mut self) -> %s"
% (field.name, return_type),
):
self.write(return_expr)
if not (typ.is_blob() or typ.is_grpc_slices() or typ.is_lazy_bytes()):
# It's hard to make this make sense, so let's not generate `get` method for lazy things.
return_type, return_expr = typ.get_method()
with block(
self,
"pub fn get_%s(&self) -> %s"
% (field.name, return_type),
):
self.write(return_expr)
with block(self, "impl ::std::default::Default for " + name):
with block(self, "fn default() -> Self"):
with block(self, name):
for field in msg_type.field:
typ = self.rust_type(msg_type, field)
if not typ.oneof:
self.write("%s: %s," % (field.name, typ.default(name)))
for oneof in msg_type.oneof_decl:
oneof_field = oneof_fields[oneof.name][0]
typ = self.rust_type(msg_type, oneof_field)
self.write("%s: %s," % (oneof.name, typ.default(name)))
if msg_type.options.Extensions[
extensions_pb2.preserve_unrecognized
]:
self.write("_unrecognized: Vec::new(),")
with block(self, "lazy_static!"):
self.write(
"pub static ref %s_default: %s = %s::default();" % (name, name, name)
)
with block(self, "impl ::pb_jelly::Message for " + name):
with block(self, "fn compute_size(&self) -> usize "):
if (
len(msg_type.field) > 0
or msg_type.options.Extensions[extensions_pb2.preserve_unrecognized]
):
self.write("let mut size = 0;")
for field in msg_type.field:
typ = self.rust_type(msg_type, field)
self.write("let mut %s_size = 0;" % field.name)
with field_iter(self, "val", name, msg_type, field):
self.write("let l = ::pb_jelly::Message::compute_size(val);")
if not typ.should_serialize_packed():
self.write(
"%s_size += ::pb_jelly::wire_format::serialized_length(%s);"
% (field.name, field.number)
)
if typ.is_length_delimited():
self.write(
"%s_size += ::pb_jelly::varint::serialized_length(l as u64);"
% field.name
)
self.write("%s_size += l;" % field.name)
if typ.should_serialize_packed():
with block(self, "if !self.%s.is_empty()" % field.name):
self.write(
"size += ::pb_jelly::wire_format::serialized_length(%s);"
% field.number