MessageDescriptor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. #if DOTNET35
  37. // Needed for ReadOnlyDictionary, which does not exist in .NET 3.5
  38. using Google.Protobuf.Collections;
  39. #endif
  40. namespace Google.Protobuf.Reflection
  41. {
  42. /// <summary>
  43. /// Describes a message type.
  44. /// </summary>
  45. public sealed class MessageDescriptor : DescriptorBase
  46. {
  47. private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string>
  48. {
  49. "google/protobuf/any.proto",
  50. "google/protobuf/api.proto",
  51. "google/protobuf/duration.proto",
  52. "google/protobuf/empty.proto",
  53. "google/protobuf/wrappers.proto",
  54. "google/protobuf/timestamp.proto",
  55. "google/protobuf/field_mask.proto",
  56. "google/protobuf/source_context.proto",
  57. "google/protobuf/struct.proto",
  58. "google/protobuf/type.proto",
  59. };
  60. private readonly IList<FieldDescriptor> fieldsInDeclarationOrder;
  61. private readonly IList<FieldDescriptor> fieldsInNumberOrder;
  62. private readonly IDictionary<string, FieldDescriptor> jsonFieldMap;
  63. internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo)
  64. : base(file, file.ComputeFullName(parent, proto.Name), typeIndex)
  65. {
  66. Proto = proto;
  67. Parser = generatedCodeInfo?.Parser;
  68. ClrType = generatedCodeInfo?.ClrType;
  69. ContainingType = parent;
  70. // Note use of generatedCodeInfo. rather than generatedCodeInfo?. here... we don't expect
  71. // to see any nested oneofs, types or enums in "not actually generated" code... we do
  72. // expect fields though (for map entry messages).
  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. fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
  86. proto.Field,
  87. (field, index) =>
  88. new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index]));
  89. fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray());
  90. // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.)
  91. jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder);
  92. file.DescriptorPool.AddSymbol(this);
  93. Fields = new FieldCollection(this);
  94. }
  95. private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields)
  96. {
  97. var map = new Dictionary<string, FieldDescriptor>();
  98. foreach (var field in fields)
  99. {
  100. map[field.Name] = field;
  101. map[field.JsonName] = field;
  102. }
  103. return new ReadOnlyDictionary<string, FieldDescriptor>(map);
  104. }
  105. /// <summary>
  106. /// The brief name of the descriptor's target.
  107. /// </summary>
  108. public override string Name => Proto.Name;
  109. internal DescriptorProto Proto { get; }
  110. /// <summary>
  111. /// The CLR type used to represent message instances from this descriptor.
  112. /// </summary>
  113. /// <remarks>
  114. /// <para>
  115. /// The value returned by this property will be non-null for all regular fields. However,
  116. /// if a message containing a map field is introspected, the list of nested messages will include
  117. /// an auto-generated nested key/value pair message for the field. This is not represented in any
  118. /// generated type, so this property will return null in such cases.
  119. /// </para>
  120. /// <para>
  121. /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here
  122. /// will be the generated message type, not the native type used by reflection for fields of those types. Code
  123. /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
  124. /// a wrapper type, and handle the result appropriately.
  125. /// </para>
  126. /// </remarks>
  127. public Type ClrType { get; }
  128. /// <summary>
  129. /// A parser for this message type.
  130. /// </summary>
  131. /// <remarks>
  132. /// <para>
  133. /// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically
  134. /// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>.
  135. /// </para>
  136. /// <para>
  137. /// The value returned by this property will be non-null for all regular fields. However,
  138. /// if a message containing a map field is introspected, the list of nested messages will include
  139. /// an auto-generated nested key/value pair message for the field. No message parser object is created for
  140. /// such messages, so this property will return null in such cases.
  141. /// </para>
  142. /// <para>
  143. /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here
  144. /// will be the generated message type, not the native type used by reflection for fields of those types. Code
  145. /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
  146. /// a wrapper type, and handle the result appropriately.
  147. /// </para>
  148. /// </remarks>
  149. public MessageParser Parser { get; }
  150. /// <summary>
  151. /// Returns whether this message is one of the "well known types" which may have runtime/protoc support.
  152. /// </summary>
  153. internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name);
  154. /// <summary>
  155. /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values
  156. /// with the addition of presence.
  157. /// </summary>
  158. internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto";
  159. /// <value>
  160. /// If this is a nested type, get the outer descriptor, otherwise null.
  161. /// </value>
  162. public MessageDescriptor ContainingType { get; }
  163. /// <value>
  164. /// A collection of fields, which can be retrieved by name or field number.
  165. /// </value>
  166. public FieldCollection Fields { get; }
  167. /// <value>
  168. /// An unmodifiable list of this message type's nested types.
  169. /// </value>
  170. public IList<MessageDescriptor> NestedTypes { get; }
  171. /// <value>
  172. /// An unmodifiable list of this message type's enum types.
  173. /// </value>
  174. public IList<EnumDescriptor> EnumTypes { get; }
  175. /// <value>
  176. /// An unmodifiable list of the "oneof" field collections in this message type.
  177. /// </value>
  178. public IList<OneofDescriptor> Oneofs { get; }
  179. /// <summary>
  180. /// Finds a field by field name.
  181. /// </summary>
  182. /// <param name="name">The unqualified name of the field (e.g. "foo").</param>
  183. /// <returns>The field's descriptor, or null if not found.</returns>
  184. public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name);
  185. /// <summary>
  186. /// Finds a field by field number.
  187. /// </summary>
  188. /// <param name="number">The field number within this message type.</param>
  189. /// <returns>The field's descriptor, or null if not found.</returns>
  190. public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number);
  191. /// <summary>
  192. /// Finds a nested descriptor by name. The is valid for fields, nested
  193. /// message types, oneofs and enums.
  194. /// </summary>
  195. /// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param>
  196. /// <returns>The descriptor, or null if not found.</returns>
  197. public T FindDescriptor<T>(string name) where T : class, IDescriptor =>
  198. File.DescriptorPool.FindSymbol<T>(FullName + "." + name);
  199. /// <summary>
  200. /// Looks up and cross-links all fields and nested types.
  201. /// </summary>
  202. internal void CrossLink()
  203. {
  204. foreach (MessageDescriptor message in NestedTypes)
  205. {
  206. message.CrossLink();
  207. }
  208. foreach (FieldDescriptor field in fieldsInDeclarationOrder)
  209. {
  210. field.CrossLink();
  211. }
  212. foreach (OneofDescriptor oneof in Oneofs)
  213. {
  214. oneof.CrossLink();
  215. }
  216. }
  217. /// <summary>
  218. /// A collection to simplify retrieving the field accessor for a particular field.
  219. /// </summary>
  220. public sealed class FieldCollection
  221. {
  222. private readonly MessageDescriptor messageDescriptor;
  223. internal FieldCollection(MessageDescriptor messageDescriptor)
  224. {
  225. this.messageDescriptor = messageDescriptor;
  226. }
  227. /// <value>
  228. /// Returns the fields in the message as an immutable list, in the order in which they
  229. /// are declared in the source .proto file.
  230. /// </value>
  231. public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder;
  232. /// <value>
  233. /// Returns the fields in the message as an immutable list, in ascending field number
  234. /// order. Field numbers need not be contiguous, so there is no direct mapping from the
  235. /// index in the list to the field number; to retrieve a field by field number, it is better
  236. /// to use the <see cref="FieldCollection"/> indexer.
  237. /// </value>
  238. public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder;
  239. // TODO: consider making this public in the future. (Being conservative for now...)
  240. /// <value>
  241. /// Returns a read-only dictionary mapping the field names in this message as they're available
  242. /// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c>
  243. /// in the message would result two entries, one with a key <c>fooBar</c> and one with a key
  244. /// <c>foo_bar</c>, both referring to the same field.
  245. /// </value>
  246. internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap;
  247. /// <summary>
  248. /// Retrieves the descriptor for the field with the given number.
  249. /// </summary>
  250. /// <param name="number">Number of the field to retrieve the descriptor for</param>
  251. /// <returns>The accessor for the given field</returns>
  252. /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
  253. /// with the given number</exception>
  254. public FieldDescriptor this[int number]
  255. {
  256. get
  257. {
  258. var fieldDescriptor = messageDescriptor.FindFieldByNumber(number);
  259. if (fieldDescriptor == null)
  260. {
  261. throw new KeyNotFoundException("No such field number");
  262. }
  263. return fieldDescriptor;
  264. }
  265. }
  266. /// <summary>
  267. /// Retrieves the descriptor for the field with the given name.
  268. /// </summary>
  269. /// <param name="name">Name of the field to retrieve the descriptor for</param>
  270. /// <returns>The descriptor for the given field</returns>
  271. /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
  272. /// with the given name</exception>
  273. public FieldDescriptor this[string name]
  274. {
  275. get
  276. {
  277. var fieldDescriptor = messageDescriptor.FindFieldByName(name);
  278. if (fieldDescriptor == null)
  279. {
  280. throw new KeyNotFoundException("No such field name");
  281. }
  282. return fieldDescriptor;
  283. }
  284. }
  285. }
  286. }
  287. }