FieldDescriptor.cs 15 KB

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