blob: 4925d2c7b26858c4bbbcacfbb904c31b675ad43a [file] [log] [blame]
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -07001use protobuf::descriptor::*;
2use protobuf::rt;
3use protobuf::rust;
4use protobuf::text_format;
5use protobuf::wire_format;
6
7use super::code_writer::CodeWriter;
8use super::enums::*;
9use super::rust_types_values::*;
10
11use super::customize::customize_from_rustproto_for_field;
12use super::customize::Customize;
13use oneof::OneofField;
14
15use float;
16use inside::protobuf_crate_path;
Haibo Huang72fec012020-07-10 20:24:04 -070017use message::RustTypeMessage;
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -070018use protobuf_name::ProtobufAbsolutePath;
19use rust_name::RustIdent;
Haibo Huang72fec012020-07-10 20:24:04 -070020use rust_name::RustIdentWithPath;
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -070021use scope::FieldWithContext;
22use scope::MessageOrEnumWithScope;
23use scope::RootScope;
24use scope::WithScope;
25use std::marker;
26use syntax::Syntax;
27
28fn type_is_copy(field_type: FieldDescriptorProto_Type) -> bool {
29 match field_type {
30 FieldDescriptorProto_Type::TYPE_MESSAGE
31 | FieldDescriptorProto_Type::TYPE_STRING
32 | FieldDescriptorProto_Type::TYPE_BYTES => false,
33 _ => true,
34 }
35}
36
37trait FieldDescriptorProtoTypeExt {
38 fn read(&self, is: &str, primitive_type_variant: PrimitiveTypeVariant) -> String;
39 fn is_s_varint(&self) -> bool;
40}
41
42impl FieldDescriptorProtoTypeExt for FieldDescriptorProto_Type {
43 fn read(&self, is: &str, primitive_type_variant: PrimitiveTypeVariant) -> String {
44 match primitive_type_variant {
45 PrimitiveTypeVariant::Default => format!("{}.read_{}()", is, protobuf_name(*self)),
46 PrimitiveTypeVariant::Carllerche => {
47 let protobuf_name = match self {
48 &FieldDescriptorProto_Type::TYPE_STRING => "chars",
49 _ => protobuf_name(*self),
50 };
51 format!("{}.read_carllerche_{}()", is, protobuf_name)
52 }
53 }
54 }
55
56 /// True if self is signed integer with zigzag encoding
57 fn is_s_varint(&self) -> bool {
58 match *self {
59 FieldDescriptorProto_Type::TYPE_SINT32 | FieldDescriptorProto_Type::TYPE_SINT64 => true,
60 _ => false,
61 }
62 }
63}
64
65fn field_type_wire_type(field_type: FieldDescriptorProto_Type) -> wire_format::WireType {
66 use protobuf::stream::wire_format::*;
67 match field_type {
68 FieldDescriptorProto_Type::TYPE_INT32 => WireTypeVarint,
69 FieldDescriptorProto_Type::TYPE_INT64 => WireTypeVarint,
70 FieldDescriptorProto_Type::TYPE_UINT32 => WireTypeVarint,
71 FieldDescriptorProto_Type::TYPE_UINT64 => WireTypeVarint,
72 FieldDescriptorProto_Type::TYPE_SINT32 => WireTypeVarint,
73 FieldDescriptorProto_Type::TYPE_SINT64 => WireTypeVarint,
74 FieldDescriptorProto_Type::TYPE_BOOL => WireTypeVarint,
75 FieldDescriptorProto_Type::TYPE_ENUM => WireTypeVarint,
76 FieldDescriptorProto_Type::TYPE_FIXED32 => WireTypeFixed32,
77 FieldDescriptorProto_Type::TYPE_FIXED64 => WireTypeFixed64,
78 FieldDescriptorProto_Type::TYPE_SFIXED32 => WireTypeFixed32,
79 FieldDescriptorProto_Type::TYPE_SFIXED64 => WireTypeFixed64,
80 FieldDescriptorProto_Type::TYPE_FLOAT => WireTypeFixed32,
81 FieldDescriptorProto_Type::TYPE_DOUBLE => WireTypeFixed64,
82 FieldDescriptorProto_Type::TYPE_STRING => WireTypeLengthDelimited,
83 FieldDescriptorProto_Type::TYPE_BYTES => WireTypeLengthDelimited,
84 FieldDescriptorProto_Type::TYPE_MESSAGE => WireTypeLengthDelimited,
85 FieldDescriptorProto_Type::TYPE_GROUP => WireTypeLengthDelimited, // not true
86 }
87}
88
89fn type_protobuf_name(field_type: FieldDescriptorProto_Type) -> &'static str {
90 match field_type {
91 FieldDescriptorProto_Type::TYPE_INT32 => "int32",
92 FieldDescriptorProto_Type::TYPE_INT64 => "int64",
93 FieldDescriptorProto_Type::TYPE_UINT32 => "uint32",
94 FieldDescriptorProto_Type::TYPE_UINT64 => "uint64",
95 FieldDescriptorProto_Type::TYPE_SINT32 => "sint32",
96 FieldDescriptorProto_Type::TYPE_SINT64 => "sint64",
97 FieldDescriptorProto_Type::TYPE_BOOL => "bool",
98 FieldDescriptorProto_Type::TYPE_FIXED32 => "fixed32",
99 FieldDescriptorProto_Type::TYPE_FIXED64 => "fixed64",
100 FieldDescriptorProto_Type::TYPE_SFIXED32 => "sfixed32",
101 FieldDescriptorProto_Type::TYPE_SFIXED64 => "sfixed64",
102 FieldDescriptorProto_Type::TYPE_FLOAT => "float",
103 FieldDescriptorProto_Type::TYPE_DOUBLE => "double",
104 FieldDescriptorProto_Type::TYPE_STRING => "string",
105 FieldDescriptorProto_Type::TYPE_BYTES => "bytes",
106 FieldDescriptorProto_Type::TYPE_ENUM
107 | FieldDescriptorProto_Type::TYPE_MESSAGE
108 | FieldDescriptorProto_Type::TYPE_GROUP => panic!(),
109 }
110}
111
112fn field_type_protobuf_name<'a>(field: &'a FieldDescriptorProto) -> &'a str {
113 if field.has_type_name() {
114 field.get_type_name()
115 } else {
116 type_protobuf_name(field.get_field_type())
117 }
118}
119
120// size of value for type, None if variable
121fn field_type_size(field_type: FieldDescriptorProto_Type) -> Option<u32> {
122 match field_type {
123 FieldDescriptorProto_Type::TYPE_BOOL => Some(1),
124 t if field_type_wire_type(t) == wire_format::WireTypeFixed32 => Some(4),
125 t if field_type_wire_type(t) == wire_format::WireTypeFixed64 => Some(8),
126 _ => None,
127 }
128}
129
130#[derive(Clone, PartialEq, Eq)]
131pub enum SingularFieldFlag {
132 // proto2 or proto3 message
133 WithFlag { required: bool },
134 // proto3
135 WithoutFlag,
136}
137
138impl SingularFieldFlag {
139 pub fn is_required(&self) -> bool {
140 match *self {
141 SingularFieldFlag::WithFlag { required, .. } => required,
142 SingularFieldFlag::WithoutFlag => false,
143 }
144 }
145}
146
147#[derive(Clone)]
148pub(crate) struct SingularField<'a> {
149 pub flag: SingularFieldFlag,
150 pub elem: FieldElem<'a>,
151}
152
153impl<'a> SingularField<'a> {
154 fn rust_storage_type(&self) -> RustType {
155 match self.flag {
156 SingularFieldFlag::WithFlag { .. } => match self.elem.proto_type() {
157 FieldDescriptorProto_Type::TYPE_MESSAGE => {
158 RustType::SingularPtrField(Box::new(self.elem.rust_storage_type()))
159 }
160 FieldDescriptorProto_Type::TYPE_STRING | FieldDescriptorProto_Type::TYPE_BYTES
161 if self.elem.primitive_type_variant() == PrimitiveTypeVariant::Default =>
162 {
163 RustType::SingularField(Box::new(self.elem.rust_storage_type()))
164 }
165 _ => RustType::Option(Box::new(self.elem.rust_storage_type())),
166 },
167 SingularFieldFlag::WithoutFlag => self.elem.rust_storage_type(),
168 }
169 }
170}
171
172#[derive(Clone)]
173pub(crate) struct RepeatedField<'a> {
174 pub elem: FieldElem<'a>,
175 pub packed: bool,
176}
177
178impl<'a> RepeatedField<'a> {
179 fn rust_type(&self) -> RustType {
180 if !self.elem.is_copy()
181 && self.elem.primitive_type_variant() != PrimitiveTypeVariant::Carllerche
182 {
183 RustType::RepeatedField(Box::new(self.elem.rust_storage_type()))
184 } else {
185 RustType::Vec(Box::new(self.elem.rust_storage_type()))
186 }
187 }
188}
189
190#[derive(Clone)]
191pub struct MapField<'a> {
192 name: String,
193 key: FieldElem<'a>,
194 value: FieldElem<'a>,
195}
196
197#[derive(Clone)]
198pub(crate) enum FieldKind<'a> {
199 // optional or required
200 Singular(SingularField<'a>),
201 // repeated except map
202 Repeated(RepeatedField<'a>),
203 // map
204 Map(MapField<'a>),
205 // part of oneof
206 Oneof(OneofField<'a>),
207}
208
209impl<'a> FieldKind<'a> {
210 fn elem(&self) -> &FieldElem {
211 match self {
212 &FieldKind::Singular(ref s) => &s.elem,
213 &FieldKind::Repeated(ref r) => &r.elem,
214 &FieldKind::Oneof(ref o) => &o.elem,
215 &FieldKind::Map(..) => {
216 panic!("no single elem type for map field");
217 }
218 }
219 }
220
221 fn primitive_type_variant(&self) -> PrimitiveTypeVariant {
222 self.elem().primitive_type_variant()
223 }
224}
225
226// Representation of map entry: key type and value type
227#[derive(Clone, Debug)]
228pub struct EntryKeyValue<'a>(FieldElem<'a>, FieldElem<'a>);
229
230#[derive(Clone, Debug)]
231pub(crate) enum FieldElem<'a> {
232 Primitive(FieldDescriptorProto_Type, PrimitiveTypeVariant),
233 // name, file name, entry
234 Message(
235 String,
236 String,
237 Option<Box<EntryKeyValue<'a>>>,
238 marker::PhantomData<&'a ()>,
239 ),
240 // name, file name, default value
241 Enum(String, String, RustIdent),
242 Group,
243}
244
245impl<'a> FieldElem<'a> {
246 fn proto_type(&self) -> FieldDescriptorProto_Type {
247 match *self {
248 FieldElem::Primitive(t, ..) => t,
249 FieldElem::Group => FieldDescriptorProto_Type::TYPE_GROUP,
250 FieldElem::Message(..) => FieldDescriptorProto_Type::TYPE_MESSAGE,
251 FieldElem::Enum(..) => FieldDescriptorProto_Type::TYPE_ENUM,
252 }
253 }
254
255 fn is_copy(&self) -> bool {
256 type_is_copy(self.proto_type())
257 }
258
259 pub fn rust_storage_type(&self) -> RustType {
260 match *self {
261 FieldElem::Primitive(t, PrimitiveTypeVariant::Default) => rust_name(t),
262 FieldElem::Primitive(
263 FieldDescriptorProto_Type::TYPE_STRING,
264 PrimitiveTypeVariant::Carllerche,
265 ) => RustType::Chars,
266 FieldElem::Primitive(
267 FieldDescriptorProto_Type::TYPE_BYTES,
268 PrimitiveTypeVariant::Carllerche,
269 ) => RustType::Bytes,
270 FieldElem::Primitive(.., PrimitiveTypeVariant::Carllerche) => unreachable!(),
271 FieldElem::Group => RustType::Group,
Haibo Huang72fec012020-07-10 20:24:04 -0700272 FieldElem::Message(ref name, ..) => {
273 RustType::Message(RustTypeMessage(RustIdentWithPath::new(name.clone())))
274 }
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -0700275 FieldElem::Enum(ref name, _, ref default_value) => {
276 RustType::Enum(name.clone(), default_value.clone())
277 }
278 }
279 }
280
281 fn protobuf_type_gen(&self) -> ProtobufTypeGen {
282 match *self {
283 FieldElem::Primitive(t, v) => ProtobufTypeGen::Primitive(t, v),
284 FieldElem::Message(ref name, ..) => ProtobufTypeGen::Message(name.clone()),
285 FieldElem::Enum(ref name, ..) => ProtobufTypeGen::Enum(name.clone()),
286 FieldElem::Group => unreachable!(),
287 }
288 }
289
290 /// implementation of ProtobufType trait
291 fn lib_protobuf_type(&self, customize: &Customize) -> String {
292 self.protobuf_type_gen().rust_type(customize)
293 }
294
295 fn primitive_type_variant(&self) -> PrimitiveTypeVariant {
296 match self {
297 &FieldElem::Primitive(_, v) => v,
298 _ => PrimitiveTypeVariant::Default,
299 }
300 }
301}
302
303fn field_elem<'a>(
304 field: &FieldWithContext,
305 root_scope: &'a RootScope<'a>,
306 parse_map: bool,
307 customize: &Customize,
308) -> (FieldElem<'a>, Option<EnumValueGen>) {
309 if field.field.get_field_type() == FieldDescriptorProto_Type::TYPE_GROUP {
310 (FieldElem::Group, None)
311 } else if field.field.has_type_name() {
312 let message_or_enum = root_scope
313 .find_message_or_enum(&ProtobufAbsolutePath::from(field.field.get_type_name()));
314 let file_name = message_or_enum
315 .get_scope()
316 .file_scope
317 .file_descriptor
318 .get_name()
319 .to_owned();
320 let rust_relative_name = type_name_to_rust_relative(
321 &ProtobufAbsolutePath::from(field.field.get_type_name()),
322 field.message.get_scope().file_scope.file_descriptor,
323 false,
324 root_scope,
325 );
326 match (field.field.get_field_type(), message_or_enum) {
327 (
328 FieldDescriptorProto_Type::TYPE_MESSAGE,
329 MessageOrEnumWithScope::Message(message_with_scope),
330 ) => {
331 let entry_key_value = if let (true, Some((key, value))) =
332 (parse_map, message_with_scope.map_entry())
333 {
334 Some(Box::new(EntryKeyValue(
335 field_elem(&key, root_scope, false, customize).0,
336 field_elem(&value, root_scope, false, customize).0,
337 )))
338 } else {
339 None
340 };
341 (
342 FieldElem::Message(
343 rust_relative_name,
344 file_name,
345 entry_key_value,
346 marker::PhantomData,
347 ),
348 None,
349 )
350 }
351 (
352 FieldDescriptorProto_Type::TYPE_ENUM,
353 MessageOrEnumWithScope::Enum(enum_with_scope),
354 ) => {
355 let e = EnumGen::new(
356 &enum_with_scope,
357 field.message.get_scope().get_file_descriptor(),
358 customize,
359 root_scope,
360 );
361 let ev = if field.field.has_default_value() {
362 e.value_by_name(field.field.get_default_value()).clone()
363 } else {
364 e.values_unique().into_iter().next().unwrap()
365 };
366 (
367 FieldElem::Enum(
368 rust_relative_name,
369 file_name,
370 RustIdent::from(enum_with_scope.values()[0].rust_name().to_owned()),
371 ),
372 Some(ev),
373 )
374 }
375 _ => panic!("unknown named type: {:?}", field.field.get_field_type()),
376 }
377 } else if field.field.has_field_type() {
378 let carllerche_for_bytes = customize.carllerche_bytes_for_bytes.unwrap_or(false);
379 let carllerche_for_string = customize.carllerche_bytes_for_string.unwrap_or(false);
380
381 let elem = match field.field.get_field_type() {
382 FieldDescriptorProto_Type::TYPE_STRING if carllerche_for_string => {
383 FieldElem::Primitive(
384 FieldDescriptorProto_Type::TYPE_STRING,
385 PrimitiveTypeVariant::Carllerche,
386 )
387 }
388 FieldDescriptorProto_Type::TYPE_BYTES if carllerche_for_bytes => FieldElem::Primitive(
389 FieldDescriptorProto_Type::TYPE_BYTES,
390 PrimitiveTypeVariant::Carllerche,
391 ),
392 t => FieldElem::Primitive(t, PrimitiveTypeVariant::Default),
393 };
394
395 (elem, None)
396 } else {
397 panic!(
398 "neither type_name, nor field_type specified for field: {}",
399 field.field.get_name()
400 );
401 }
402}
403
404pub enum AccessorStyle {
405 Lambda,
406 HasGet,
407}
408
409pub struct AccessorFn {
410 name: String,
411 type_params: Vec<String>,
412 pub style: AccessorStyle,
413}
414
415impl AccessorFn {
416 pub fn sig(&self) -> String {
417 let mut s = self.name.clone();
418 s.push_str("::<_");
419 for p in &self.type_params {
420 s.push_str(", ");
421 s.push_str(&p);
422 }
423 s.push_str(">");
424 s
425 }
426}
427
428#[derive(Clone)]
429pub(crate) struct FieldGen<'a> {
430 root_scope: &'a RootScope<'a>,
431 syntax: Syntax,
432 pub proto_field: FieldWithContext<'a>,
433 // field name in generated code
434 pub rust_name: RustIdent,
435 pub proto_type: FieldDescriptorProto_Type,
436 wire_type: wire_format::WireType,
437 enum_default_value: Option<EnumValueGen>,
438 pub kind: FieldKind<'a>,
439 pub expose_field: bool,
440 pub generate_accessors: bool,
441 pub(crate) customize: Customize,
442}
443
444impl<'a> FieldGen<'a> {
445 pub fn parse(
446 field: FieldWithContext<'a>,
447 root_scope: &'a RootScope<'a>,
448 customize: &Customize,
449 ) -> FieldGen<'a> {
450 let mut customize = customize.clone();
451 customize.update_with(&customize_from_rustproto_for_field(
452 &field.field.get_options(),
453 ));
454
455 let (elem, enum_default_value) = field_elem(&field, root_scope, true, &customize);
456
457 let generate_accessors = customize.generate_accessors.unwrap_or(true);
458
Haibo Huang72fec012020-07-10 20:24:04 -0700459 let syntax = field.message.scope.file_scope.syntax();
460
461 let field_may_have_custom_default_value = syntax == Syntax::PROTO2
462 && field.field.get_label() != FieldDescriptorProto_Label::LABEL_REPEATED
463 && field.field.get_field_type() != FieldDescriptorProto_Type::TYPE_MESSAGE;
464
465 let default_expose_field = !field_may_have_custom_default_value;
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -0700466
467 let expose_field = customize.expose_fields.unwrap_or(default_expose_field);
468
469 let kind = if field.field.get_label() == FieldDescriptorProto_Label::LABEL_REPEATED {
470 match (elem, true) {
471 // map field
472 (FieldElem::Message(name, _, Some(key_value), _), true) => {
473 FieldKind::Map(MapField {
474 name: name,
475 key: key_value.0.clone(),
476 value: key_value.1.clone(),
477 })
478 }
479 // regular repeated field
480 (elem, _) => FieldKind::Repeated(RepeatedField {
481 elem,
482 packed: field.field.get_options().get_packed(),
483 }),
484 }
485 } else if let Some(oneof) = field.oneof() {
486 FieldKind::Oneof(OneofField::parse(&oneof, &field, elem, root_scope))
487 } else {
488 let flag = if field.message.scope.file_scope.syntax() == Syntax::PROTO3
489 && field.field.get_field_type() != FieldDescriptorProto_Type::TYPE_MESSAGE
490 {
491 SingularFieldFlag::WithoutFlag
492 } else {
493 SingularFieldFlag::WithFlag {
494 required: field.field.get_label() == FieldDescriptorProto_Label::LABEL_REQUIRED,
495 }
496 };
497 FieldKind::Singular(SingularField { elem, flag })
498 };
499
500 FieldGen {
501 root_scope,
502 syntax: field.message.get_scope().file_scope.syntax(),
503 rust_name: field.rust_name(),
504 proto_type: field.field.get_field_type(),
505 wire_type: field_type_wire_type(field.field.get_field_type()),
506 enum_default_value,
507 proto_field: field.clone(),
508 kind,
509 expose_field,
510 generate_accessors,
511 customize,
512 }
513 }
514
515 fn tag_size(&self) -> u32 {
516 rt::tag_size(self.proto_field.number())
517 }
518
519 pub fn is_oneof(&self) -> bool {
520 match self.kind {
521 FieldKind::Oneof(..) => true,
522 _ => false,
523 }
524 }
525
526 pub fn oneof(&self) -> &OneofField {
527 match self.kind {
528 FieldKind::Oneof(ref oneof) => &oneof,
529 _ => panic!("not a oneof field: {}", self.reconstruct_def()),
530 }
531 }
532
533 fn is_singular(&self) -> bool {
534 match self.kind {
535 FieldKind::Singular(..) => true,
536 _ => false,
537 }
538 }
539
540 fn is_repeated_not_map(&self) -> bool {
541 match self.kind {
542 FieldKind::Repeated(..) => true,
543 _ => false,
544 }
545 }
546
547 fn is_repeated_or_map(&self) -> bool {
548 match self.kind {
549 FieldKind::Repeated(..) | FieldKind::Map(..) => true,
550 _ => false,
551 }
552 }
553
554 fn is_repeated_packed(&self) -> bool {
555 match self.kind {
556 FieldKind::Repeated(RepeatedField { packed: true, .. }) => true,
557 _ => false,
558 }
559 }
560
561 #[allow(dead_code)]
562 fn repeated(&self) -> &RepeatedField {
563 match self.kind {
564 FieldKind::Repeated(ref repeated) => &repeated,
565 _ => panic!("not a repeated field: {}", self.reconstruct_def()),
566 }
567 }
568
569 fn singular(&self) -> &SingularField {
570 match self.kind {
571 FieldKind::Singular(ref singular) => &singular,
572 _ => panic!("not a singular field: {}", self.reconstruct_def()),
573 }
574 }
575
576 fn map(&self) -> &MapField {
577 match self.kind {
578 FieldKind::Map(ref map) => &map,
579 _ => panic!("not a map field: {}", self.reconstruct_def()),
580 }
581 }
582
583 fn variant_path(&self) -> String {
584 // TODO: should reuse code from OneofVariantGen
585 format!(
586 "{}::{}",
587 self.oneof().oneof_type_name.to_code(&self.customize),
588 self.rust_name
589 )
590 }
591
592 // TODO: drop it
593 pub fn elem(&self) -> &FieldElem {
594 match self.kind {
595 FieldKind::Singular(SingularField { ref elem, .. }) => &elem,
596 FieldKind::Repeated(RepeatedField { ref elem, .. }) => &elem,
597 FieldKind::Oneof(OneofField { ref elem, .. }) => &elem,
598 FieldKind::Map(..) => unreachable!(),
599 }
600 }
601
602 // type of field in struct
603 pub fn full_storage_type(&self) -> RustType {
604 match self.kind {
605 FieldKind::Repeated(ref repeated) => repeated.rust_type(),
606 FieldKind::Map(MapField {
607 ref key, ref value, ..
608 }) => RustType::HashMap(
609 Box::new(key.rust_storage_type()),
610 Box::new(value.rust_storage_type()),
611 ),
612 FieldKind::Singular(ref singular) => singular.rust_storage_type(),
613 FieldKind::Oneof(..) => unreachable!(),
614 }
615 }
616
617 // type of `v` in `for v in field`
618 fn full_storage_iter_elem_type(&self) -> RustType {
619 if let FieldKind::Oneof(ref oneof) = self.kind {
620 oneof.elem.rust_storage_type()
621 } else {
622 self.full_storage_type().iter_elem_type()
623 }
624 }
625
626 // suffix `xxx` as in `os.write_xxx_no_tag(..)`
627 fn os_write_fn_suffix(&self) -> &str {
628 protobuf_name(self.proto_type)
629 }
630
631 // type of `v` in `os.write_xxx_no_tag(v)`
632 fn os_write_fn_param_type(&self) -> RustType {
633 match self.proto_type {
634 FieldDescriptorProto_Type::TYPE_STRING => RustType::Ref(Box::new(RustType::Str)),
635 FieldDescriptorProto_Type::TYPE_BYTES => {
636 RustType::Ref(Box::new(RustType::Slice(Box::new(RustType::Int(false, 8)))))
637 }
638 FieldDescriptorProto_Type::TYPE_ENUM => RustType::Int(true, 32),
639 t => rust_name(t),
640 }
641 }
642
643 // for field `foo`, type of param of `fn set_foo(..)`
644 fn set_xxx_param_type(&self) -> RustType {
645 match self.kind {
646 FieldKind::Singular(SingularField { ref elem, .. })
647 | FieldKind::Oneof(OneofField { ref elem, .. }) => elem.rust_storage_type(),
648 FieldKind::Repeated(..) | FieldKind::Map(..) => self.full_storage_type(),
649 }
650 }
651
652 // for field `foo`, return type if `fn take_foo(..)`
653 fn take_xxx_return_type(&self) -> RustType {
654 self.set_xxx_param_type()
655 }
656
657 // for field `foo`, return type of `fn mut_foo(..)`
658 fn mut_xxx_return_type(&self) -> RustType {
659 RustType::Ref(Box::new(match self.kind {
660 FieldKind::Singular(SingularField { ref elem, .. })
661 | FieldKind::Oneof(OneofField { ref elem, .. }) => elem.rust_storage_type(),
662 FieldKind::Repeated(..) | FieldKind::Map(..) => self.full_storage_type(),
663 }))
664 }
665
666 // for field `foo`, return type of `fn get_foo(..)`
667 fn get_xxx_return_type(&self) -> RustType {
668 match self.kind {
669 FieldKind::Singular(SingularField { ref elem, .. })
670 | FieldKind::Oneof(OneofField { ref elem, .. }) => match elem.is_copy() {
671 true => elem.rust_storage_type(),
672 false => elem.rust_storage_type().ref_type(),
673 },
674 FieldKind::Repeated(RepeatedField { ref elem, .. }) => RustType::Ref(Box::new(
675 RustType::Slice(Box::new(elem.rust_storage_type())),
676 )),
677 FieldKind::Map(..) => RustType::Ref(Box::new(self.full_storage_type())),
678 }
679 }
680
681 // fixed size type?
682 fn is_fixed(&self) -> bool {
683 field_type_size(self.proto_type).is_some()
684 }
685
686 // must use zigzag encoding?
687 fn is_zigzag(&self) -> bool {
688 match self.proto_type {
689 FieldDescriptorProto_Type::TYPE_SINT32 | FieldDescriptorProto_Type::TYPE_SINT64 => true,
690 _ => false,
691 }
692 }
693
694 // data is enum
695 fn is_enum(&self) -> bool {
696 match self.proto_type {
697 FieldDescriptorProto_Type::TYPE_ENUM => true,
698 _ => false,
699 }
700 }
701
702 // elem data is not stored in heap
703 pub fn elem_type_is_copy(&self) -> bool {
704 type_is_copy(self.proto_type)
705 }
706
707 fn defaut_value_from_proto_float(&self) -> String {
708 assert!(self.proto_field.field.has_default_value());
709
710 let type_name = match self.proto_type {
711 FieldDescriptorProto_Type::TYPE_FLOAT => "f32",
712 FieldDescriptorProto_Type::TYPE_DOUBLE => "f64",
713 _ => unreachable!(),
714 };
715 let proto_default = self.proto_field.field.get_default_value();
716
717 let f = float::parse_protobuf_float(proto_default)
718 .expect(&format!("failed to parse float: {:?}", proto_default));
719
720 if f.is_nan() {
721 format!("::std::{}::NAN", type_name)
722 } else if f.is_infinite() {
723 if f > 0.0 {
724 format!("::std::{}::INFINITY", type_name)
725 } else {
726 format!("::std::{}::NEG_INFINITY", type_name)
727 }
728 } else {
729 format!("{:?}{}", f, type_name)
730 }
731 }
732
733 fn default_value_from_proto(&self) -> Option<String> {
734 assert!(self.is_singular() || self.is_oneof());
735 if self.enum_default_value.is_some() {
736 Some(self.enum_default_value.as_ref().unwrap().rust_name_outer())
737 } else if self.proto_field.field.has_default_value() {
738 let proto_default = self.proto_field.field.get_default_value();
739 Some(match self.proto_type {
740 // For numeric types, contains the original text representation of the value
741 FieldDescriptorProto_Type::TYPE_DOUBLE | FieldDescriptorProto_Type::TYPE_FLOAT => {
742 self.defaut_value_from_proto_float()
743 }
744 FieldDescriptorProto_Type::TYPE_INT32
745 | FieldDescriptorProto_Type::TYPE_SINT32
746 | FieldDescriptorProto_Type::TYPE_SFIXED32 => format!("{}i32", proto_default),
747 FieldDescriptorProto_Type::TYPE_UINT32
748 | FieldDescriptorProto_Type::TYPE_FIXED32 => format!("{}u32", proto_default),
749 FieldDescriptorProto_Type::TYPE_INT64
750 | FieldDescriptorProto_Type::TYPE_SINT64
751 | FieldDescriptorProto_Type::TYPE_SFIXED64 => format!("{}i64", proto_default),
752 FieldDescriptorProto_Type::TYPE_UINT64
753 | FieldDescriptorProto_Type::TYPE_FIXED64 => format!("{}u64", proto_default),
754
755 // For booleans, "true" or "false"
756 FieldDescriptorProto_Type::TYPE_BOOL => format!("{}", proto_default),
757 // For strings, contains the default text contents (not escaped in any way)
758 FieldDescriptorProto_Type::TYPE_STRING => rust::quote_escape_str(proto_default),
759 // For bytes, contains the C escaped value. All bytes >= 128 are escaped
760 FieldDescriptorProto_Type::TYPE_BYTES => {
761 rust::quote_escape_bytes(&text_format::unescape_string(proto_default))
762 }
763 // TODO: resolve outer message prefix
764 FieldDescriptorProto_Type::TYPE_GROUP | FieldDescriptorProto_Type::TYPE_ENUM => {
765 unreachable!()
766 }
767 FieldDescriptorProto_Type::TYPE_MESSAGE => panic!(
768 "default value is not implemented for type: {:?}",
769 self.proto_type
770 ),
771 })
772 } else {
773 None
774 }
775 }
776
777 fn default_value_from_proto_typed(&self) -> Option<RustValueTyped> {
778 self.default_value_from_proto().map(|v| {
779 let default_value_type = match self.proto_type {
780 FieldDescriptorProto_Type::TYPE_STRING => RustType::Ref(Box::new(RustType::Str)),
781 FieldDescriptorProto_Type::TYPE_BYTES => {
782 RustType::Ref(Box::new(RustType::Slice(Box::new(RustType::u8()))))
783 }
784 _ => self.full_storage_iter_elem_type(),
785 };
786
787 RustValueTyped {
788 value: v,
789 rust_type: default_value_type,
790 }
791 })
792 }
793
794 // default value to be returned from fn get_xxx
795 fn get_xxx_default_value_rust(&self) -> String {
796 assert!(self.is_singular() || self.is_oneof());
797 self.default_value_from_proto()
798 .unwrap_or_else(|| self.get_xxx_return_type().default_value(&self.customize))
799 }
800
801 // default to be assigned to field
802 fn element_default_value_rust(&self) -> RustValueTyped {
803 assert!(
804 self.is_singular() || self.is_oneof(),
805 "field is not singular: {}",
806 self.reconstruct_def()
807 );
808 self.default_value_from_proto_typed().unwrap_or_else(|| {
809 self.elem()
810 .rust_storage_type()
811 .default_value_typed(&self.customize)
812 })
813 }
814
815 pub fn reconstruct_def(&self) -> String {
816 let prefix = match (self.proto_field.field.get_label(), self.syntax) {
817 (FieldDescriptorProto_Label::LABEL_REPEATED, _) => "repeated ",
818 (_, Syntax::PROTO3) => "",
819 (FieldDescriptorProto_Label::LABEL_OPTIONAL, _) => "optional ",
820 (FieldDescriptorProto_Label::LABEL_REQUIRED, _) => "required ",
821 };
822 format!(
823 "{}{} {} = {}",
824 prefix,
825 field_type_protobuf_name(&self.proto_field.field),
826 self.proto_field.name(),
827 self.proto_field.number()
828 )
829 }
830
831 pub fn accessor_fn(&self) -> AccessorFn {
832 match self.kind {
833 FieldKind::Repeated(RepeatedField { ref elem, .. }) => {
834 let coll = match self.full_storage_type() {
835 RustType::Vec(..) => "vec",
836 RustType::RepeatedField(..) => "repeated_field",
837 _ => unreachable!(),
838 };
839 let name = format!("make_{}_accessor", coll);
840 AccessorFn {
841 name: name,
842 type_params: vec![elem.lib_protobuf_type(&self.customize)],
843 style: AccessorStyle::Lambda,
844 }
845 }
846 FieldKind::Map(MapField {
847 ref key, ref value, ..
848 }) => AccessorFn {
849 name: "make_map_accessor".to_owned(),
850 type_params: vec![
851 key.lib_protobuf_type(&self.customize),
852 value.lib_protobuf_type(&self.customize),
853 ],
854 style: AccessorStyle::Lambda,
855 },
856 FieldKind::Singular(SingularField {
857 ref elem,
858 flag: SingularFieldFlag::WithoutFlag,
859 }) => {
860 if let &FieldElem::Message(ref name, ..) = elem {
861 // TODO: old style, needed because of default instance
862
863 AccessorFn {
864 name: "make_singular_message_accessor".to_owned(),
865 type_params: vec![name.clone()],
866 style: AccessorStyle::HasGet,
867 }
868 } else {
869 AccessorFn {
870 name: "make_simple_field_accessor".to_owned(),
871 type_params: vec![elem.lib_protobuf_type(&self.customize)],
872 style: AccessorStyle::Lambda,
873 }
874 }
875 }
876 FieldKind::Singular(SingularField {
877 ref elem,
878 flag: SingularFieldFlag::WithFlag { .. },
879 }) => {
880 let coll = match self.full_storage_type() {
881 RustType::Option(..) => "option",
882 RustType::SingularField(..) => "singular_field",
883 RustType::SingularPtrField(..) => "singular_ptr_field",
884 _ => unreachable!(),
885 };
886 let name = format!("make_{}_accessor", coll);
887 AccessorFn {
888 name: name,
889 type_params: vec![elem.lib_protobuf_type(&self.customize)],
890 style: AccessorStyle::Lambda,
891 }
892 }
893 FieldKind::Oneof(OneofField { ref elem, .. }) => {
894 // TODO: uses old style
895
896 let suffix = match &self.elem().rust_storage_type() {
897 t if t.is_primitive() => t.to_code(&self.customize),
898 &RustType::String | &RustType::Chars => "string".to_string(),
899 &RustType::Vec(ref t) if t.is_u8() => "bytes".to_string(),
900 &RustType::Bytes => "bytes".to_string(),
901 &RustType::Enum(..) => "enum".to_string(),
902 &RustType::Message(..) => "message".to_string(),
903 t => panic!("unexpected field type: {:?}", t),
904 };
905
906 let name = format!("make_singular_{}_accessor", suffix);
907
908 let mut type_params = Vec::new();
909 match elem {
910 &FieldElem::Message(ref name, ..) | &FieldElem::Enum(ref name, ..) => {
911 type_params.push(name.to_owned());
912 }
913 _ => (),
914 }
915
916 AccessorFn {
917 name: name,
918 type_params: type_params,
919 style: AccessorStyle::HasGet,
920 }
921 }
922 }
923 }
924
925 pub fn write_clear(&self, w: &mut CodeWriter) {
926 if self.is_oneof() {
927 w.write_line(&format!(
928 "self.{} = ::std::option::Option::None;",
929 self.oneof().oneof_rust_field_name
930 ));
931 } else {
932 let clear_expr = self
933 .full_storage_type()
934 .clear(&self.self_field(), &self.customize);
935 w.write_line(&format!("{};", clear_expr));
936 }
937 }
938
939 // expression that returns size of data is variable
940 fn element_size(&self, var: &str, var_type: &RustType) -> String {
941 assert!(!self.is_repeated_packed());
942
943 match field_type_size(self.proto_type) {
944 Some(data_size) => format!("{}", data_size + self.tag_size()),
945 None => match self.proto_type {
946 FieldDescriptorProto_Type::TYPE_MESSAGE => panic!("not a single-liner"),
947 FieldDescriptorProto_Type::TYPE_BYTES => format!(
948 "::protobuf::rt::bytes_size({}, &{})",
949 self.proto_field.number(),
950 var
951 ),
952 FieldDescriptorProto_Type::TYPE_STRING => format!(
953 "::protobuf::rt::string_size({}, &{})",
954 self.proto_field.number(),
955 var
956 ),
957 FieldDescriptorProto_Type::TYPE_ENUM => {
958 let param_type = match var_type {
959 &RustType::Ref(ref t) => (**t).clone(),
960 t => t.clone(),
961 };
962 format!(
963 "::protobuf::rt::enum_size({}, {})",
964 self.proto_field.number(),
965 var_type.into_target(&param_type, var, &self.customize)
966 )
967 }
968 _ => {
969 let param_type = match var_type {
970 &RustType::Ref(ref t) => (**t).clone(),
971 t => t.clone(),
972 };
973 if self.proto_type.is_s_varint() {
974 format!(
975 "::protobuf::rt::value_varint_zigzag_size({}, {})",
976 self.proto_field.number(),
977 var_type.into_target(&param_type, var, &self.customize)
978 )
979 } else {
980 format!(
981 "::protobuf::rt::value_size({}, {}, ::protobuf::wire_format::{:?})",
982 self.proto_field.number(),
983 var_type.into_target(&param_type, var, &self.customize),
984 self.wire_type
985 )
986 }
987 }
988 },
989 }
990 }
991
992 // output code that writes single element to stream
993 pub fn write_write_element(&self, w: &mut CodeWriter, os: &str, var: &str, ty: &RustType) {
994 if let FieldKind::Repeated(RepeatedField { packed: true, .. }) = self.kind {
995 unreachable!();
996 };
997
998 match self.proto_type {
999 FieldDescriptorProto_Type::TYPE_MESSAGE => {
1000 w.write_line(&format!(
1001 "{}.write_tag({}, ::protobuf::wire_format::{:?})?;",
1002 os,
1003 self.proto_field.number(),
1004 wire_format::WireTypeLengthDelimited
1005 ));
1006 w.write_line(&format!(
1007 "{}.write_raw_varint32({}.get_cached_size())?;",
1008 os, var
1009 ));
1010 w.write_line(&format!("{}.write_to_with_cached_sizes({})?;", var, os));
1011 }
1012 _ => {
1013 let param_type = self.os_write_fn_param_type();
1014 let os_write_fn_suffix = self.os_write_fn_suffix();
1015 let number = self.proto_field.number();
1016 w.write_line(&format!(
1017 "{}.write_{}({}, {})?;",
1018 os,
1019 os_write_fn_suffix,
1020 number,
1021 ty.into_target(&param_type, var, &self.customize)
1022 ));
1023 }
1024 }
1025 }
1026
1027 fn self_field(&self) -> String {
1028 format!("self.{}", self.rust_name)
1029 }
1030
1031 fn self_field_is_some(&self) -> String {
1032 assert!(self.is_singular());
1033 format!("{}.is_some()", self.self_field())
1034 }
1035
1036 fn self_field_is_not_empty(&self) -> String {
1037 assert!(self.is_repeated_or_map());
1038 format!("!{}.is_empty()", self.self_field())
1039 }
1040
1041 fn self_field_is_none(&self) -> String {
1042 assert!(self.is_singular());
1043 format!("{}.is_none()", self.self_field())
1044 }
1045
1046 // type of expression returned by `as_option()`
1047 fn as_option_type(&self) -> RustType {
1048 assert!(self.is_singular());
1049 match self.full_storage_type() {
1050 RustType::Option(ref e) if e.is_copy() => RustType::Option(e.clone()),
1051 RustType::Option(e) => RustType::Option(Box::new(e.ref_type())),
1052 RustType::SingularField(ty) | RustType::SingularPtrField(ty) => {
1053 RustType::Option(Box::new(RustType::Ref(ty)))
1054 }
1055 x => panic!("cannot convert {:?} to option", x),
1056 }
1057 }
1058
1059 // field data viewed as Option
1060 fn self_field_as_option(&self) -> RustValueTyped {
1061 assert!(self.is_singular());
1062
1063 let suffix = match self.full_storage_type() {
1064 RustType::Option(ref e) if e.is_copy() => "",
1065 _ => ".as_ref()",
1066 };
1067
1068 self.as_option_type()
1069 .value(format!("{}{}", self.self_field(), suffix))
1070 }
1071
1072 fn write_if_let_self_field_is_some<F>(&self, w: &mut CodeWriter, cb: F)
1073 where
1074 F: Fn(&str, &RustType, &mut CodeWriter),
1075 {
1076 match self.kind {
1077 FieldKind::Repeated(..) | FieldKind::Map(..) => panic!("field is not singular"),
1078 FieldKind::Singular(SingularField {
1079 flag: SingularFieldFlag::WithFlag { .. },
1080 ref elem,
1081 }) => {
1082 let var = "v";
1083 let ref_prefix = match elem.rust_storage_type().is_copy() {
1084 true => "",
1085 false => "ref ",
1086 };
1087 let as_option = self.self_field_as_option();
1088 w.if_let_stmt(
1089 &format!("Some({}{})", ref_prefix, var),
1090 &as_option.value,
1091 |w| {
1092 let v_type = as_option.rust_type.elem_type();
1093 cb(var, &v_type, w);
1094 },
1095 );
1096 }
1097 FieldKind::Singular(SingularField {
1098 flag: SingularFieldFlag::WithoutFlag,
1099 ref elem,
1100 }) => match *elem {
1101 FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_STRING, ..)
1102 | FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_BYTES, ..) => {
1103 w.if_stmt(format!("!{}.is_empty()", self.self_field()), |w| {
1104 cb(&self.self_field(), &self.full_storage_type(), w);
1105 });
1106 }
1107 _ => {
1108 w.if_stmt(
1109 format!(
1110 "{} != {}",
1111 self.self_field(),
1112 self.full_storage_type().default_value(&self.customize)
1113 ),
1114 |w| {
1115 cb(&self.self_field(), &self.full_storage_type(), w);
1116 },
1117 );
1118 }
1119 },
1120 FieldKind::Oneof(..) => unreachable!(),
1121 }
1122 }
1123
1124 fn write_if_self_field_is_not_empty<F>(&self, w: &mut CodeWriter, cb: F)
1125 where
1126 F: Fn(&mut CodeWriter),
1127 {
1128 assert!(self.is_repeated_or_map());
1129 let self_field_is_not_empty = self.self_field_is_not_empty();
1130 w.if_stmt(self_field_is_not_empty, cb);
1131 }
1132
1133 pub fn write_if_self_field_is_none<F>(&self, w: &mut CodeWriter, cb: F)
1134 where
1135 F: Fn(&mut CodeWriter),
1136 {
1137 let self_field_is_none = self.self_field_is_none();
1138 w.if_stmt(self_field_is_none, cb)
1139 }
1140
1141 // repeated or singular
1142 pub fn write_for_self_field<F>(&self, w: &mut CodeWriter, varn: &str, cb: F)
1143 where
1144 F: Fn(&mut CodeWriter, &RustType),
1145 {
1146 match self.kind {
1147 FieldKind::Oneof(OneofField {
1148 ref elem,
1149 ref oneof_type_name,
1150 ..
1151 }) => {
1152 let cond = format!(
1153 "Some({}::{}(ref {}))",
1154 oneof_type_name.to_code(&self.customize),
1155 self.rust_name,
1156 varn
1157 );
1158 w.if_let_stmt(&cond, &self.self_field_oneof(), |w| {
1159 cb(w, &elem.rust_storage_type())
1160 })
1161 }
1162 _ => {
1163 let v_type = self.full_storage_iter_elem_type();
1164 let self_field = self.self_field();
1165 w.for_stmt(&format!("&{}", self_field), varn, |w| cb(w, &v_type));
1166 }
1167 }
1168 }
1169
1170 fn write_self_field_assign(&self, w: &mut CodeWriter, value: &str) {
1171 let self_field = self.self_field();
1172 w.write_line(&format!("{} = {};", self_field, value));
1173 }
1174
1175 fn write_self_field_assign_some(&self, w: &mut CodeWriter, value: &str) {
1176 let full_storage_type = self.full_storage_type();
1177 match self.singular() {
1178 &SingularField {
1179 flag: SingularFieldFlag::WithFlag { .. },
1180 ..
1181 } => {
1182 self.write_self_field_assign(w, &full_storage_type.wrap_value(value));
1183 }
1184 &SingularField {
1185 flag: SingularFieldFlag::WithoutFlag,
1186 ..
1187 } => {
1188 self.write_self_field_assign(w, value);
1189 }
1190 }
1191 }
1192
1193 fn write_self_field_assign_value(&self, w: &mut CodeWriter, value: &str, ty: &RustType) {
1194 match self.kind {
1195 FieldKind::Repeated(..) | FieldKind::Map(..) => {
1196 let converted = ty.into_target(&self.full_storage_type(), value, &self.customize);
1197 self.write_self_field_assign(w, &converted);
1198 }
1199 FieldKind::Singular(SingularField { ref elem, ref flag }) => {
1200 let converted = ty.into_target(&elem.rust_storage_type(), value, &self.customize);
1201 let wrapped = if *flag == SingularFieldFlag::WithoutFlag {
1202 converted
1203 } else {
1204 self.full_storage_type().wrap_value(&converted)
1205 };
1206 self.write_self_field_assign(w, &wrapped);
1207 }
1208 FieldKind::Oneof(..) => unreachable!(),
1209 }
1210 }
1211
1212 fn write_self_field_assign_default(&self, w: &mut CodeWriter) {
1213 assert!(self.is_singular());
1214 if self.is_oneof() {
1215 let self_field_oneof = self.self_field_oneof();
1216 w.write_line(format!(
1217 "{} = ::std::option::Option::Some({}({}))",
1218 self_field_oneof,
1219 self.variant_path(),
1220 // TODO: default from .proto is not needed here (?)
1221 self.element_default_value_rust()
1222 .into_type(self.full_storage_iter_elem_type(), &self.customize)
1223 .value
1224 ));
1225 } else {
1226 // Note it is different from C++ protobuf, where field is initialized
1227 // with default value
1228 match self.full_storage_type() {
1229 RustType::SingularField(..) | RustType::SingularPtrField(..) => {
1230 let self_field = self.self_field();
1231 w.write_line(&format!("{}.set_default();", self_field));
1232 }
1233 _ => {
1234 self.write_self_field_assign_some(
1235 w,
1236 &self
1237 .elem()
1238 .rust_storage_type()
1239 .default_value_typed(&self.customize)
1240 .into_type(self.elem().rust_storage_type(), &self.customize)
1241 .value,
1242 );
1243 }
1244 }
1245 }
1246 }
1247
1248 fn self_field_vec_packed_fixed_data_size(&self) -> String {
1249 assert!(self.is_fixed());
1250 format!(
1251 "({}.len() * {}) as u32",
1252 self.self_field(),
1253 field_type_size(self.proto_type).unwrap()
1254 )
1255 }
1256
1257 fn self_field_vec_packed_varint_data_size(&self) -> String {
1258 assert!(!self.is_fixed());
1259 let fn_name = if self.is_enum() {
1260 "vec_packed_enum_data_size".to_string()
1261 } else {
1262 let zigzag_suffix = if self.is_zigzag() { "_zigzag" } else { "" };
1263 format!("vec_packed_varint{}_data_size", zigzag_suffix)
1264 };
1265 format!(
1266 "{}::rt::{}(&{})",
1267 protobuf_crate_path(&self.customize),
1268 fn_name,
1269 self.self_field()
1270 )
1271 }
1272
1273 fn self_field_vec_packed_data_size(&self) -> String {
1274 assert!(self.is_repeated_not_map());
1275 if self.is_fixed() {
1276 self.self_field_vec_packed_fixed_data_size()
1277 } else {
1278 self.self_field_vec_packed_varint_data_size()
1279 }
1280 }
1281
1282 fn self_field_vec_packed_fixed_size(&self) -> String {
1283 // zero is filtered outside
1284 format!(
1285 "{} + {}::rt::compute_raw_varint32_size({}) + {}",
1286 self.tag_size(),
1287 protobuf_crate_path(&self.customize),
1288 self.self_field_vec_packed_fixed_data_size(),
1289 self.self_field_vec_packed_fixed_data_size()
1290 )
1291 }
1292
1293 fn self_field_vec_packed_varint_size(&self) -> String {
1294 // zero is filtered outside
1295 assert!(!self.is_fixed());
1296 let fn_name = if self.is_enum() {
1297 "vec_packed_enum_size".to_string()
1298 } else {
1299 let zigzag_suffix = if self.is_zigzag() { "_zigzag" } else { "" };
1300 format!("vec_packed_varint{}_size", zigzag_suffix)
1301 };
1302 format!(
1303 "{}::rt::{}({}, &{})",
1304 protobuf_crate_path(&self.customize),
1305 fn_name,
1306 self.proto_field.number(),
1307 self.self_field()
1308 )
1309 }
1310
1311 fn self_field_oneof(&self) -> String {
1312 format!("self.{}", self.oneof().oneof_rust_field_name)
1313 }
1314
1315 pub fn clear_field_func(&self) -> String {
1316 format!("clear_{}", self.rust_name)
1317 }
1318
1319 // Write `merge_from` part for this singular or repeated field
1320 // of type message, string or bytes
1321 fn write_merge_from_field_message_string_bytes(&self, w: &mut CodeWriter) {
1322 let singular_or_repeated = match self.kind {
1323 FieldKind::Repeated(..) => "repeated",
1324 FieldKind::Singular(SingularField {
1325 flag: SingularFieldFlag::WithFlag { .. },
1326 ..
1327 }) => "singular",
1328 FieldKind::Singular(SingularField {
1329 flag: SingularFieldFlag::WithoutFlag,
1330 ..
1331 }) => "singular_proto3",
1332 FieldKind::Map(..) | FieldKind::Oneof(..) => unreachable!(),
1333 };
1334 let carllerche = match self.kind.primitive_type_variant() {
1335 PrimitiveTypeVariant::Carllerche => "carllerche_",
1336 PrimitiveTypeVariant::Default => "",
1337 };
1338 let type_name_for_fn = protobuf_name(self.proto_type);
1339 w.write_line(&format!(
1340 "::protobuf::rt::read_{}_{}{}_into(wire_type, is, &mut self.{})?;",
1341 singular_or_repeated, carllerche, type_name_for_fn, self.rust_name
1342 ));
1343 }
1344
1345 fn write_error_unexpected_wire_type(&self, wire_type_var: &str, w: &mut CodeWriter) {
1346 w.write_line(&format!(
1347 "return ::std::result::Result::Err({}::rt::unexpected_wire_type({}));",
1348 protobuf_crate_path(&self.customize),
1349 wire_type_var
1350 ));
1351 }
1352
1353 fn write_assert_wire_type(&self, wire_type_var: &str, w: &mut CodeWriter) {
1354 w.if_stmt(
1355 &format!(
1356 "{} != ::protobuf::wire_format::{:?}",
1357 wire_type_var, self.wire_type
1358 ),
1359 |w| {
1360 self.write_error_unexpected_wire_type(wire_type_var, w);
1361 },
1362 );
1363 }
1364
1365 // Write `merge_from` part for this oneof field
1366 fn write_merge_from_oneof(&self, f: &OneofField, wire_type_var: &str, w: &mut CodeWriter) {
1367 self.write_assert_wire_type(wire_type_var, w);
1368
1369 let typed = RustValueTyped {
1370 value: format!(
1371 "{}?",
1372 self.proto_type.read("is", f.elem.primitive_type_variant())
1373 ),
1374 rust_type: self.full_storage_iter_elem_type(),
1375 };
1376
1377 let maybe_boxed = if f.boxed {
1378 typed.boxed(&self.customize)
1379 } else {
1380 typed
1381 };
1382
1383 w.write_line(&format!(
1384 "self.{} = ::std::option::Option::Some({}({}));",
1385 self.oneof().oneof_rust_field_name,
1386 self.variant_path(),
1387 maybe_boxed.value
1388 )); // TODO: into_type
1389 }
1390
1391 // Write `merge_from` part for this map field
1392 fn write_merge_from_map(&self, w: &mut CodeWriter) {
1393 let &MapField {
1394 ref key, ref value, ..
1395 } = self.map();
1396 w.write_line(&format!(
1397 "::protobuf::rt::read_map_into::<{}, {}>(wire_type, is, &mut {})?;",
1398 key.lib_protobuf_type(&self.customize),
1399 value.lib_protobuf_type(&self.customize),
1400 self.self_field()
1401 ));
1402 }
1403
1404 // Write `merge_from` part for this singular field
1405 fn write_merge_from_singular(&self, wire_type_var: &str, w: &mut CodeWriter) {
1406 let field = match self.kind {
1407 FieldKind::Singular(ref field) => field,
1408 _ => panic!(),
1409 };
1410
1411 match field.elem {
1412 FieldElem::Message(..)
1413 | FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_STRING, ..)
1414 | FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_BYTES, ..) => {
1415 self.write_merge_from_field_message_string_bytes(w);
1416 }
1417 FieldElem::Enum(..) => {
1418 let version = match field.flag {
1419 SingularFieldFlag::WithFlag { .. } => "proto2",
1420 SingularFieldFlag::WithoutFlag => "proto3",
1421 };
1422 w.write_line(&format!(
1423 "::protobuf::rt::read_{}_enum_with_unknown_fields_into({}, is, &mut self.{}, {}, &mut self.unknown_fields)?",
1424 version,
1425 wire_type_var,
1426 self.rust_name,
1427 self.proto_field.number()
1428 ));
1429 }
1430 _ => {
1431 let read_proc = format!(
1432 "{}?",
1433 self.proto_type.read("is", PrimitiveTypeVariant::Default)
1434 );
1435
1436 self.write_assert_wire_type(wire_type_var, w);
1437 w.write_line(&format!("let tmp = {};", read_proc));
1438 self.write_self_field_assign_some(w, "tmp");
1439 }
1440 }
1441 }
1442
1443 // Write `merge_from` part for this repeated field
1444 fn write_merge_from_repeated(&self, wire_type_var: &str, w: &mut CodeWriter) {
1445 let field = match self.kind {
1446 FieldKind::Repeated(ref field) => field,
1447 _ => panic!(),
1448 };
1449
1450 match field.elem {
1451 FieldElem::Message(..)
1452 | FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_STRING, ..)
1453 | FieldElem::Primitive(FieldDescriptorProto_Type::TYPE_BYTES, ..) => {
1454 self.write_merge_from_field_message_string_bytes(w);
1455 }
1456 FieldElem::Enum(..) => {
1457 w.write_line(&format!(
1458 "::protobuf::rt::read_repeated_enum_with_unknown_fields_into({}, is, &mut self.{}, {}, &mut self.unknown_fields)?",
1459 wire_type_var,
1460 self.rust_name,
1461 self.proto_field.number()
1462 ));
1463 }
1464 _ => {
1465 w.write_line(&format!(
1466 "{}::rt::read_repeated_{}_into({}, is, &mut self.{})?;",
1467 protobuf_crate_path(&self.customize),
1468 protobuf_name(self.proto_type),
1469 wire_type_var,
1470 self.rust_name
1471 ));
1472 }
1473 }
1474 }
1475
1476 // Write `merge_from` part for this field
1477 pub fn write_merge_from_field(&self, wire_type_var: &str, w: &mut CodeWriter) {
1478 match self.kind {
1479 FieldKind::Oneof(ref f) => self.write_merge_from_oneof(&f, wire_type_var, w),
1480 FieldKind::Map(..) => self.write_merge_from_map(w),
1481 FieldKind::Singular(..) => self.write_merge_from_singular(wire_type_var, w),
1482 FieldKind::Repeated(..) => self.write_merge_from_repeated(wire_type_var, w),
1483 }
1484 }
1485
1486 fn self_field_vec_packed_size(&self) -> String {
1487 match self.kind {
1488 FieldKind::Repeated(RepeatedField { packed: true, .. }) => {
1489 // zero is filtered outside
1490 if self.is_fixed() {
1491 self.self_field_vec_packed_fixed_size()
1492 } else {
1493 self.self_field_vec_packed_varint_size()
1494 }
1495 }
1496 _ => {
1497 panic!("not packed");
1498 }
1499 }
1500 }
1501
1502 pub fn write_element_size(
1503 &self,
1504 w: &mut CodeWriter,
1505 item_var: &str,
1506 item_var_type: &RustType,
1507 sum_var: &str,
1508 ) {
1509 assert!(!self.is_repeated_packed());
1510
1511 match self.proto_type {
1512 FieldDescriptorProto_Type::TYPE_MESSAGE => {
1513 w.write_line(&format!("let len = {}.compute_size();", item_var));
1514 let tag_size = self.tag_size();
1515 w.write_line(&format!(
1516 "{} += {} + ::protobuf::rt::compute_raw_varint32_size(len) + len;",
1517 sum_var, tag_size
1518 ));
1519 }
1520 _ => {
1521 w.write_line(&format!(
1522 "{} += {};",
1523 sum_var,
1524 self.element_size(item_var, item_var_type)
1525 ));
1526 }
1527 }
1528 }
1529
1530 pub fn write_message_write_field(&self, w: &mut CodeWriter) {
1531 match self.kind {
1532 FieldKind::Singular(..) => {
1533 self.write_if_let_self_field_is_some(w, |v, v_type, w| {
1534 self.write_write_element(w, "os", v, v_type);
1535 });
1536 }
1537 FieldKind::Repeated(RepeatedField { packed: false, .. }) => {
1538 self.write_for_self_field(w, "v", |w, v_type| {
1539 self.write_write_element(w, "os", "v", v_type);
1540 });
1541 }
1542 FieldKind::Repeated(RepeatedField { packed: true, .. }) => {
1543 self.write_if_self_field_is_not_empty(w, |w| {
1544 let number = self.proto_field.number();
1545 w.write_line(&format!(
1546 "os.write_tag({}, {}::wire_format::{:?})?;",
1547 number,
1548 protobuf_crate_path(&self.customize),
1549 wire_format::WireTypeLengthDelimited
1550 ));
1551 w.comment("TODO: Data size is computed again, it should be cached");
1552 let data_size_expr = self.self_field_vec_packed_data_size();
1553 w.write_line(&format!("os.write_raw_varint32({})?;", data_size_expr));
1554 self.write_for_self_field(w, "v", |w, v_type| {
1555 let param_type = self.os_write_fn_param_type();
1556 let os_write_fn_suffix = self.os_write_fn_suffix();
1557 w.write_line(&format!(
1558 "os.write_{}_no_tag({})?;",
1559 os_write_fn_suffix,
1560 v_type.into_target(&param_type, "v", &self.customize)
1561 ));
1562 });
1563 });
1564 }
1565 FieldKind::Map(MapField {
1566 ref key, ref value, ..
1567 }) => {
1568 w.write_line(&format!(
1569 "::protobuf::rt::write_map_with_cached_sizes::<{}, {}>({}, &{}, os)?;",
1570 key.lib_protobuf_type(&self.customize),
1571 value.lib_protobuf_type(&self.customize),
1572 self.proto_field.number(),
1573 self.self_field()
1574 ));
1575 }
1576 FieldKind::Oneof(..) => unreachable!(),
1577 };
1578 }
1579
1580 pub fn write_message_compute_field_size(&self, sum_var: &str, w: &mut CodeWriter) {
1581 match self.kind {
1582 FieldKind::Singular(..) => {
1583 self.write_if_let_self_field_is_some(w, |v, v_type, w| {
1584 match field_type_size(self.proto_type) {
1585 Some(s) => {
1586 let tag_size = self.tag_size();
1587 w.write_line(&format!("{} += {};", sum_var, (s + tag_size) as isize));
1588 }
1589 None => {
1590 self.write_element_size(w, v, v_type, sum_var);
1591 }
1592 };
1593 });
1594 }
1595 FieldKind::Repeated(RepeatedField { packed: false, .. }) => {
1596 match field_type_size(self.proto_type) {
1597 Some(s) => {
1598 let tag_size = self.tag_size();
1599 let self_field = self.self_field();
1600 w.write_line(&format!(
1601 "{} += {} * {}.len() as u32;",
1602 sum_var,
1603 (s + tag_size) as isize,
1604 self_field
1605 ));
1606 }
1607 None => {
1608 self.write_for_self_field(w, "value", |w, value_type| {
1609 self.write_element_size(w, "value", value_type, sum_var);
1610 });
1611 }
1612 };
1613 }
1614 FieldKind::Map(MapField {
1615 ref key, ref value, ..
1616 }) => {
1617 w.write_line(&format!(
1618 "{} += {}::rt::compute_map_size::<{}, {}>({}, &{});",
1619 sum_var,
1620 protobuf_crate_path(&self.customize),
1621 key.lib_protobuf_type(&self.customize),
1622 value.lib_protobuf_type(&self.customize),
1623 self.proto_field.number(),
1624 self.self_field()
1625 ));
1626 }
1627 FieldKind::Repeated(RepeatedField { packed: true, .. }) => {
1628 self.write_if_self_field_is_not_empty(w, |w| {
1629 let size_expr = self.self_field_vec_packed_size();
1630 w.write_line(&format!("{} += {};", sum_var, size_expr));
1631 });
1632 }
1633 FieldKind::Oneof(..) => unreachable!(),
1634 }
1635 }
1636
1637 fn write_message_field_get_singular(&self, w: &mut CodeWriter) {
1638 let get_xxx_return_type = self.get_xxx_return_type();
1639
1640 if self.proto_type == FieldDescriptorProto_Type::TYPE_MESSAGE {
1641 let self_field = self.self_field();
Haibo Huang72fec012020-07-10 20:24:04 -07001642 let ref rust_type_message = match self.elem().rust_storage_type() {
1643 RustType::Message(m) => m,
1644 _ => unreachable!(),
1645 };
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -07001646 w.write_line(&format!(
Haibo Huang72fec012020-07-10 20:24:04 -07001647 "{}.as_ref().unwrap_or_else(|| {})",
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -07001648 self_field,
Haibo Huang72fec012020-07-10 20:24:04 -07001649 rust_type_message.default_instance(&self.customize)
Chih-Hung Hsieh92ff6052020-06-10 20:18:39 -07001650 ));
1651 } else {
1652 let get_xxx_default_value_rust = self.get_xxx_default_value_rust();
1653 let self_field = self.self_field();
1654 match self.singular() {
1655 &SingularField {
1656 flag: SingularFieldFlag::WithFlag { .. },
1657 ..
1658 } => {
1659 if get_xxx_return_type.is_ref() {
1660 let as_option = self.self_field_as_option();
1661 w.match_expr(&as_option.value, |w| {
1662 let v_type = as_option.rust_type.elem_type();
1663 let r_type = self.get_xxx_return_type();
1664 w.case_expr(
1665 "Some(v)",
1666 v_type.into_target(&r_type, "v", &self.customize),
1667 );
1668 let get_xxx_default_value_rust = self.get_xxx_default_value_rust();
1669 w.case_expr("None", get_xxx_default_value_rust);
1670 });
1671 } else {
1672 w.write_line(&format!(
1673 "{}.unwrap_or({})",
1674 self_field, get_xxx_default_value_rust
1675 ));
1676 }
1677 }
1678 &SingularField {
1679 flag: SingularFieldFlag::WithoutFlag,
1680 ..
1681 } => {
1682 w.write_line(self.full_storage_type().into_target(
1683 &get_xxx_return_type,
1684 &self_field,
1685 &self.customize,
1686 ));
1687 }
1688 }
1689 }
1690 }
1691
1692 fn write_message_field_get(&self, w: &mut CodeWriter) {
1693 let get_xxx_return_type = self.get_xxx_return_type();
1694 let fn_def = format!(
1695 "get_{}(&self) -> {}",
1696 self.rust_name,
1697 get_xxx_return_type.to_code(&self.customize)
1698 );
1699
1700 w.pub_fn(&fn_def, |w| match self.kind {
1701 FieldKind::Oneof(OneofField { ref elem, .. }) => {
1702 let self_field_oneof = self.self_field_oneof();
1703 w.match_expr(self_field_oneof, |w| {
1704 let (refv, vtype) = if !self.elem_type_is_copy() {
1705 ("ref v", elem.rust_storage_type().ref_type())
1706 } else {
1707 ("v", elem.rust_storage_type())
1708 };
1709 w.case_expr(
1710 format!(
1711 "::std::option::Option::Some({}({}))",
1712 self.variant_path(),
1713 refv
1714 ),
1715 vtype.into_target(&get_xxx_return_type, "v", &self.customize),
1716 );
1717 w.case_expr("_", self.get_xxx_default_value_rust());
1718 })
1719 }
1720 FieldKind::Singular(..) => {
1721 self.write_message_field_get_singular(w);
1722 }
1723 FieldKind::Repeated(..) | FieldKind::Map(..) => {
1724 let self_field = self.self_field();
1725 w.write_line(&format!("&{}", self_field));
1726 }
1727 });
1728 }
1729
1730 fn has_has(&self) -> bool {
1731 match self.kind {
1732 FieldKind::Repeated(..) | FieldKind::Map(..) => false,
1733 FieldKind::Singular(SingularField {
1734 flag: SingularFieldFlag::WithFlag { .. },
1735 ..
1736 }) => true,
1737 FieldKind::Singular(SingularField {
1738 flag: SingularFieldFlag::WithoutFlag,
1739 ..
1740 }) => false,
1741 FieldKind::Oneof(..) => true,
1742 }
1743 }
1744
1745 fn has_mut(&self) -> bool {
1746 match self.kind {
1747 FieldKind::Repeated(..) | FieldKind::Map(..) => true,
1748 // TODO: string should be public, and mut is not needed
1749 FieldKind::Singular(..) | FieldKind::Oneof(..) => !self.elem_type_is_copy(),
1750 }
1751 }
1752
1753 fn has_take(&self) -> bool {
1754 match self.kind {
1755 FieldKind::Repeated(..) | FieldKind::Map(..) => true,
1756 // TODO: string should be public, and mut is not needed
1757 FieldKind::Singular(..) | FieldKind::Oneof(..) => !self.elem_type_is_copy(),
1758 }
1759 }
1760
1761 fn has_name(&self) -> String {
1762 format!("has_{}", self.rust_name)
1763 }
1764
1765 fn write_message_field_has(&self, w: &mut CodeWriter) {
1766 w.pub_fn(&format!("{}(&self) -> bool", self.has_name()), |w| {
1767 if !self.is_oneof() {
1768 let self_field_is_some = self.self_field_is_some();
1769 w.write_line(self_field_is_some);
1770 } else {
1771 let self_field_oneof = self.self_field_oneof();
1772 w.match_expr(self_field_oneof, |w| {
1773 w.case_expr(
1774 format!("::std::option::Option::Some({}(..))", self.variant_path()),
1775 "true",
1776 );
1777 w.case_expr("_", "false");
1778 });
1779 }
1780 });
1781 }
1782
1783 fn write_message_field_set(&self, w: &mut CodeWriter) {
1784 let set_xxx_param_type = self.set_xxx_param_type();
1785 w.comment("Param is passed by value, moved");
1786 let ref name = self.rust_name;
1787 w.pub_fn(
1788 &format!(
1789 "set_{}(&mut self, v: {})",
1790 name,
1791 set_xxx_param_type.to_code(&self.customize)
1792 ),
1793 |w| {
1794 if !self.is_oneof() {
1795 self.write_self_field_assign_value(w, "v", &set_xxx_param_type);
1796 } else {
1797 let self_field_oneof = self.self_field_oneof();
1798 let v = set_xxx_param_type.into_target(
1799 &self.oneof().rust_type(),
1800 "v",
1801 &self.customize,
1802 );
1803 w.write_line(&format!(
1804 "{} = ::std::option::Option::Some({}({}))",
1805 self_field_oneof,
1806 self.variant_path(),
1807 v
1808 ));
1809 }
1810 },
1811 );
1812 }
1813
1814 fn write_message_field_mut(&self, w: &mut CodeWriter) {
1815 let mut_xxx_return_type = self.mut_xxx_return_type();
1816 w.comment("Mutable pointer to the field.");
1817 if self.is_singular() {
1818 w.comment("If field is not initialized, it is initialized with default value first.");
1819 }
1820 let fn_def = match mut_xxx_return_type {
1821 RustType::Ref(ref param) => format!(
1822 "mut_{}(&mut self) -> &mut {}",
1823 self.rust_name,
1824 param.to_code(&self.customize)
1825 ),
1826 _ => panic!(
1827 "not a ref: {}",
1828 mut_xxx_return_type.to_code(&self.customize)
1829 ),
1830 };
1831 w.pub_fn(&fn_def, |w| {
1832 match self.kind {
1833 FieldKind::Repeated(..) | FieldKind::Map(..) => {
1834 let self_field = self.self_field();
1835 w.write_line(&format!("&mut {}", self_field));
1836 }
1837 FieldKind::Singular(SingularField {
1838 flag: SingularFieldFlag::WithFlag { .. },
1839 ..
1840 }) => {
1841 self.write_if_self_field_is_none(w, |w| {
1842 self.write_self_field_assign_default(w);
1843 });
1844 let self_field = self.self_field();
1845 w.write_line(&format!("{}.as_mut().unwrap()", self_field));
1846 }
1847 FieldKind::Singular(SingularField {
1848 flag: SingularFieldFlag::WithoutFlag,
1849 ..
1850 }) => w.write_line(&format!("&mut {}", self.self_field())),
1851 FieldKind::Oneof(..) => {
1852 let self_field_oneof = self.self_field_oneof();
1853
1854 // if oneof does not contain current field
1855 w.if_let_else_stmt(
1856 &format!("::std::option::Option::Some({}(_))", self.variant_path())[..],
1857 &self_field_oneof[..],
1858 |w| {
1859 // initialize it with default value
1860 w.write_line(&format!(
1861 "{} = ::std::option::Option::Some({}({}));",
1862 self_field_oneof,
1863 self.variant_path(),
1864 self.element_default_value_rust()
1865 .into_type(self.oneof().rust_type(), &self.customize)
1866 .value
1867 ));
1868 },
1869 );
1870
1871 // extract field
1872 w.match_expr(self_field_oneof, |w| {
1873 w.case_expr(
1874 format!(
1875 "::std::option::Option::Some({}(ref mut v))",
1876 self.variant_path()
1877 ),
1878 "v",
1879 );
1880 w.case_expr("_", "panic!()");
1881 });
1882 }
1883 }
1884 });
1885 }
1886
1887 fn write_message_field_take_oneof(&self, w: &mut CodeWriter) {
1888 let take_xxx_return_type = self.take_xxx_return_type();
1889
1890 // TODO: replace with if let
1891 w.write_line(&format!("if self.{}() {{", self.has_name()));
1892 w.indented(|w| {
1893 let self_field_oneof = self.self_field_oneof();
1894 w.match_expr(format!("{}.take()", self_field_oneof), |w| {
1895 let value_in_some = self.oneof().rust_type().value("v".to_owned());
1896 let converted =
1897 value_in_some.into_type(self.take_xxx_return_type(), &self.customize);
1898 w.case_expr(
1899 format!("::std::option::Option::Some({}(v))", self.variant_path()),
1900 &converted.value,
1901 );
1902 w.case_expr("_", "panic!()");
1903 });
1904 });
1905 w.write_line("} else {");
1906 w.indented(|w| {
1907 w.write_line(
1908 self.elem()
1909 .rust_storage_type()
1910 .default_value_typed(&self.customize)
1911 .into_type(take_xxx_return_type.clone(), &self.customize)
1912 .value,
1913 );
1914 });
1915 w.write_line("}");
1916 }
1917
1918 fn write_message_field_take(&self, w: &mut CodeWriter) {
1919 let take_xxx_return_type = self.take_xxx_return_type();
1920 w.comment("Take field");
1921 w.pub_fn(
1922 &format!(
1923 "take_{}(&mut self) -> {}",
1924 self.rust_name,
1925 take_xxx_return_type.to_code(&self.customize)
1926 ),
1927 |w| match self.kind {
1928 FieldKind::Oneof(..) => {
1929 self.write_message_field_take_oneof(w);
1930 }
1931 FieldKind::Repeated(..) | FieldKind::Map(..) => {
1932 w.write_line(&format!(
1933 "::std::mem::replace(&mut self.{}, {})",
1934 self.rust_name,
1935 take_xxx_return_type.default_value(&self.customize)
1936 ));
1937 }
1938 FieldKind::Singular(SingularField {
1939 ref elem,
1940 flag: SingularFieldFlag::WithFlag { .. },
1941 }) => {
1942 if !elem.is_copy() {
1943 w.write_line(&format!(
1944 "{}.take().unwrap_or_else(|| {})",
1945 self.self_field(),
1946 elem.rust_storage_type().default_value(&self.customize)
1947 ));
1948 } else {
1949 w.write_line(&format!(
1950 "{}.take().unwrap_or({})",
1951 self.self_field(),
1952 self.element_default_value_rust().value
1953 ));
1954 }
1955 }
1956 FieldKind::Singular(SingularField {
1957 flag: SingularFieldFlag::WithoutFlag,
1958 ..
1959 }) => w.write_line(&format!(
1960 "::std::mem::replace(&mut {}, {})",
1961 self.self_field(),
1962 self.full_storage_type().default_value(&self.customize)
1963 )),
1964 },
1965 );
1966 }
1967
1968 pub fn write_message_single_field_accessors(&self, w: &mut CodeWriter) {
1969 // TODO: do not generate `get` when !proto2 and !generate_accessors`
1970 w.write_line("");
1971 self.write_message_field_get(w);
1972
1973 if !self.generate_accessors {
1974 return;
1975 }
1976
1977 let clear_field_func = self.clear_field_func();
1978 w.pub_fn(&format!("{}(&mut self)", clear_field_func), |w| {
1979 self.write_clear(w);
1980 });
1981
1982 if self.has_has() {
1983 w.write_line("");
1984 self.write_message_field_has(w);
1985 }
1986
1987 w.write_line("");
1988 self.write_message_field_set(w);
1989
1990 if self.has_mut() {
1991 w.write_line("");
1992 self.write_message_field_mut(w);
1993 }
1994
1995 if self.has_take() {
1996 w.write_line("");
1997 self.write_message_field_take(w);
1998 }
1999 }
2000}
2001
2002pub(crate) fn rust_field_name_for_protobuf_field_name(name: &str) -> RustIdent {
2003 if rust::is_rust_keyword(name) {
2004 RustIdent::new(&format!("field_{}", name))
2005 } else {
2006 RustIdent::new(name)
2007 }
2008}