PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/src/ProtocolBuffers/Descriptors/FileDescriptor.cs

https://code.google.com/p/protobuf-csharp-port/
C# | 496 lines | 304 code | 47 blank | 145 comment | 37 complexity | f91082e6dd85f054b1ee5c989b4b1271 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-2.0
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://github.com/jskeet/dotnet-protobufs/
  4. // Original C++/Java/Python code:
  5. // http://code.google.com/p/protobuf/
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following disclaimer
  15. // in the documentation and/or other materials provided with the
  16. // distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived from
  19. // this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Collections.ObjectModel;
  35. using System.IO;
  36. using Google.ProtocolBuffers.DescriptorProtos;
  37. using FileOptions = Google.ProtocolBuffers.DescriptorProtos.FileOptions;
  38. namespace Google.ProtocolBuffers.Descriptors
  39. {
  40. /// <summary>
  41. /// Describes a .proto file, including everything defined within.
  42. /// IDescriptor is implemented such that the File property returns this descriptor,
  43. /// and the FullName is the same as the Name.
  44. /// </summary>
  45. public sealed class FileDescriptor : IDescriptor<FileDescriptorProto>
  46. {
  47. private FileDescriptorProto proto;
  48. private readonly IList<MessageDescriptor> messageTypes;
  49. private readonly IList<EnumDescriptor> enumTypes;
  50. private readonly IList<ServiceDescriptor> services;
  51. private readonly IList<FieldDescriptor> extensions;
  52. private readonly IList<FileDescriptor> dependencies;
  53. private readonly DescriptorPool pool;
  54. private CSharpFileOptions csharpFileOptions;
  55. private readonly object optionsLock = new object();
  56. private FileDescriptor(FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool)
  57. {
  58. this.pool = pool;
  59. this.proto = proto;
  60. this.dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
  61. pool.AddPackage(Package, this);
  62. messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList,
  63. (message, index) =>
  64. new MessageDescriptor(message, this, null, index));
  65. enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList,
  66. (enumType, index) =>
  67. new EnumDescriptor(enumType, this, null, index));
  68. services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList,
  69. (service, index) =>
  70. new ServiceDescriptor(service, this, index));
  71. extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList,
  72. (field, index) =>
  73. new FieldDescriptor(field, this, null, index, true));
  74. }
  75. /// <summary>
  76. /// Allows a file descriptor to be configured with a set of external options, e.g. from the
  77. /// command-line arguments to protogen.
  78. /// </summary>
  79. public void ConfigureWithDefaultOptions(CSharpFileOptions options)
  80. {
  81. csharpFileOptions = BuildOrFakeWithDefaultOptions(options);
  82. }
  83. private CSharpFileOptions BuildOrFakeWithDefaultOptions(CSharpFileOptions defaultOptions)
  84. {
  85. // Fix for being able to relocate these files to any directory structure
  86. if (proto.Package == "google.protobuf")
  87. {
  88. string filename = Path.GetFileName(proto.Name);
  89. // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues)
  90. if (filename == "descriptor.proto")
  91. {
  92. return new CSharpFileOptions.Builder
  93. {
  94. Namespace = "Google.ProtocolBuffers.DescriptorProtos",
  95. UmbrellaClassname = "DescriptorProtoFile",
  96. NestClasses = false,
  97. MultipleFiles = false,
  98. PublicClasses = true,
  99. OutputDirectory = defaultOptions.OutputDirectory,
  100. IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf
  101. }.Build();
  102. }
  103. if (filename == "csharp_options.proto")
  104. {
  105. return new CSharpFileOptions.Builder
  106. {
  107. Namespace = "Google.ProtocolBuffers.DescriptorProtos",
  108. UmbrellaClassname = "CSharpOptions",
  109. NestClasses = false,
  110. MultipleFiles = false,
  111. PublicClasses = true,
  112. OutputDirectory = defaultOptions.OutputDirectory,
  113. IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf
  114. }.Build();
  115. }
  116. }
  117. CSharpFileOptions.Builder builder = defaultOptions.ToBuilder();
  118. if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions))
  119. {
  120. builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions));
  121. }
  122. if (!builder.HasNamespace)
  123. {
  124. builder.Namespace = Package;
  125. }
  126. if (!builder.HasUmbrellaClassname)
  127. {
  128. int lastSlash = Name.LastIndexOf('/');
  129. string baseName = Name.Substring(lastSlash + 1);
  130. builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName));
  131. }
  132. // Auto-fix for name collision by placing umbrella class into a new namespace. This
  133. // still won't fix the collisions with nesting enabled; however, you have to turn that on explicitly anyway.
  134. if (!builder.NestClasses && !builder.HasUmbrellaNamespace)
  135. {
  136. bool collision = false;
  137. foreach (IDescriptor d in MessageTypes)
  138. {
  139. collision |= d.Name == builder.UmbrellaClassname;
  140. }
  141. foreach (IDescriptor d in Services)
  142. {
  143. collision |= d.Name == builder.UmbrellaClassname;
  144. }
  145. foreach (IDescriptor d in EnumTypes)
  146. {
  147. collision |= d.Name == builder.UmbrellaClassname;
  148. }
  149. if (collision)
  150. {
  151. builder.UmbrellaNamespace = "Proto";
  152. }
  153. }
  154. return builder.Build();
  155. }
  156. /// <value>
  157. /// The descriptor in its protocol message representation.
  158. /// </value>
  159. public FileDescriptorProto Proto
  160. {
  161. get { return proto; }
  162. }
  163. /// <value>
  164. /// The <see cref="DescriptorProtos.FileOptions" /> defined in <c>descriptor.proto</c>.
  165. /// </value>
  166. public FileOptions Options
  167. {
  168. get { return proto.Options; }
  169. }
  170. /// <summary>
  171. /// Returns the C#-specific options for this file descriptor. This will always be
  172. /// completely filled in.
  173. /// </summary>
  174. public CSharpFileOptions CSharpOptions
  175. {
  176. get
  177. {
  178. lock (optionsLock)
  179. {
  180. if (csharpFileOptions == null)
  181. {
  182. csharpFileOptions = BuildOrFakeWithDefaultOptions(CSharpFileOptions.DefaultInstance);
  183. }
  184. }
  185. return csharpFileOptions;
  186. }
  187. }
  188. /// <value>
  189. /// The file name.
  190. /// </value>
  191. public string Name
  192. {
  193. get { return proto.Name; }
  194. }
  195. /// <summary>
  196. /// The package as declared in the .proto file. This may or may not
  197. /// be equivalent to the .NET namespace of the generated classes.
  198. /// </summary>
  199. public string Package
  200. {
  201. get { return proto.Package; }
  202. }
  203. /// <value>
  204. /// Unmodifiable list of top-level message types declared in this file.
  205. /// </value>
  206. public IList<MessageDescriptor> MessageTypes
  207. {
  208. get { return messageTypes; }
  209. }
  210. /// <value>
  211. /// Unmodifiable list of top-level enum types declared in this file.
  212. /// </value>
  213. public IList<EnumDescriptor> EnumTypes
  214. {
  215. get { return enumTypes; }
  216. }
  217. /// <value>
  218. /// Unmodifiable list of top-level services declared in this file.
  219. /// </value>
  220. public IList<ServiceDescriptor> Services
  221. {
  222. get { return services; }
  223. }
  224. /// <value>
  225. /// Unmodifiable list of top-level extensions declared in this file.
  226. /// </value>
  227. public IList<FieldDescriptor> Extensions
  228. {
  229. get { return extensions; }
  230. }
  231. /// <value>
  232. /// Unmodifiable list of this file's dependencies (imports).
  233. /// </value>
  234. public IList<FileDescriptor> Dependencies
  235. {
  236. get { return dependencies; }
  237. }
  238. /// <value>
  239. /// Implementation of IDescriptor.FullName - just returns the same as Name.
  240. /// </value>
  241. string IDescriptor.FullName
  242. {
  243. get { return Name; }
  244. }
  245. /// <value>
  246. /// Implementation of IDescriptor.File - just returns this descriptor.
  247. /// </value>
  248. FileDescriptor IDescriptor.File
  249. {
  250. get { return this; }
  251. }
  252. /// <value>
  253. /// Protocol buffer describing this descriptor.
  254. /// </value>
  255. IMessage IDescriptor.Proto
  256. {
  257. get { return Proto; }
  258. }
  259. /// <value>
  260. /// Pool containing symbol descriptors.
  261. /// </value>
  262. internal DescriptorPool DescriptorPool
  263. {
  264. get { return pool; }
  265. }
  266. /// <summary>
  267. /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
  268. /// </summary>
  269. /// <param name="name">The unqualified type name to look for.</param>
  270. /// <typeparam name="T">The type of descriptor to look for (or ITypeDescriptor for any)</typeparam>
  271. /// <returns>The type's descriptor, or null if not found.</returns>
  272. public T FindTypeByName<T>(String name)
  273. where T : class, IDescriptor
  274. {
  275. // Don't allow looking up nested types. This will make optimization
  276. // easier later.
  277. if (name.IndexOf('.') != -1)
  278. {
  279. return null;
  280. }
  281. if (Package.Length > 0)
  282. {
  283. name = Package + "." + name;
  284. }
  285. T result = pool.FindSymbol<T>(name);
  286. if (result != null && result.File == this)
  287. {
  288. return result;
  289. }
  290. return null;
  291. }
  292. /// <summary>
  293. /// Builds a FileDescriptor from its protocol buffer representation.
  294. /// </summary>
  295. /// <param name="proto">The protocol message form of the FileDescriptor.</param>
  296. /// <param name="dependencies">FileDescriptors corresponding to all of the
  297. /// file's dependencies, in the exact order listed in the .proto file. May be null,
  298. /// in which case it is treated as an empty array.</param>
  299. /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
  300. /// a valid descriptor. This can occur for a number of reasons, such as a field
  301. /// having an undefined type or because two messages were defined with the same name.</exception>
  302. public static FileDescriptor BuildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies)
  303. {
  304. // Building descriptors involves two steps: translating and linking.
  305. // In the translation step (implemented by FileDescriptor's
  306. // constructor), we build an object tree mirroring the
  307. // FileDescriptorProto's tree and put all of the descriptors into the
  308. // DescriptorPool's lookup tables. In the linking step, we look up all
  309. // type references in the DescriptorPool, so that, for example, a
  310. // FieldDescriptor for an embedded message contains a pointer directly
  311. // to the Descriptor for that message's type. We also detect undefined
  312. // types in the linking step.
  313. if (dependencies == null)
  314. {
  315. dependencies = new FileDescriptor[0];
  316. }
  317. DescriptorPool pool = new DescriptorPool(dependencies);
  318. FileDescriptor result = new FileDescriptor(proto, dependencies, pool);
  319. if (dependencies.Length != proto.DependencyCount)
  320. {
  321. throw new DescriptorValidationException(result,
  322. "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
  323. "those listed in the FileDescriptorProto.");
  324. }
  325. for (int i = 0; i < proto.DependencyCount; i++)
  326. {
  327. if (dependencies[i].Name != proto.DependencyList[i])
  328. {
  329. throw new DescriptorValidationException(result,
  330. "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
  331. "those listed in the FileDescriptorProto.");
  332. }
  333. }
  334. result.CrossLink();
  335. return result;
  336. }
  337. private void CrossLink()
  338. {
  339. foreach (MessageDescriptor message in messageTypes)
  340. {
  341. message.CrossLink();
  342. }
  343. foreach (ServiceDescriptor service in services)
  344. {
  345. service.CrossLink();
  346. }
  347. foreach (FieldDescriptor extension in extensions)
  348. {
  349. extension.CrossLink();
  350. }
  351. foreach (MessageDescriptor message in messageTypes)
  352. {
  353. message.CheckRequiredFields();
  354. }
  355. }
  356. /// <summary>
  357. /// This method is to be called by generated code only. It is equivalent
  358. /// to BuildFrom except that the FileDescriptorProto is encoded in
  359. /// protocol buffer wire format. This overload is maintained for backward
  360. /// compatibility with source code generated before the custom options were available
  361. /// (and working).
  362. /// </summary>
  363. public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, FileDescriptor[] dependencies)
  364. {
  365. return InternalBuildGeneratedFileFrom(descriptorData, dependencies, x => null);
  366. }
  367. /// <summary>
  368. /// This delegate should be used by generated code only. When calling
  369. /// FileDescriptor.InternalBuildGeneratedFileFrom, the caller can provide
  370. /// a callback which assigns the global variables defined in the generated code
  371. /// which point at parts of the FileDescriptor. The callback returns an
  372. /// Extension Registry which contains any extensions which might be used in
  373. /// the descriptor - that is, extensions of the various "Options" messages defined
  374. /// in descriptor.proto. The callback may also return null to indicate that
  375. /// no extensions are used in the descriptor.
  376. /// </summary>
  377. /// <param name="descriptor"></param>
  378. /// <returns></returns>
  379. public delegate ExtensionRegistry InternalDescriptorAssigner(FileDescriptor descriptor);
  380. public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData,
  381. FileDescriptor[] dependencies,
  382. InternalDescriptorAssigner descriptorAssigner)
  383. {
  384. FileDescriptorProto proto;
  385. try
  386. {
  387. proto = FileDescriptorProto.ParseFrom(descriptorData);
  388. }
  389. catch (InvalidProtocolBufferException e)
  390. {
  391. throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
  392. }
  393. FileDescriptor result;
  394. try
  395. {
  396. result = BuildFrom(proto, dependencies);
  397. }
  398. catch (DescriptorValidationException e)
  399. {
  400. throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e);
  401. }
  402. ExtensionRegistry registry = descriptorAssigner(result);
  403. if (registry != null)
  404. {
  405. // We must re-parse the proto using the registry.
  406. try
  407. {
  408. proto = FileDescriptorProto.ParseFrom(descriptorData, registry);
  409. }
  410. catch (InvalidProtocolBufferException e)
  411. {
  412. throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
  413. }
  414. result.ReplaceProto(proto);
  415. }
  416. return result;
  417. }
  418. /// <summary>
  419. /// Replace our FileDescriptorProto with the given one, which is
  420. /// identical except that it might contain extensions that weren't present
  421. /// in the original. This method is needed for bootstrapping when a file
  422. /// defines custom options. The options may be defined in the file itself,
  423. /// so we can't actually parse them until we've constructed the descriptors,
  424. /// but to construct the decsriptors we have to have parsed the descriptor
  425. /// protos. So, we have to parse the descriptor protos a second time after
  426. /// constructing the descriptors.
  427. /// </summary>
  428. private void ReplaceProto(FileDescriptorProto newProto)
  429. {
  430. proto = newProto;
  431. for (int i = 0; i < messageTypes.Count; i++)
  432. {
  433. messageTypes[i].ReplaceProto(proto.GetMessageType(i));
  434. }
  435. for (int i = 0; i < enumTypes.Count; i++)
  436. {
  437. enumTypes[i].ReplaceProto(proto.GetEnumType(i));
  438. }
  439. for (int i = 0; i < services.Count; i++)
  440. {
  441. services[i].ReplaceProto(proto.GetService(i));
  442. }
  443. for (int i = 0; i < extensions.Count; i++)
  444. {
  445. extensions[i].ReplaceProto(proto.GetExtension(i));
  446. }
  447. }
  448. }
  449. }