MessageDescriptor.cs 18 KB

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