MessageDescriptor.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 System;
  33. using System.Collections.Generic;
  34. using System.Collections.ObjectModel;
  35. using System.Linq;
  36. using System.Reflection;
  37. #if NET35
  38. // Needed for ReadOnlyDictionary, which does not exist in .NET 3.5
  39. using Google.Protobuf.Collections;
  40. #endif
  41. namespace Google.Protobuf.Reflection
  42. {
  43. /// <summary>
  44. /// Describes a message type.
  45. /// </summary>
  46. public sealed class MessageDescriptor : DescriptorBase
  47. {
  48. private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string>
  49. {
  50. "google/protobuf/any.proto",
  51. "google/protobuf/api.proto",
  52. "google/protobuf/duration.proto",
  53. "google/protobuf/empty.proto",
  54. "google/protobuf/wrappers.proto",
  55. "google/protobuf/timestamp.proto",
  56. "google/protobuf/field_mask.proto",
  57. "google/protobuf/source_context.proto",
  58. "google/protobuf/struct.proto",
  59. "google/protobuf/type.proto",
  60. };
  61. private readonly IList<FieldDescriptor> fieldsInDeclarationOrder;
  62. private readonly IList<FieldDescriptor> fieldsInNumberOrder;
  63. private readonly IDictionary<string, FieldDescriptor> jsonFieldMap;
  64. private Func<IMessage, bool> extensionSetIsInitialized;
  65. internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo)
  66. : base(file, file.ComputeFullName(parent, proto.Name), typeIndex)
  67. {
  68. Proto = proto;
  69. Parser = generatedCodeInfo?.Parser;
  70. ClrType = generatedCodeInfo?.ClrType;
  71. ContainingType = parent;
  72. // If generatedCodeInfo is null, we just won't generate an accessor for any fields.
  73. Oneofs = DescriptorUtil.ConvertAndMakeReadOnly(
  74. proto.OneofDecl,
  75. (oneof, index) =>
  76. new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index]));
  77. NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
  78. proto.NestedType,
  79. (type, index) =>
  80. new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index]));
  81. EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(
  82. proto.EnumType,
  83. (type, index) =>
  84. new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index]));
  85. Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions);
  86. fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
  87. proto.Field,
  88. (field, index) =>
  89. new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null));
  90. fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray());
  91. // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.)
  92. jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder);
  93. file.DescriptorPool.AddSymbol(this);
  94. Fields = new FieldCollection(this);
  95. }
  96. private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields)
  97. {
  98. var map = new Dictionary<string, FieldDescriptor>();
  99. foreach (var field in fields)
  100. {
  101. map[field.Name] = field;
  102. map[field.JsonName] = field;
  103. }
  104. return new ReadOnlyDictionary<string, FieldDescriptor>(map);
  105. }
  106. /// <summary>
  107. /// The brief name of the descriptor's target.
  108. /// </summary>
  109. public override string Name => Proto.Name;
  110. internal override IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber)
  111. {
  112. switch (fieldNumber)
  113. {
  114. case DescriptorProto.FieldFieldNumber:
  115. return (IReadOnlyList<DescriptorBase>) fieldsInDeclarationOrder;
  116. case DescriptorProto.NestedTypeFieldNumber:
  117. return (IReadOnlyList<DescriptorBase>) NestedTypes;
  118. case DescriptorProto.EnumTypeFieldNumber:
  119. return (IReadOnlyList<DescriptorBase>) EnumTypes;
  120. default:
  121. return null;
  122. }
  123. }
  124. internal DescriptorProto Proto { get; }
  125. internal bool IsExtensionsInitialized(IMessage message)
  126. {
  127. if (Proto.ExtensionRange.Count == 0)
  128. {
  129. return true;
  130. }
  131. if (extensionSetIsInitialized == null)
  132. {
  133. extensionSetIsInitialized = ReflectionUtil.CreateIsInitializedCaller(ClrType);
  134. }
  135. return extensionSetIsInitialized(message);
  136. }
  137. /// <summary>
  138. /// The CLR type used to represent message instances from this descriptor.
  139. /// </summary>
  140. /// <remarks>
  141. /// <para>
  142. /// The value returned by this property will be non-null for all regular fields. However,
  143. /// if a message containing a map field is introspected, the list of nested messages will include
  144. /// an auto-generated nested key/value pair message for the field. This is not represented in any
  145. /// generated type, so this property will return null in such cases.
  146. /// </para>
  147. /// <para>
  148. /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here
  149. /// will be the generated message type, not the native type used by reflection for fields of those types. Code
  150. /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
  151. /// a wrapper type, and handle the result appropriately.
  152. /// </para>
  153. /// </remarks>
  154. public Type ClrType { get; }
  155. /// <summary>
  156. /// A parser for this message type.
  157. /// </summary>
  158. /// <remarks>
  159. /// <para>
  160. /// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically
  161. /// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>.
  162. /// </para>
  163. /// <para>
  164. /// The value returned by this property will be non-null for all regular fields. However,
  165. /// if a message containing a map field is introspected, the list of nested messages will include
  166. /// an auto-generated nested key/value pair message for the field. No message parser object is created for
  167. /// such messages, so this property will return null in such cases.
  168. /// </para>
  169. /// <para>
  170. /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here
  171. /// will be the generated message type, not the native type used by reflection for fields of those types. Code
  172. /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
  173. /// a wrapper type, and handle the result appropriately.
  174. /// </para>
  175. /// </remarks>
  176. public MessageParser Parser { get; }
  177. /// <summary>
  178. /// Returns whether this message is one of the "well known types" which may have runtime/protoc support.
  179. /// </summary>
  180. internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name);
  181. /// <summary>
  182. /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values
  183. /// with the addition of presence.
  184. /// </summary>
  185. internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto";
  186. /// <value>
  187. /// If this is a nested type, get the outer descriptor, otherwise null.
  188. /// </value>
  189. public MessageDescriptor ContainingType { get; }
  190. /// <value>
  191. /// A collection of fields, which can be retrieved by name or field number.
  192. /// </value>
  193. public FieldCollection Fields { get; }
  194. /// <summary>
  195. /// An unmodifiable list of extensions defined in this message's scope.
  196. /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null)
  197. /// if they are declared in a file generated using a version of protoc that did not fully
  198. /// support extensions in C#.
  199. /// </summary>
  200. public ExtensionCollection Extensions { get; }
  201. /// <value>
  202. /// An unmodifiable list of this message type's nested types.
  203. /// </value>
  204. public IList<MessageDescriptor> NestedTypes { get; }
  205. /// <value>
  206. /// An unmodifiable list of this message type's enum types.
  207. /// </value>
  208. public IList<EnumDescriptor> EnumTypes { get; }
  209. /// <value>
  210. /// An unmodifiable list of the "oneof" field collections in this message type.
  211. /// </value>
  212. public IList<OneofDescriptor> Oneofs { get; }
  213. /// <summary>
  214. /// Finds a field by field name.
  215. /// </summary>
  216. /// <param name="name">The unqualified name of the field (e.g. "foo").</param>
  217. /// <returns>The field's descriptor, or null if not found.</returns>
  218. public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name);
  219. /// <summary>
  220. /// Finds a field by field number.
  221. /// </summary>
  222. /// <param name="number">The field number within this message type.</param>
  223. /// <returns>The field's descriptor, or null if not found.</returns>
  224. public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number);
  225. /// <summary>
  226. /// Finds a nested descriptor by name. The is valid for fields, nested
  227. /// message types, oneofs and enums.
  228. /// </summary>
  229. /// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param>
  230. /// <returns>The descriptor, or null if not found.</returns>
  231. public T FindDescriptor<T>(string name) where T : class, IDescriptor =>
  232. File.DescriptorPool.FindSymbol<T>(FullName + "." + name);
  233. /// <summary>
  234. /// The (possibly empty) set of custom options for this message.
  235. /// </summary>
  236. [Obsolete("CustomOptions are obsolete. Use GetOption")]
  237. public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
  238. /// <summary>
  239. /// Gets a single value message option for this descriptor
  240. /// </summary>
  241. public T GetOption<T>(Extension<MessageOptions, T> extension)
  242. {
  243. var value = Proto.Options.GetExtension(extension);
  244. return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value;
  245. }
  246. /// <summary>
  247. /// Gets a repeated value message option for this descriptor
  248. /// </summary>
  249. public Collections.RepeatedField<T> GetOption<T>(RepeatedExtension<MessageOptions, T> extension)
  250. {
  251. return Proto.Options.GetExtension(extension).Clone();
  252. }
  253. /// <summary>
  254. /// Looks up and cross-links all fields and nested types.
  255. /// </summary>
  256. internal void CrossLink()
  257. {
  258. foreach (MessageDescriptor message in NestedTypes)
  259. {
  260. message.CrossLink();
  261. }
  262. foreach (FieldDescriptor field in fieldsInDeclarationOrder)
  263. {
  264. field.CrossLink();
  265. }
  266. foreach (OneofDescriptor oneof in Oneofs)
  267. {
  268. oneof.CrossLink();
  269. }
  270. Extensions.CrossLink();
  271. }
  272. /// <summary>
  273. /// A collection to simplify retrieving the field accessor for a particular field.
  274. /// </summary>
  275. public sealed class FieldCollection
  276. {
  277. private readonly MessageDescriptor messageDescriptor;
  278. internal FieldCollection(MessageDescriptor messageDescriptor)
  279. {
  280. this.messageDescriptor = messageDescriptor;
  281. }
  282. /// <value>
  283. /// Returns the fields in the message as an immutable list, in the order in which they
  284. /// are declared in the source .proto file.
  285. /// </value>
  286. public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder;
  287. /// <value>
  288. /// Returns the fields in the message as an immutable list, in ascending field number
  289. /// order. Field numbers need not be contiguous, so there is no direct mapping from the
  290. /// index in the list to the field number; to retrieve a field by field number, it is better
  291. /// to use the <see cref="FieldCollection"/> indexer.
  292. /// </value>
  293. public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder;
  294. // TODO: consider making this public in the future. (Being conservative for now...)
  295. /// <value>
  296. /// Returns a read-only dictionary mapping the field names in this message as they're available
  297. /// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c>
  298. /// in the message would result two entries, one with a key <c>fooBar</c> and one with a key
  299. /// <c>foo_bar</c>, both referring to the same field.
  300. /// </value>
  301. internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap;
  302. /// <summary>
  303. /// Retrieves the descriptor for the field with the given number.
  304. /// </summary>
  305. /// <param name="number">Number of the field to retrieve the descriptor for</param>
  306. /// <returns>The accessor for the given field</returns>
  307. /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
  308. /// with the given number</exception>
  309. public FieldDescriptor this[int number]
  310. {
  311. get
  312. {
  313. var fieldDescriptor = messageDescriptor.FindFieldByNumber(number);
  314. if (fieldDescriptor == null)
  315. {
  316. throw new KeyNotFoundException("No such field number");
  317. }
  318. return fieldDescriptor;
  319. }
  320. }
  321. /// <summary>
  322. /// Retrieves the descriptor for the field with the given name.
  323. /// </summary>
  324. /// <param name="name">Name of the field to retrieve the descriptor for</param>
  325. /// <returns>The descriptor for the given field</returns>
  326. /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
  327. /// with the given name</exception>
  328. public FieldDescriptor this[string name]
  329. {
  330. get
  331. {
  332. var fieldDescriptor = messageDescriptor.FindFieldByName(name);
  333. if (fieldDescriptor == null)
  334. {
  335. throw new KeyNotFoundException("No such field name");
  336. }
  337. return fieldDescriptor;
  338. }
  339. }
  340. }
  341. }
  342. }