OneofDescriptor.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Collections.ObjectModel;
  35. using System.Linq;
  36. using Google.Protobuf.Collections;
  37. using Google.Protobuf.Compatibility;
  38. namespace Google.Protobuf.Reflection
  39. {
  40. /// <summary>
  41. /// Describes a "oneof" field collection in a message type: a set of
  42. /// fields of which at most one can be set in any particular message.
  43. /// </summary>
  44. public sealed class OneofDescriptor : DescriptorBase
  45. {
  46. private readonly OneofDescriptorProto proto;
  47. private MessageDescriptor containingType;
  48. private IList<FieldDescriptor> fields;
  49. private readonly OneofAccessor accessor;
  50. internal OneofDescriptor(OneofDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string clrName)
  51. : base(file, file.ComputeFullName(parent, proto.Name), index)
  52. {
  53. this.proto = proto;
  54. containingType = parent;
  55. file.DescriptorPool.AddSymbol(this);
  56. // It's useful to determine whether or not this is a synthetic oneof before cross-linking. That means
  57. // diving into the proto directly rather than using FieldDescriptor, but that's okay.
  58. var firstFieldInOneof = parent.Proto.Field.FirstOrDefault(fieldProto => fieldProto.OneofIndex == index);
  59. IsSynthetic = firstFieldInOneof?.Proto3Optional ?? false;
  60. accessor = CreateAccessor(clrName);
  61. }
  62. /// <summary>
  63. /// The brief name of the descriptor's target.
  64. /// </summary>
  65. public override string Name { get { return proto.Name; } }
  66. /// <summary>
  67. /// Gets the message type containing this oneof.
  68. /// </summary>
  69. /// <value>
  70. /// The message type containing this oneof.
  71. /// </value>
  72. public MessageDescriptor ContainingType
  73. {
  74. get { return containingType; }
  75. }
  76. /// <summary>
  77. /// Gets the fields within this oneof, in declaration order.
  78. /// </summary>
  79. /// <value>
  80. /// The fields within this oneof, in declaration order.
  81. /// </value>
  82. public IList<FieldDescriptor> Fields { get { return fields; } }
  83. /// <summary>
  84. /// Returns <c>true</c> if this oneof is a synthetic oneof containing a proto3 optional field;
  85. /// <c>false</c> otherwise.
  86. /// </summary>
  87. public bool IsSynthetic { get; }
  88. /// <summary>
  89. /// Gets an accessor for reflective access to the values associated with the oneof
  90. /// in a particular message.
  91. /// </summary>
  92. /// <remarks>
  93. /// <para>
  94. /// In descriptors for generated code, the value returned by this property will always be non-null.
  95. /// </para>
  96. /// <para>
  97. /// In dynamically loaded descriptors, the value returned by this property will current be null;
  98. /// if and when dynamic messages are supported, it will return a suitable accessor to work with
  99. /// them.
  100. /// </para>
  101. /// </remarks>
  102. /// <value>
  103. /// The accessor used for reflective access.
  104. /// </value>
  105. public OneofAccessor Accessor { get { return accessor; } }
  106. /// <summary>
  107. /// The (possibly empty) set of custom options for this oneof.
  108. /// </summary>
  109. [Obsolete("CustomOptions are obsolete. Use GetOption")]
  110. public CustomOptions CustomOptions => new CustomOptions(proto.Options?._extensions?.ValuesByNumber);
  111. /// <summary>
  112. /// Gets a single value oneof option for this descriptor
  113. /// </summary>
  114. public T GetOption<T>(Extension<OneofOptions, T> extension)
  115. {
  116. var value = proto.Options.GetExtension(extension);
  117. return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value;
  118. }
  119. /// <summary>
  120. /// Gets a repeated value oneof option for this descriptor
  121. /// </summary>
  122. public RepeatedField<T> GetOption<T>(RepeatedExtension<OneofOptions, T> extension)
  123. {
  124. return proto.Options.GetExtension(extension).Clone();
  125. }
  126. internal void CrossLink()
  127. {
  128. List<FieldDescriptor> fieldCollection = new List<FieldDescriptor>();
  129. foreach (var field in ContainingType.Fields.InDeclarationOrder())
  130. {
  131. if (field.ContainingOneof == this)
  132. {
  133. fieldCollection.Add(field);
  134. }
  135. }
  136. fields = new ReadOnlyCollection<FieldDescriptor>(fieldCollection);
  137. }
  138. private OneofAccessor CreateAccessor(string clrName)
  139. {
  140. // We won't have a CLR name if this is from a dynamically-loaded FileDescriptor.
  141. // TODO: Support dynamic messages.
  142. if (clrName == null)
  143. {
  144. return null;
  145. }
  146. if (IsSynthetic)
  147. {
  148. return OneofAccessor.ForSyntheticOneof(this);
  149. }
  150. else
  151. {
  152. var caseProperty = containingType.ClrType.GetProperty(clrName + "Case");
  153. if (caseProperty == null)
  154. {
  155. throw new DescriptorValidationException(this, $"Property {clrName}Case not found in {containingType.ClrType}");
  156. }
  157. if (!caseProperty.CanRead)
  158. {
  159. throw new ArgumentException($"Cannot read from property {clrName}Case in {containingType.ClrType}");
  160. }
  161. var clearMethod = containingType.ClrType.GetMethod("Clear" + clrName);
  162. if (clearMethod == null)
  163. {
  164. throw new DescriptorValidationException(this, $"Method Clear{clrName} not found in {containingType.ClrType}");
  165. }
  166. return OneofAccessor.ForRegularOneof(this, caseProperty, clearMethod);
  167. }
  168. }
  169. }
  170. }