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