FileDescriptor.cs 16 KB

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