1 use std::fmt;
2 
3 use crate::descriptor::field_descriptor_proto;
4 use crate::descriptor::FieldDescriptorProto;
5 use crate::message_dyn::MessageDyn;
6 use crate::reflect::acc::v2::map::MapFieldAccessorHolder;
7 use crate::reflect::acc::v2::repeated::RepeatedFieldAccessorHolder;
8 use crate::reflect::acc::v2::singular::SingularFieldAccessorHolder;
9 use crate::reflect::acc::v2::AccessorV2;
10 use crate::reflect::acc::GeneratedFieldAccessor;
11 use crate::reflect::dynamic::DynamicMessage;
12 use crate::reflect::field::dynamic::DynamicFieldDescriptorRef;
13 use crate::reflect::field::index::FieldIndex;
14 use crate::reflect::field::index::FieldKind;
15 use crate::reflect::field::protobuf_field_type::ProtobufFieldType;
16 use crate::reflect::field::runtime_field_type::RuntimeFieldType;
17 use crate::reflect::map::ReflectMapMut;
18 use crate::reflect::map::ReflectMapRef;
19 use crate::reflect::message::message_ref::MessageRef;
20 use crate::reflect::message::MessageDescriptorImplRef;
21 use crate::reflect::oneof::OneofDescriptor;
22 use crate::reflect::protobuf_type_box::ProtobufType;
23 use crate::reflect::reflect_eq::ReflectEq;
24 use crate::reflect::reflect_eq::ReflectEqMode;
25 use crate::reflect::repeated::ReflectRepeatedMut;
26 use crate::reflect::repeated::ReflectRepeatedRef;
27 use crate::reflect::value::value_ref::ReflectValueMut;
28 use crate::reflect::FileDescriptor;
29 use crate::reflect::MessageDescriptor;
30 use crate::reflect::ReflectOptionalRef;
31 use crate::reflect::ReflectValueBox;
32 use crate::reflect::ReflectValueRef;
33 use crate::reflect::RuntimeType;
34 
35 pub(crate) mod dynamic;
36 pub(crate) mod index;
37 pub(crate) mod protobuf_field_type;
38 pub(crate) mod runtime_field_type;
39 
40 /// Reference to a value stored in a field, optional, repeated or map.
41 #[derive(PartialEq)]
42 pub enum ReflectFieldRef<'a> {
43     /// Singular field, optional or required in proto3 and just plain field in proto3
44     Optional(ReflectOptionalRef<'a>),
45     /// Repeated field
46     Repeated(ReflectRepeatedRef<'a>),
47     /// Map field
48     Map(ReflectMapRef<'a>),
49 }
50 
51 impl<'a> ReflectFieldRef<'a> {
default_for_field(field: &FieldDescriptor) -> ReflectFieldRef<'a>52     pub(crate) fn default_for_field(field: &FieldDescriptor) -> ReflectFieldRef<'a> {
53         match field.runtime_field_type() {
54             RuntimeFieldType::Singular(elem) => {
55                 ReflectFieldRef::Optional(ReflectOptionalRef::none(elem))
56             }
57             RuntimeFieldType::Repeated(elem) => {
58                 ReflectFieldRef::Repeated(ReflectRepeatedRef::new_empty(elem))
59             }
60             RuntimeFieldType::Map(k, v) => ReflectFieldRef::Map(ReflectMapRef::new_empty(k, v)),
61         }
62     }
63 }
64 
65 impl<'a> ReflectEq for ReflectFieldRef<'a> {
reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool66     fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool {
67         match (self, that) {
68             (ReflectFieldRef::Optional(a), ReflectFieldRef::Optional(b)) => {
69                 match (a.value(), b.value()) {
70                     (Some(av), Some(bv)) => av.reflect_eq(&bv, mode),
71                     (None, None) => true,
72                     _ => false,
73                 }
74             }
75             (ReflectFieldRef::Repeated(a), ReflectFieldRef::Repeated(b)) => a.reflect_eq(b, mode),
76             (ReflectFieldRef::Map(a), ReflectFieldRef::Map(b)) => a.reflect_eq(b, mode),
77             _ => false,
78         }
79     }
80 }
81 
_assert_sync<'a>()82 fn _assert_sync<'a>() {
83     fn _assert_send_sync<T: Sync>() {}
84     _assert_send_sync::<ReflectFieldRef<'a>>();
85 }
86 
87 /// Field descriptor.
88 ///
89 /// Can be used for runtime reflection.
90 #[derive(Eq, PartialEq, Clone)]
91 pub struct FieldDescriptor {
92     pub(crate) file_descriptor: FileDescriptor,
93     pub(crate) index: usize,
94 }
95 
96 impl fmt::Display for FieldDescriptor {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result97     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98         match &self.index().kind {
99             FieldKind::MessageField(m) => write!(
100                 f,
101                 "{}.{}",
102                 self.file_descriptor.message_by_index(*m),
103                 self.name()
104             ),
105             FieldKind::Extension(Some(m), _) => write!(
106                 f,
107                 "{}.{}",
108                 self.file_descriptor.message_by_index(*m),
109                 self.name()
110             ),
111             FieldKind::Extension(None, _) => {
112                 if self.file_descriptor.proto().package().is_empty() {
113                     write!(f, "{}", self.name())
114                 } else {
115                     write!(
116                         f,
117                         "{}.{}",
118                         self.file_descriptor.proto().package(),
119                         self.name()
120                     )
121                 }
122             }
123         }
124     }
125 }
126 
127 impl FieldDescriptor {
regular(&self) -> (MessageDescriptor, usize)128     pub(crate) fn regular(&self) -> (MessageDescriptor, usize) {
129         match self.index().kind {
130             FieldKind::MessageField(_) => {
131                 let m = self.containing_message();
132                 (
133                     m.clone(),
134                     self.index - m.index().message_index.first_field_index,
135                 )
136             }
137             // TODO: implement and remove.
138             _ => panic!("regular field"),
139         }
140     }
141 
file_descriptor(&self) -> &FileDescriptor142     pub(crate) fn file_descriptor(&self) -> &FileDescriptor {
143         &self.file_descriptor
144     }
145 
146     /// Get `.proto` description of field
proto(&self) -> &FieldDescriptorProto147     pub fn proto(&self) -> &FieldDescriptorProto {
148         &self.index().proto
149     }
150 
151     /// Field name as specified in `.proto` file.
name(&self) -> &str152     pub fn name(&self) -> &str {
153         self.proto().name()
154     }
155 
156     /// Field number as specified in `.proto` file.
number(&self) -> i32157     pub fn number(&self) -> i32 {
158         self.proto().number()
159     }
160 
161     /// Fully qualified name of the field: fully qualified name of the declaring type
162     /// followed by the field name.
163     ///
164     /// Declaring type is a message (for regular field or extensions) or a package
165     /// (for top-level extensions).
full_name(&self) -> String166     pub fn full_name(&self) -> String {
167         self.to_string()
168     }
169 
170     /// Oneof descriptor containing this field. Do not skip synthetic oneofs.
containing_oneof_including_synthetic(&self) -> Option<OneofDescriptor>171     pub fn containing_oneof_including_synthetic(&self) -> Option<OneofDescriptor> {
172         if let FieldKind::MessageField(..) = self.index().kind {
173             let proto = self.proto();
174             if proto.has_oneof_index() {
175                 Some(OneofDescriptor {
176                     file_descriptor: self.file_descriptor().clone(),
177                     index: self.containing_message().index().oneofs.start
178                         + proto.oneof_index() as usize,
179                 })
180             } else {
181                 None
182             }
183         } else {
184             None
185         }
186     }
187 
188     /// Oneof containing this field.
189     ///
190     /// Return `None` if this field is not part of oneof or if it is synthetic oneof.
containing_oneof(&self) -> Option<OneofDescriptor>191     pub fn containing_oneof(&self) -> Option<OneofDescriptor> {
192         self.containing_oneof_including_synthetic()
193             .filter(|o| !o.is_synthetic())
194     }
195 
196     /// Message which declares this field (for extension, **not** the message we extend).
_declaring_message(&self) -> Option<MessageDescriptor>197     fn _declaring_message(&self) -> Option<MessageDescriptor> {
198         match &self.index().kind {
199             FieldKind::MessageField(m) => Some(self.file_descriptor.message_by_index(*m)),
200             FieldKind::Extension(m, _) => Some(self.file_descriptor.message_by_index(*m.as_ref()?)),
201         }
202     }
203 
204     /// Message which contains this field.
205     ///
206     /// For extension fields, this is the message being extended.
containing_message(&self) -> MessageDescriptor207     pub fn containing_message(&self) -> MessageDescriptor {
208         match &self.index().kind {
209             FieldKind::MessageField(m) => self.file_descriptor().message_by_index(*m),
210             FieldKind::Extension(_, extendee) => extendee.resolve_message(self.file_descriptor()),
211         }
212     }
213 
index(&self) -> &FieldIndex214     fn index(&self) -> &FieldIndex {
215         &self.file_descriptor.common().fields[self.index]
216     }
217 
index_with_message_lifetime<'a>(&self, m: &'a dyn MessageDyn) -> &'a FieldIndex218     fn index_with_message_lifetime<'a>(&self, m: &'a dyn MessageDyn) -> &'a FieldIndex {
219         let (descriptor, index) = self.regular();
220         let file_fields = match self.singular() {
221             SingularFieldAccessorRef::Generated(..) => {
222                 &descriptor
223                     .file_descriptor
224                     .common_for_generated_descriptor()
225                     .fields
226             }
227             SingularFieldAccessorRef::Dynamic(..) => {
228                 &DynamicMessage::downcast_ref(m)
229                     .descriptor()
230                     .file_descriptor
231                     .common()
232                     .fields
233             }
234         };
235         &descriptor.index().message_index.slice_fields(file_fields)[index]
236     }
237 
238     /// JSON field name.
239     ///
240     /// Can be different from `.proto` field name.
241     ///
242     /// See [JSON mapping][json] for details.
243     ///
244     /// [json]: https://developers.google.com/protocol-buffers/docs/proto3#json
json_name(&self) -> &str245     pub fn json_name(&self) -> &str {
246         &self.index().json_name
247     }
248 
249     /// If this field is optional or required.
is_singular(&self) -> bool250     pub fn is_singular(&self) -> bool {
251         match self.proto().label() {
252             field_descriptor_proto::Label::LABEL_REQUIRED => true,
253             field_descriptor_proto::Label::LABEL_OPTIONAL => true,
254             field_descriptor_proto::Label::LABEL_REPEATED => false,
255         }
256     }
257 
258     /// Is this field required.
is_required(&self) -> bool259     pub fn is_required(&self) -> bool {
260         self.proto().label() == field_descriptor_proto::Label::LABEL_REQUIRED
261     }
262 
263     /// If this field repeated or map?
is_repeated_or_map(&self) -> bool264     pub fn is_repeated_or_map(&self) -> bool {
265         self.proto().label() == field_descriptor_proto::Label::LABEL_REPEATED
266     }
267 
268     /// Is this field repeated, but not map field?
is_repeated(&self) -> bool269     pub fn is_repeated(&self) -> bool {
270         match self.runtime_field_type() {
271             RuntimeFieldType::Repeated(..) => true,
272             _ => false,
273         }
274     }
275 
get_impl(&self) -> FieldDescriptorImplRef276     fn get_impl(&self) -> FieldDescriptorImplRef {
277         let (descriptor, index) = self.regular();
278         match descriptor.get_impl() {
279             MessageDescriptorImplRef::Generated(g) => {
280                 FieldDescriptorImplRef::Generated(&g.non_map().fields[index].accessor)
281             }
282             MessageDescriptorImplRef::Dynamic => {
283                 FieldDescriptorImplRef::Dynamic(DynamicFieldDescriptorRef { field: self })
284             }
285         }
286     }
287 
288     /// If this field a map field?
is_map(&self) -> bool289     pub fn is_map(&self) -> bool {
290         match self.runtime_field_type() {
291             RuntimeFieldType::Map(..) => true,
292             _ => false,
293         }
294     }
295 
296     /// Check if field is set in given message.
297     ///
298     /// For repeated field or map field return `true` if
299     /// collection is not empty.
300     ///
301     /// # Panics
302     ///
303     /// If this field belongs to a different message type.
has_field(&self, m: &dyn MessageDyn) -> bool304     pub fn has_field(&self, m: &dyn MessageDyn) -> bool {
305         match self.get_reflect(m) {
306             ReflectFieldRef::Optional(v) => v.value().is_some(),
307             ReflectFieldRef::Repeated(r) => !r.is_empty(),
308             ReflectFieldRef::Map(m) => !m.is_empty(),
309         }
310     }
311 
312     // accessors
313 
singular(&self) -> SingularFieldAccessorRef314     fn singular(&self) -> SingularFieldAccessorRef {
315         match self.get_impl() {
316             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(
317                 AccessorV2::Singular(ref a),
318             )) => SingularFieldAccessorRef::Generated(a),
319             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => {
320                 panic!("not a singular field: {}", self)
321             }
322             FieldDescriptorImplRef::Dynamic(d) => SingularFieldAccessorRef::Dynamic(d),
323         }
324     }
325 
repeated(&self) -> RepeatedFieldAccessorRef326     fn repeated(&self) -> RepeatedFieldAccessorRef {
327         match self.get_impl() {
328             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(
329                 AccessorV2::Repeated(ref a),
330             )) => RepeatedFieldAccessorRef::Generated(a),
331             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => {
332                 panic!("not a repeated field: {}", self)
333             }
334             FieldDescriptorImplRef::Dynamic(d) => RepeatedFieldAccessorRef::Dynamic(d),
335         }
336     }
337 
map(&self) -> MapFieldAccessorRef338     fn map(&self) -> MapFieldAccessorRef {
339         match self.get_impl() {
340             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(AccessorV2::Map(
341                 ref a,
342             ))) => MapFieldAccessorRef::Generated(a),
343             FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => {
344                 panic!("not a map field: {}", self)
345             }
346             FieldDescriptorImplRef::Dynamic(d) => MapFieldAccessorRef::Dynamic(d),
347         }
348     }
349 
350     /// Obtain type of map key and value.
map_proto_type(&self) -> (ProtobufType, ProtobufType)351     pub(crate) fn map_proto_type(&self) -> (ProtobufType, ProtobufType) {
352         match self.protobuf_field_type() {
353             ProtobufFieldType::Map(k, v) => (k, v),
354             _ => panic!("not a map field: {}", self),
355         }
356     }
357 
358     /// Get message field or default instance if field is unset.
359     ///
360     /// # Panics
361     /// If this field belongs to a different message type or
362     /// field type is not message.
get_message<'a>(&self, m: &'a dyn MessageDyn) -> MessageRef<'a>363     pub fn get_message<'a>(&self, m: &'a dyn MessageDyn) -> MessageRef<'a> {
364         match self.get_singular_field_or_default(m) {
365             ReflectValueRef::Message(m) => m,
366             _ => panic!("not message field: {}", self),
367         }
368     }
369 
370     /// Get a mutable reference to a message field.
371     /// Initialize field with default message if unset.
372     ///
373     /// # Panics
374     ///
375     /// If this field belongs to a different message type or
376     /// field type is not singular message.
mut_message<'a>(&self, m: &'a mut dyn MessageDyn) -> &'a mut dyn MessageDyn377     pub fn mut_message<'a>(&self, m: &'a mut dyn MessageDyn) -> &'a mut dyn MessageDyn {
378         match self.mut_singular_field_or_default(m) {
379             ReflectValueMut::Message(m) => m,
380         }
381     }
382 
383     /// Default value.
384     ///
385     /// # Panics
386     ///
387     /// If field is not singular.
singular_default_value(&self) -> ReflectValueRef388     pub fn singular_default_value(&self) -> ReflectValueRef {
389         self.index().default_value(self)
390     }
391 
392     /// Get singular field value.
393     ///
394     /// Return field default value if field is unset.
395     ///
396     /// # Panics
397     ///
398     /// If this field belongs to a different message type or fields is not singular.
get_singular_field_or_default<'a>(&self, m: &'a dyn MessageDyn) -> ReflectValueRef<'a>399     pub fn get_singular_field_or_default<'a>(&self, m: &'a dyn MessageDyn) -> ReflectValueRef<'a> {
400         match self.get_singular(m) {
401             Some(m) => m,
402             None => self.index_with_message_lifetime(m).default_value(self),
403         }
404     }
405 
406     // Not public because it is not implemented for all types
mut_singular_field_or_default<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectValueMut<'a>407     fn mut_singular_field_or_default<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectValueMut<'a> {
408         match self.singular() {
409             SingularFieldAccessorRef::Generated(g) => g.accessor.mut_field_or_default(m),
410             SingularFieldAccessorRef::Dynamic(..) => {
411                 DynamicMessage::downcast_mut(m).mut_singular_field_or_default(self)
412             }
413         }
414     }
415 
416     /// Runtime representation of singular field.
417     ///
418     /// # Panics
419     ///
420     /// If this field belongs to a different message type or field is not singular.
singular_runtime_type(&self) -> RuntimeType421     pub fn singular_runtime_type(&self) -> RuntimeType {
422         match self.runtime_field_type() {
423             RuntimeFieldType::Singular(s) => s,
424             _ => panic!("Not a singular field: {}", self),
425         }
426     }
427 
428     /// Set singular field.
429     ///
430     /// # Panics
431     ///
432     /// If this field belongs to a different message type or
433     /// field is not singular or value is of different type.
set_singular_field(&self, m: &mut dyn MessageDyn, value: ReflectValueBox)434     pub fn set_singular_field(&self, m: &mut dyn MessageDyn, value: ReflectValueBox) {
435         match self.singular() {
436             SingularFieldAccessorRef::Generated(g) => g.accessor.set_field(m, value),
437             SingularFieldAccessorRef::Dynamic(d) => d.set_field(m, value),
438         }
439     }
440 
441     /// Clear a field.
clear_field(&self, m: &mut dyn MessageDyn)442     pub fn clear_field(&self, m: &mut dyn MessageDyn) {
443         if self.is_singular() {
444             match self.singular() {
445                 SingularFieldAccessorRef::Generated(g) => g.accessor.clear_field(m),
446                 SingularFieldAccessorRef::Dynamic(d) => d.clear_field(m),
447             }
448         } else if self.is_repeated() {
449             self.mut_repeated(m).clear();
450         } else if self.is_map() {
451             self.mut_map(m).clear();
452         }
453     }
454 
455     /// Dynamic representation of field type with wire type.
protobuf_field_type(&self) -> ProtobufFieldType456     pub(crate) fn protobuf_field_type(&self) -> ProtobufFieldType {
457         self.index().field_type.resolve(self.file_descriptor())
458     }
459 
460     /// Dynamic representation of field type.
runtime_field_type(&self) -> RuntimeFieldType461     pub fn runtime_field_type(&self) -> RuntimeFieldType {
462         self.protobuf_field_type().runtime()
463     }
464 
465     /// Get field of any type.
466     ///
467     /// # Panics
468     ///
469     /// If this field belongs to a different message type.
get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectFieldRef<'a>470     pub fn get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectFieldRef<'a> {
471         match self.get_impl() {
472             FieldDescriptorImplRef::Generated(g) => g.get_reflect(m),
473             FieldDescriptorImplRef::Dynamic(d) => d.get_reflect(m),
474         }
475     }
476 
477     /// Get singular field value.
478     ///
479     /// Return `None` if field is unset.
480     ///
481     /// # Panics
482     ///
483     /// If this field belongs to a different message type or fields is not singular.
get_singular<'a>(&self, m: &'a dyn MessageDyn) -> Option<ReflectValueRef<'a>>484     pub fn get_singular<'a>(&self, m: &'a dyn MessageDyn) -> Option<ReflectValueRef<'a>> {
485         match self.get_reflect(m) {
486             ReflectFieldRef::Optional(o) => o.value(),
487             _ => panic!("not a singular field"),
488         }
489     }
490 
491     // repeated
492 
493     /// Get repeated field.
494     ///
495     /// # Panics
496     ///
497     /// If this field belongs to a different message type or field is not repeated.
get_repeated<'a>(&self, m: &'a dyn MessageDyn) -> ReflectRepeatedRef<'a>498     pub fn get_repeated<'a>(&self, m: &'a dyn MessageDyn) -> ReflectRepeatedRef<'a> {
499         match self.get_reflect(m) {
500             ReflectFieldRef::Repeated(r) => r,
501             _ => panic!("not a repeated field"),
502         }
503     }
504 
505     /// Get a mutable reference to `repeated` field.
506     ///
507     /// # Panics
508     ///
509     /// If this field belongs to a different message type or field is not `repeated`.
mut_repeated<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectRepeatedMut<'a>510     pub fn mut_repeated<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectRepeatedMut<'a> {
511         match self.repeated() {
512             RepeatedFieldAccessorRef::Generated(g) => g.accessor.mut_repeated(m),
513             RepeatedFieldAccessorRef::Dynamic(d) => d.mut_repeated(m),
514         }
515     }
516 
517     // map
518 
519     /// Get `map` field.
520     ///
521     /// # Panics
522     ///
523     /// If this field belongs to a different message type or field is not `map`.
get_map<'a>(&self, m: &'a dyn MessageDyn) -> ReflectMapRef<'a>524     pub fn get_map<'a>(&self, m: &'a dyn MessageDyn) -> ReflectMapRef<'a> {
525         match self.get_reflect(m) {
526             ReflectFieldRef::Map(m) => m,
527             _ => panic!("not a map field"),
528         }
529     }
530 
531     /// Get a mutable reference to `map` field.
532     ///
533     /// # Panics
534     ///
535     /// If this field belongs to a different message type or field is not `map`.
mut_map<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectMapMut<'a>536     pub fn mut_map<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectMapMut<'a> {
537         match self.map() {
538             MapFieldAccessorRef::Generated(g) => g.accessor.mut_reflect(m),
539             MapFieldAccessorRef::Dynamic(d) => d.mut_map(m),
540         }
541     }
542 }
543 
544 enum SingularFieldAccessorRef<'a> {
545     Generated(&'a SingularFieldAccessorHolder),
546     Dynamic(DynamicFieldDescriptorRef<'a>),
547 }
548 
549 enum RepeatedFieldAccessorRef<'a> {
550     Generated(&'a RepeatedFieldAccessorHolder),
551     Dynamic(DynamicFieldDescriptorRef<'a>),
552 }
553 
554 enum MapFieldAccessorRef<'a> {
555     Generated(&'a MapFieldAccessorHolder),
556     Dynamic(DynamicFieldDescriptorRef<'a>),
557 }
558 
559 pub(crate) enum FieldDescriptorImplRef<'a> {
560     Generated(&'static GeneratedFieldAccessor),
561     Dynamic(DynamicFieldDescriptorRef<'a>),
562 }
563 
564 #[cfg(test)]
565 mod test {
566     use std::collections::HashMap;
567 
568     use crate::descriptor::DescriptorProto;
569     use crate::reflect::ReflectValueBox;
570     use crate::well_known_types::struct_::Struct;
571     use crate::well_known_types::struct_::Value;
572     use crate::MessageFull;
573 
574     #[test]
575     #[cfg_attr(miri, ignore)]
display()576     fn display() {
577         let field = DescriptorProto::descriptor()
578             .field_by_name("enum_type")
579             .unwrap();
580         assert_eq!(
581             "google.protobuf.DescriptorProto.enum_type",
582             field.to_string()
583         );
584     }
585 }
586