FieldDescriptor.cs 18 KB

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