FieldDescriptor.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 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 Google.Protobuf.Collections;
  33. using Google.Protobuf.Compatibility;
  34. using System;
  35. namespace Google.Protobuf.Reflection
  36. {
  37. /// <summary>
  38. /// Descriptor for a field or extension within a message in a .proto file.
  39. /// </summary>
  40. public sealed class FieldDescriptor : DescriptorBase, IComparable<FieldDescriptor>
  41. {
  42. private EnumDescriptor enumType;
  43. private MessageDescriptor extendeeType;
  44. private MessageDescriptor messageType;
  45. private FieldType fieldType;
  46. private readonly string propertyName; // Annoyingly, needed in Crosslink.
  47. private IFieldAccessor accessor;
  48. /// <summary>
  49. /// Get the field's containing message type, or <c>null</c> if it is a field defined at the top level of a file as an extension.
  50. /// </summary>
  51. public MessageDescriptor ContainingType { get; }
  52. /// <summary>
  53. /// Returns the oneof containing this field, or <c>null</c> if it is not part of a oneof.
  54. /// </summary>
  55. public OneofDescriptor ContainingOneof { get; }
  56. /// <summary>
  57. /// The effective JSON name for this field. This is usually the lower-camel-cased form of the field name,
  58. /// but can be overridden using the <c>json_name</c> option in the .proto file.
  59. /// </summary>
  60. public string JsonName { get; }
  61. internal FieldDescriptorProto Proto { get; }
  62. internal Extension Extension { get; }
  63. internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file,
  64. MessageDescriptor parent, int index, string propertyName, Extension extension)
  65. : base(file, file.ComputeFullName(parent, proto.Name), index)
  66. {
  67. Proto = proto;
  68. if (proto.Type != 0)
  69. {
  70. fieldType = GetFieldTypeFromProtoType(proto.Type);
  71. }
  72. if (FieldNumber <= 0)
  73. {
  74. throw new DescriptorValidationException(this, "Field numbers must be positive integers.");
  75. }
  76. ContainingType = parent;
  77. if (proto.HasOneofIndex)
  78. {
  79. if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count)
  80. {
  81. throw new DescriptorValidationException(this,
  82. $"FieldDescriptorProto.oneof_index is out of range for type {parent.Name}");
  83. }
  84. ContainingOneof = parent.Oneofs[proto.OneofIndex];
  85. }
  86. file.DescriptorPool.AddSymbol(this);
  87. // We can't create the accessor until we've cross-linked, unfortunately, as we
  88. // may not know whether the type of the field is a map or not. Remember the property name
  89. // for later.
  90. // We could trust the generated code and check whether the type of the property is
  91. // a MapField, but that feels a tad nasty.
  92. this.propertyName = propertyName;
  93. Extension = extension;
  94. JsonName = Proto.JsonName == "" ? JsonFormatter.ToJsonName(Proto.Name) : Proto.JsonName;
  95. }
  96. /// <summary>
  97. /// The brief name of the descriptor's target.
  98. /// </summary>
  99. public override string Name => Proto.Name;
  100. /// <summary>
  101. /// Returns the accessor for this field.
  102. /// </summary>
  103. /// <remarks>
  104. /// <para>
  105. /// While a <see cref="FieldDescriptor"/> describes the field, it does not provide
  106. /// any way of obtaining or changing the value of the field within a specific message;
  107. /// that is the responsibility of the accessor.
  108. /// </para>
  109. /// <para>
  110. /// In descriptors for generated code, the value returned by this property will be non-null for all
  111. /// regular fields. However, if a message containing a map field is introspected, the list of nested messages will include
  112. /// an auto-generated nested key/value pair message for the field. This is not represented in any
  113. /// generated type, and the value of the map field itself is represented by a dictionary in the
  114. /// reflection API. There are never instances of those "hidden" messages, so no accessor is provided
  115. /// and this property will return null.
  116. /// </para>
  117. /// <para>
  118. /// In dynamically loaded descriptors, the value returned by this property will current be null;
  119. /// if and when dynamic messages are supported, it will return a suitable accessor to work with
  120. /// them.
  121. /// </para>
  122. /// </remarks>
  123. public IFieldAccessor Accessor => accessor;
  124. /// <summary>
  125. /// Maps a field type as included in the .proto file to a FieldType.
  126. /// </summary>
  127. private static FieldType GetFieldTypeFromProtoType(FieldDescriptorProto.Types.Type type)
  128. {
  129. switch (type)
  130. {
  131. case FieldDescriptorProto.Types.Type.Double:
  132. return FieldType.Double;
  133. case FieldDescriptorProto.Types.Type.Float:
  134. return FieldType.Float;
  135. case FieldDescriptorProto.Types.Type.Int64:
  136. return FieldType.Int64;
  137. case FieldDescriptorProto.Types.Type.Uint64:
  138. return FieldType.UInt64;
  139. case FieldDescriptorProto.Types.Type.Int32:
  140. return FieldType.Int32;
  141. case FieldDescriptorProto.Types.Type.Fixed64:
  142. return FieldType.Fixed64;
  143. case FieldDescriptorProto.Types.Type.Fixed32:
  144. return FieldType.Fixed32;
  145. case FieldDescriptorProto.Types.Type.Bool:
  146. return FieldType.Bool;
  147. case FieldDescriptorProto.Types.Type.String:
  148. return FieldType.String;
  149. case FieldDescriptorProto.Types.Type.Group:
  150. return FieldType.Group;
  151. case FieldDescriptorProto.Types.Type.Message:
  152. return FieldType.Message;
  153. case FieldDescriptorProto.Types.Type.Bytes:
  154. return FieldType.Bytes;
  155. case FieldDescriptorProto.Types.Type.Uint32:
  156. return FieldType.UInt32;
  157. case FieldDescriptorProto.Types.Type.Enum:
  158. return FieldType.Enum;
  159. case FieldDescriptorProto.Types.Type.Sfixed32:
  160. return FieldType.SFixed32;
  161. case FieldDescriptorProto.Types.Type.Sfixed64:
  162. return FieldType.SFixed64;
  163. case FieldDescriptorProto.Types.Type.Sint32:
  164. return FieldType.SInt32;
  165. case FieldDescriptorProto.Types.Type.Sint64:
  166. return FieldType.SInt64;
  167. default:
  168. throw new ArgumentException("Invalid type specified");
  169. }
  170. }
  171. /// <summary>
  172. /// Returns <c>true</c> if this field is a repeated field; <c>false</c> otherwise.
  173. /// </summary>
  174. public bool IsRepeated => Proto.Label == FieldDescriptorProto.Types.Label.Repeated;
  175. /// <summary>
  176. /// Returns <c>true</c> if this field is a required field; <c>false</c> otherwise.
  177. /// </summary>
  178. public bool IsRequired => Proto.Label == FieldDescriptorProto.Types.Label.Required;
  179. /// <summary>
  180. /// Returns <c>true</c> if this field is a map field; <c>false</c> otherwise.
  181. /// </summary>
  182. public bool IsMap => fieldType == FieldType.Message && messageType.Proto.Options != null && messageType.Proto.Options.MapEntry;
  183. /// <summary>
  184. /// Returns <c>true</c> if this field is a packed, repeated field; <c>false</c> otherwise.
  185. /// </summary>
  186. public bool IsPacked => File.Proto.Syntax == "proto2" ? Proto.Options?.Packed ?? false : !Proto.Options.HasPacked || Proto.Options.Packed;
  187. /// <summary>
  188. /// Returns the type of the field.
  189. /// </summary>
  190. public FieldType FieldType => fieldType;
  191. /// <summary>
  192. /// Returns the field number declared in the proto file.
  193. /// </summary>
  194. public int FieldNumber => Proto.Number;
  195. /// <summary>
  196. /// Compares this descriptor with another one, ordering in "canonical" order
  197. /// which simply means ascending order by field number. <paramref name="other"/>
  198. /// must be a field of the same type, i.e. the <see cref="ContainingType"/> of
  199. /// both fields must be the same.
  200. /// </summary>
  201. public int CompareTo(FieldDescriptor other)
  202. {
  203. if (other.ContainingType != ContainingType)
  204. {
  205. throw new ArgumentException("FieldDescriptors can only be compared to other FieldDescriptors " +
  206. "for fields of the same message type.");
  207. }
  208. return FieldNumber - other.FieldNumber;
  209. }
  210. /// <summary>
  211. /// For enum fields, returns the field's type.
  212. /// </summary>
  213. public EnumDescriptor EnumType
  214. {
  215. get
  216. {
  217. if (fieldType != FieldType.Enum)
  218. {
  219. throw new InvalidOperationException("EnumType is only valid for enum fields.");
  220. }
  221. return enumType;
  222. }
  223. }
  224. /// <summary>
  225. /// For embedded message and group fields, returns the field's type.
  226. /// </summary>
  227. public MessageDescriptor MessageType
  228. {
  229. get
  230. {
  231. if (fieldType != FieldType.Message && fieldType != FieldType.Group)
  232. {
  233. throw new InvalidOperationException("MessageType is only valid for message or group fields.");
  234. }
  235. return messageType;
  236. }
  237. }
  238. /// <summary>
  239. /// For extension fields, returns the extended type
  240. /// </summary>
  241. public MessageDescriptor ExtendeeType
  242. {
  243. get
  244. {
  245. if (!Proto.HasExtendee)
  246. {
  247. throw new InvalidOperationException("ExtendeeType is only valid for extension fields.");
  248. }
  249. return extendeeType;
  250. }
  251. }
  252. /// <summary>
  253. /// The (possibly empty) set of custom options for this field.
  254. /// </summary>
  255. //[Obsolete("CustomOptions are obsolete. Use GetOption")]
  256. public CustomOptions CustomOptions => Proto.Options.CustomOptions;
  257. /* // uncomment this in the full proto2 support PR
  258. /// <summary>
  259. /// Gets a single value enum option for this descriptor
  260. /// </summary>
  261. public T GetOption<T>(Extension<FieldOptions, T> extension)
  262. {
  263. var value = Proto.Options.GetExtension(extension);
  264. return value is IDeepCloneable<T> clonable ? clonable.Clone() : value;
  265. }
  266. /// <summary>
  267. /// Gets a repeated value enum option for this descriptor
  268. /// </summary>
  269. public RepeatedField<T> GetOption<T>(RepeatedExtension<FieldOptions, T> extension)
  270. {
  271. return Proto.Options.GetExtension(extension).Clone();
  272. }
  273. */
  274. /// <summary>
  275. /// Look up and cross-link all field types etc.
  276. /// </summary>
  277. internal void CrossLink()
  278. {
  279. if (Proto.HasTypeName)
  280. {
  281. IDescriptor typeDescriptor =
  282. File.DescriptorPool.LookupSymbol(Proto.TypeName, this);
  283. if (Proto.HasType)
  284. {
  285. // Choose field type based on symbol.
  286. if (typeDescriptor is MessageDescriptor)
  287. {
  288. fieldType = FieldType.Message;
  289. }
  290. else if (typeDescriptor is EnumDescriptor)
  291. {
  292. fieldType = FieldType.Enum;
  293. }
  294. else
  295. {
  296. throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not a type.");
  297. }
  298. }
  299. if (fieldType == FieldType.Message || fieldType == FieldType.Group)
  300. {
  301. if (!(typeDescriptor is MessageDescriptor))
  302. {
  303. throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not a message type.");
  304. }
  305. messageType = (MessageDescriptor) typeDescriptor;
  306. if (Proto.HasDefaultValue)
  307. {
  308. throw new DescriptorValidationException(this, "Messages can't have default values.");
  309. }
  310. }
  311. else if (fieldType == FieldType.Enum)
  312. {
  313. if (!(typeDescriptor is EnumDescriptor))
  314. {
  315. throw new DescriptorValidationException(this, $"\"{Proto.TypeName}\" is not an enum type.");
  316. }
  317. enumType = (EnumDescriptor) typeDescriptor;
  318. }
  319. else
  320. {
  321. throw new DescriptorValidationException(this, "Field with primitive type has type_name.");
  322. }
  323. }
  324. else
  325. {
  326. if (fieldType == FieldType.Message || fieldType == FieldType.Enum)
  327. {
  328. throw new DescriptorValidationException(this, "Field with message or enum type missing type_name.");
  329. }
  330. }
  331. if (Proto.HasExtendee)
  332. {
  333. extendeeType = File.DescriptorPool.LookupSymbol(Proto.Extendee, this) as MessageDescriptor;
  334. }
  335. // Note: no attempt to perform any default value parsing
  336. File.DescriptorPool.AddFieldByNumber(this);
  337. if (ContainingType != null && ContainingType.Proto.HasOptions && ContainingType.Proto.Options.MessageSetWireFormat)
  338. {
  339. throw new DescriptorValidationException(this, "MessageSet format is not supported.");
  340. }
  341. accessor = CreateAccessor();
  342. }
  343. private IFieldAccessor CreateAccessor()
  344. {
  345. // If we're given no property name, that's because we really don't want an accessor.
  346. // This could be because it's a map message, or it could be that we're loading a FileDescriptor dynamically.
  347. // TODO: Support dynamic messages.
  348. if (propertyName == null)
  349. {
  350. return null;
  351. }
  352. if (Extension != null)
  353. {
  354. return new ExtensionAccessor(this);
  355. }
  356. var property = ContainingType.ClrType.GetProperty(propertyName);
  357. if (property == null)
  358. {
  359. throw new DescriptorValidationException(this, $"Property {propertyName} not found in {ContainingType.ClrType}");
  360. }
  361. return IsMap ? new MapFieldAccessor(property, this)
  362. : IsRepeated ? new RepeatedFieldAccessor(property, this)
  363. : (IFieldAccessor) new SingleFieldAccessor(property, this);
  364. }
  365. }
  366. }