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