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