FileDescriptor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. namespace Google.Protobuf.Reflection
  36. {
  37. /// <summary>
  38. /// Describes a .proto file, including everything defined within.
  39. /// IDescriptor is implemented such that the File property returns this descriptor,
  40. /// and the FullName is the same as the Name.
  41. /// </summary>
  42. public sealed class FileDescriptor : IDescriptor
  43. {
  44. private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
  45. {
  46. SerializedData = descriptorData;
  47. DescriptorPool = pool;
  48. Proto = proto;
  49. Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
  50. PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
  51. pool.AddPackage(Package, this);
  52. MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
  53. (message, index) =>
  54. new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
  55. EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
  56. (enumType, index) =>
  57. new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
  58. Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
  59. (service, index) =>
  60. new ServiceDescriptor(service, this, index));
  61. }
  62. /// <summary>
  63. /// Computes the full name of a descriptor within this file, with an optional parent message.
  64. /// </summary>
  65. internal string ComputeFullName(MessageDescriptor parent, string name)
  66. {
  67. if (parent != null)
  68. {
  69. return parent.FullName + "." + name;
  70. }
  71. if (Package.Length > 0)
  72. {
  73. return Package + "." + name;
  74. }
  75. return name;
  76. }
  77. /// <summary>
  78. /// Extracts public dependencies from direct dependencies. This is a static method despite its
  79. /// first parameter, as the value we're in the middle of constructing is only used for exceptions.
  80. /// </summary>
  81. private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
  82. {
  83. var nameToFileMap = new Dictionary<string, FileDescriptor>();
  84. foreach (var file in dependencies)
  85. {
  86. nameToFileMap[file.Name] = file;
  87. }
  88. var publicDependencies = new List<FileDescriptor>();
  89. for (int i = 0; i < proto.PublicDependency.Count; i++)
  90. {
  91. int index = proto.PublicDependency[i];
  92. if (index < 0 || index >= proto.Dependency.Count)
  93. {
  94. throw new DescriptorValidationException(@this, "Invalid public dependency index.");
  95. }
  96. string name = proto.Dependency[index];
  97. FileDescriptor file = nameToFileMap[name];
  98. if (file == null)
  99. {
  100. if (!allowUnknownDependencies)
  101. {
  102. throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
  103. }
  104. // Ignore unknown dependencies.
  105. }
  106. else
  107. {
  108. publicDependencies.Add(file);
  109. }
  110. }
  111. return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
  112. }
  113. /// <value>
  114. /// The descriptor in its protocol message representation.
  115. /// </value>
  116. internal FileDescriptorProto Proto { get; }
  117. /// <value>
  118. /// The file name.
  119. /// </value>
  120. public string Name => Proto.Name;
  121. /// <summary>
  122. /// The package as declared in the .proto file. This may or may not
  123. /// be equivalent to the .NET namespace of the generated classes.
  124. /// </summary>
  125. public string Package => Proto.Package;
  126. /// <value>
  127. /// Unmodifiable list of top-level message types declared in this file.
  128. /// </value>
  129. public IList<MessageDescriptor> MessageTypes { get; }
  130. /// <value>
  131. /// Unmodifiable list of top-level enum types declared in this file.
  132. /// </value>
  133. public IList<EnumDescriptor> EnumTypes { get; }
  134. /// <value>
  135. /// Unmodifiable list of top-level services declared in this file.
  136. /// </value>
  137. public IList<ServiceDescriptor> Services { get; }
  138. /// <value>
  139. /// Unmodifiable list of this file's dependencies (imports).
  140. /// </value>
  141. public IList<FileDescriptor> Dependencies { get; }
  142. /// <value>
  143. /// Unmodifiable list of this file's public dependencies (public imports).
  144. /// </value>
  145. public IList<FileDescriptor> PublicDependencies { get; }
  146. /// <value>
  147. /// The original serialized binary form of this descriptor.
  148. /// </value>
  149. public ByteString SerializedData { get; }
  150. /// <value>
  151. /// Implementation of IDescriptor.FullName - just returns the same as Name.
  152. /// </value>
  153. string IDescriptor.FullName => Name;
  154. /// <value>
  155. /// Implementation of IDescriptor.File - just returns this descriptor.
  156. /// </value>
  157. FileDescriptor IDescriptor.File => this;
  158. /// <value>
  159. /// Pool containing symbol descriptors.
  160. /// </value>
  161. internal DescriptorPool DescriptorPool { get; }
  162. /// <summary>
  163. /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
  164. /// </summary>
  165. /// <param name="name">The unqualified type name to look for.</param>
  166. /// <typeparam name="T">The type of descriptor to look for</typeparam>
  167. /// <returns>The type's descriptor, or null if not found.</returns>
  168. public T FindTypeByName<T>(String name)
  169. where T : class, IDescriptor
  170. {
  171. // Don't allow looking up nested types. This will make optimization
  172. // easier later.
  173. if (name.IndexOf('.') != -1)
  174. {
  175. return null;
  176. }
  177. if (Package.Length > 0)
  178. {
  179. name = Package + "." + name;
  180. }
  181. T result = DescriptorPool.FindSymbol<T>(name);
  182. if (result != null && result.File == this)
  183. {
  184. return result;
  185. }
  186. return null;
  187. }
  188. /// <summary>
  189. /// Builds a FileDescriptor from its protocol buffer representation.
  190. /// </summary>
  191. /// <param name="descriptorData">The original serialized descriptor data.
  192. /// We have only limited proto2 support, so serializing FileDescriptorProto
  193. /// would not necessarily give us this.</param>
  194. /// <param name="proto">The protocol message form of the FileDescriptor.</param>
  195. /// <param name="dependencies">FileDescriptors corresponding to all of the
  196. /// file's dependencies, in the exact order listed in the .proto file. May be null,
  197. /// in which case it is treated as an empty array.</param>
  198. /// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
  199. /// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
  200. /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
  201. /// a valid descriptor. This can occur for a number of reasons, such as a field
  202. /// having an undefined type or because two messages were defined with the same name.</exception>
  203. private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
  204. {
  205. // Building descriptors involves two steps: translating and linking.
  206. // In the translation step (implemented by FileDescriptor's
  207. // constructor), we build an object tree mirroring the
  208. // FileDescriptorProto's tree and put all of the descriptors into the
  209. // DescriptorPool's lookup tables. In the linking step, we look up all
  210. // type references in the DescriptorPool, so that, for example, a
  211. // FieldDescriptor for an embedded message contains a pointer directly
  212. // to the Descriptor for that message's type. We also detect undefined
  213. // types in the linking step.
  214. if (dependencies == null)
  215. {
  216. dependencies = new FileDescriptor[0];
  217. }
  218. DescriptorPool pool = new DescriptorPool(dependencies);
  219. FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
  220. // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
  221. // need.
  222. if (dependencies.Length != proto.Dependency.Count)
  223. {
  224. throw new DescriptorValidationException(
  225. result,
  226. "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
  227. "those listed in the FileDescriptorProto.");
  228. }
  229. result.CrossLink();
  230. return result;
  231. }
  232. private void CrossLink()
  233. {
  234. foreach (MessageDescriptor message in MessageTypes)
  235. {
  236. message.CrossLink();
  237. }
  238. foreach (ServiceDescriptor service in Services)
  239. {
  240. service.CrossLink();
  241. }
  242. }
  243. /// <summary>
  244. /// Creates a descriptor for generated code.
  245. /// </summary>
  246. /// <remarks>
  247. /// This method is only designed to be used by the results of generating code with protoc,
  248. /// which creates the appropriate dependencies etc. It has to be public because the generated
  249. /// code is "external", but should not be called directly by end users.
  250. /// </remarks>
  251. public static FileDescriptor FromGeneratedCode(
  252. byte[] descriptorData,
  253. FileDescriptor[] dependencies,
  254. GeneratedClrTypeInfo generatedCodeInfo)
  255. {
  256. FileDescriptorProto proto;
  257. try
  258. {
  259. proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
  260. }
  261. catch (InvalidProtocolBufferException e)
  262. {
  263. throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
  264. }
  265. try
  266. {
  267. // When building descriptors for generated code, we allow unknown
  268. // dependencies by default.
  269. return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
  270. }
  271. catch (DescriptorValidationException e)
  272. {
  273. throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
  274. }
  275. }
  276. /// <summary>
  277. /// Returns a <see cref="System.String" /> that represents this instance.
  278. /// </summary>
  279. /// <returns>
  280. /// A <see cref="System.String" /> that represents this instance.
  281. /// </returns>
  282. public override string ToString()
  283. {
  284. return $"FileDescriptor for {Name}";
  285. }
  286. /// <summary>
  287. /// Returns the file descriptor for descriptor.proto.
  288. /// </summary>
  289. /// <remarks>
  290. /// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
  291. /// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
  292. /// runtime for reflection purposes. The messages are internal to the runtime as they would require
  293. /// proto2 semantics for full support, but the file descriptor is available via this property. The
  294. /// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
  295. /// </remarks>
  296. /// <value>
  297. /// The file descriptor for <c>descriptor.proto</c>.
  298. /// </value>
  299. public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
  300. /// <summary>
  301. /// The (possibly empty) set of custom options for this file.
  302. /// </summary>
  303. public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
  304. }
  305. }