FileDescriptor.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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 Google.Protobuf.Collections;
  33. using Google.Protobuf.WellKnownTypes;
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Collections.ObjectModel;
  37. using System.Diagnostics;
  38. using System.Linq;
  39. using System.Threading;
  40. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  41. namespace Google.Protobuf.Reflection
  42. {
  43. /// <summary>
  44. /// The syntax of a .proto file
  45. /// </summary>
  46. public enum Syntax
  47. {
  48. /// <summary>
  49. /// Proto2 syntax
  50. /// </summary>
  51. Proto2,
  52. /// <summary>
  53. /// Proto3 syntax
  54. /// </summary>
  55. Proto3,
  56. /// <summary>
  57. /// An unknown declared syntax
  58. /// </summary>
  59. Unknown
  60. }
  61. /// <summary>
  62. /// Describes a .proto file, including everything defined within.
  63. /// IDescriptor is implemented such that the File property returns this descriptor,
  64. /// and the FullName is the same as the Name.
  65. /// </summary>
  66. public sealed class FileDescriptor : IDescriptor
  67. {
  68. // Prevent linker failures when using IL2CPP with the well-known types.
  69. static FileDescriptor()
  70. {
  71. ForceReflectionInitialization<Syntax>();
  72. ForceReflectionInitialization<NullValue>();
  73. ForceReflectionInitialization<Field.Types.Cardinality>();
  74. ForceReflectionInitialization<Field.Types.Kind>();
  75. ForceReflectionInitialization<Value.KindOneofCase>();
  76. }
  77. private readonly Lazy<Dictionary<IDescriptor, DescriptorDeclaration>> declarations;
  78. private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
  79. {
  80. SerializedData = descriptorData;
  81. DescriptorPool = pool;
  82. Proto = proto;
  83. Dependencies = new ReadOnlyCollection<FileDescriptor>(dependencies.ToList());
  84. PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
  85. pool.AddPackage(Package, this);
  86. MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
  87. (message, index) =>
  88. new MessageDescriptor(message, this, null, index, generatedCodeInfo?.NestedTypes[index]));
  89. EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
  90. (enumType, index) =>
  91. new EnumDescriptor(enumType, this, null, index, generatedCodeInfo?.NestedEnums[index]));
  92. Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
  93. (service, index) =>
  94. new ServiceDescriptor(service, this, index));
  95. Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions);
  96. declarations = new Lazy<Dictionary<IDescriptor, DescriptorDeclaration>>(CreateDeclarationMap, LazyThreadSafetyMode.ExecutionAndPublication);
  97. if (!proto.HasSyntax || proto.Syntax == "proto2")
  98. {
  99. Syntax = Syntax.Proto2;
  100. }
  101. else if (proto.Syntax == "proto3")
  102. {
  103. Syntax = Syntax.Proto3;
  104. }
  105. else
  106. {
  107. Syntax = Syntax.Unknown;
  108. }
  109. }
  110. private Dictionary<IDescriptor, DescriptorDeclaration> CreateDeclarationMap()
  111. {
  112. var dictionary = new Dictionary<IDescriptor, DescriptorDeclaration>();
  113. foreach (var location in Proto.SourceCodeInfo?.Location ?? Enumerable.Empty<Location>())
  114. {
  115. var descriptor = FindDescriptorForPath(location.Path);
  116. if (descriptor != null)
  117. {
  118. dictionary[descriptor] = DescriptorDeclaration.FromProto(descriptor, location);
  119. }
  120. }
  121. return dictionary;
  122. }
  123. private IDescriptor FindDescriptorForPath(IList<int> path)
  124. {
  125. // All complete declarations have an even, non-empty path length
  126. // (There can be an empty path for a descriptor declaration, but that can't have any comments,
  127. // so we currently ignore it.)
  128. if (path.Count == 0 || (path.Count & 1) != 0)
  129. {
  130. return null;
  131. }
  132. IReadOnlyList<DescriptorBase> topLevelList = GetNestedDescriptorListForField(path[0]);
  133. DescriptorBase current = GetDescriptorFromList(topLevelList, path[1]);
  134. for (int i = 2; current != null && i < path.Count; i += 2)
  135. {
  136. var list = current.GetNestedDescriptorListForField(path[i]);
  137. current = GetDescriptorFromList(list, path[i + 1]);
  138. }
  139. return current;
  140. }
  141. private DescriptorBase GetDescriptorFromList(IReadOnlyList<DescriptorBase> list, int index)
  142. {
  143. // This is fine: it may be a newer version of protobuf than we understand, with a new descriptor
  144. // field.
  145. if (list == null)
  146. {
  147. return null;
  148. }
  149. // We *could* return null to silently continue, but this is basically data corruption.
  150. if (index < 0 || index >= list.Count)
  151. {
  152. // We don't have much extra information to give at this point unfortunately. If this becomes a problem,
  153. // we can pass in the complete path and report that and the file name.
  154. throw new InvalidProtocolBufferException($"Invalid descriptor location path: index out of range");
  155. }
  156. return list[index];
  157. }
  158. private IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber)
  159. {
  160. switch (fieldNumber)
  161. {
  162. case FileDescriptorProto.ServiceFieldNumber:
  163. return (IReadOnlyList<DescriptorBase>) Services;
  164. case FileDescriptorProto.MessageTypeFieldNumber:
  165. return (IReadOnlyList<DescriptorBase>) MessageTypes;
  166. case FileDescriptorProto.EnumTypeFieldNumber:
  167. return (IReadOnlyList<DescriptorBase>) EnumTypes;
  168. default:
  169. return null;
  170. }
  171. }
  172. internal DescriptorDeclaration GetDeclaration(IDescriptor descriptor)
  173. {
  174. DescriptorDeclaration declaration;
  175. declarations.Value.TryGetValue(descriptor, out declaration);
  176. return declaration;
  177. }
  178. /// <summary>
  179. /// Computes the full name of a descriptor within this file, with an optional parent message.
  180. /// </summary>
  181. internal string ComputeFullName(MessageDescriptor parent, string name)
  182. {
  183. if (parent != null)
  184. {
  185. return parent.FullName + "." + name;
  186. }
  187. if (Package.Length > 0)
  188. {
  189. return Package + "." + name;
  190. }
  191. return name;
  192. }
  193. /// <summary>
  194. /// Extracts public dependencies from direct dependencies. This is a static method despite its
  195. /// first parameter, as the value we're in the middle of constructing is only used for exceptions.
  196. /// </summary>
  197. private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, bool allowUnknownDependencies)
  198. {
  199. var nameToFileMap = dependencies.ToDictionary(file => file.Name);
  200. var publicDependencies = new List<FileDescriptor>();
  201. for (int i = 0; i < proto.PublicDependency.Count; i++)
  202. {
  203. int index = proto.PublicDependency[i];
  204. if (index < 0 || index >= proto.Dependency.Count)
  205. {
  206. throw new DescriptorValidationException(@this, "Invalid public dependency index.");
  207. }
  208. string name = proto.Dependency[index];
  209. FileDescriptor file;
  210. if (!nameToFileMap.TryGetValue(name, out file))
  211. {
  212. if (!allowUnknownDependencies)
  213. {
  214. throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
  215. }
  216. // Ignore unknown dependencies.
  217. }
  218. else
  219. {
  220. publicDependencies.Add(file);
  221. }
  222. }
  223. return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
  224. }
  225. /// <value>
  226. /// The descriptor in its protocol message representation.
  227. /// </value>
  228. internal FileDescriptorProto Proto { get; }
  229. /// <summary>
  230. /// The syntax of the file
  231. /// </summary>
  232. public Syntax Syntax { get; }
  233. /// <value>
  234. /// The file name.
  235. /// </value>
  236. public string Name => Proto.Name;
  237. /// <summary>
  238. /// The package as declared in the .proto file. This may or may not
  239. /// be equivalent to the .NET namespace of the generated classes.
  240. /// </summary>
  241. public string Package => Proto.Package;
  242. /// <value>
  243. /// Unmodifiable list of top-level message types declared in this file.
  244. /// </value>
  245. public IList<MessageDescriptor> MessageTypes { get; }
  246. /// <value>
  247. /// Unmodifiable list of top-level enum types declared in this file.
  248. /// </value>
  249. public IList<EnumDescriptor> EnumTypes { get; }
  250. /// <value>
  251. /// Unmodifiable list of top-level services declared in this file.
  252. /// </value>
  253. public IList<ServiceDescriptor> Services { get; }
  254. /// <summary>
  255. /// Unmodifiable list of top-level extensions declared in this file.
  256. /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null)
  257. /// if this descriptor was generated using a version of protoc that did not fully
  258. /// support extensions in C#.
  259. /// </summary>
  260. public ExtensionCollection Extensions { get; }
  261. /// <value>
  262. /// Unmodifiable list of this file's dependencies (imports).
  263. /// </value>
  264. public IList<FileDescriptor> Dependencies { get; }
  265. /// <value>
  266. /// Unmodifiable list of this file's public dependencies (public imports).
  267. /// </value>
  268. public IList<FileDescriptor> PublicDependencies { get; }
  269. /// <value>
  270. /// The original serialized binary form of this descriptor.
  271. /// </value>
  272. public ByteString SerializedData { get; }
  273. /// <value>
  274. /// Implementation of IDescriptor.FullName - just returns the same as Name.
  275. /// </value>
  276. string IDescriptor.FullName => Name;
  277. /// <value>
  278. /// Implementation of IDescriptor.File - just returns this descriptor.
  279. /// </value>
  280. FileDescriptor IDescriptor.File => this;
  281. /// <value>
  282. /// Pool containing symbol descriptors.
  283. /// </value>
  284. internal DescriptorPool DescriptorPool { get; }
  285. /// <summary>
  286. /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
  287. /// </summary>
  288. /// <param name="name">The unqualified type name to look for.</param>
  289. /// <typeparam name="T">The type of descriptor to look for</typeparam>
  290. /// <returns>The type's descriptor, or null if not found.</returns>
  291. public T FindTypeByName<T>(String name)
  292. where T : class, IDescriptor
  293. {
  294. // Don't allow looking up nested types. This will make optimization
  295. // easier later.
  296. if (name.IndexOf('.') != -1)
  297. {
  298. return null;
  299. }
  300. if (Package.Length > 0)
  301. {
  302. name = Package + "." + name;
  303. }
  304. T result = DescriptorPool.FindSymbol<T>(name);
  305. if (result != null && result.File == this)
  306. {
  307. return result;
  308. }
  309. return null;
  310. }
  311. /// <summary>
  312. /// Builds a FileDescriptor from its protocol buffer representation.
  313. /// </summary>
  314. /// <param name="descriptorData">The original serialized descriptor data.
  315. /// We have only limited proto2 support, so serializing FileDescriptorProto
  316. /// would not necessarily give us this.</param>
  317. /// <param name="proto">The protocol message form of the FileDescriptor.</param>
  318. /// <param name="dependencies">FileDescriptors corresponding to all of the
  319. /// file's dependencies, in the exact order listed in the .proto file. May be null,
  320. /// in which case it is treated as an empty array.</param>
  321. /// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
  322. /// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
  323. /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
  324. /// a valid descriptor. This can occur for a number of reasons, such as a field
  325. /// having an undefined type or because two messages were defined with the same name.</exception>
  326. private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
  327. {
  328. // Building descriptors involves two steps: translating and linking.
  329. // In the translation step (implemented by FileDescriptor's
  330. // constructor), we build an object tree mirroring the
  331. // FileDescriptorProto's tree and put all of the descriptors into the
  332. // DescriptorPool's lookup tables. In the linking step, we look up all
  333. // type references in the DescriptorPool, so that, for example, a
  334. // FieldDescriptor for an embedded message contains a pointer directly
  335. // to the Descriptor for that message's type. We also detect undefined
  336. // types in the linking step.
  337. if (dependencies == null)
  338. {
  339. dependencies = new FileDescriptor[0];
  340. }
  341. DescriptorPool pool = new DescriptorPool(dependencies);
  342. FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
  343. // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
  344. // need.
  345. if (dependencies.Length != proto.Dependency.Count)
  346. {
  347. throw new DescriptorValidationException(
  348. result,
  349. "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
  350. "those listed in the FileDescriptorProto.");
  351. }
  352. result.CrossLink();
  353. return result;
  354. }
  355. private void CrossLink()
  356. {
  357. foreach (MessageDescriptor message in MessageTypes)
  358. {
  359. message.CrossLink();
  360. }
  361. foreach (ServiceDescriptor service in Services)
  362. {
  363. service.CrossLink();
  364. }
  365. Extensions.CrossLink();
  366. }
  367. /// <summary>
  368. /// Creates a descriptor for generated code.
  369. /// </summary>
  370. /// <remarks>
  371. /// This method is only designed to be used by the results of generating code with protoc,
  372. /// which creates the appropriate dependencies etc. It has to be public because the generated
  373. /// code is "external", but should not be called directly by end users.
  374. /// </remarks>
  375. public static FileDescriptor FromGeneratedCode(
  376. byte[] descriptorData,
  377. FileDescriptor[] dependencies,
  378. GeneratedClrTypeInfo generatedCodeInfo)
  379. {
  380. ExtensionRegistry registry = new ExtensionRegistry();
  381. registry.AddRange(GetAllExtensions(dependencies, generatedCodeInfo));
  382. FileDescriptorProto proto;
  383. try
  384. {
  385. proto = FileDescriptorProto.Parser.WithExtensionRegistry(registry).ParseFrom(descriptorData);
  386. }
  387. catch (InvalidProtocolBufferException e)
  388. {
  389. throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
  390. }
  391. try
  392. {
  393. // When building descriptors for generated code, we allow unknown
  394. // dependencies by default.
  395. return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
  396. }
  397. catch (DescriptorValidationException e)
  398. {
  399. throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
  400. }
  401. }
  402. private static IEnumerable<Extension> GetAllExtensions(FileDescriptor[] dependencies, GeneratedClrTypeInfo generatedInfo)
  403. {
  404. return dependencies.SelectMany(GetAllDependedExtensions).Distinct().Concat(GetAllGeneratedExtensions(generatedInfo));
  405. }
  406. private static IEnumerable<Extension> GetAllGeneratedExtensions(GeneratedClrTypeInfo generated)
  407. {
  408. return generated.Extensions.Concat(generated.NestedTypes.Where(t => t != null).SelectMany(GetAllGeneratedExtensions));
  409. }
  410. private static IEnumerable<Extension> GetAllDependedExtensions(FileDescriptor descriptor)
  411. {
  412. return descriptor.Extensions.UnorderedExtensions
  413. .Select(s => s.Extension)
  414. .Where(e => e != null)
  415. .Concat(descriptor.Dependencies.Concat(descriptor.PublicDependencies).SelectMany(GetAllDependedExtensions))
  416. .Concat(descriptor.MessageTypes.SelectMany(GetAllDependedExtensionsFromMessage));
  417. }
  418. private static IEnumerable<Extension> GetAllDependedExtensionsFromMessage(MessageDescriptor descriptor)
  419. {
  420. return descriptor.Extensions.UnorderedExtensions
  421. .Select(s => s.Extension)
  422. .Where(e => e != null)
  423. .Concat(descriptor.NestedTypes.SelectMany(GetAllDependedExtensionsFromMessage));
  424. }
  425. /// <summary>
  426. /// Converts the given descriptor binary data into FileDescriptor objects.
  427. /// Note: reflection using the returned FileDescriptors is not currently supported.
  428. /// </summary>
  429. /// <param name="descriptorData">The binary file descriptor proto data. Must not be null, and any
  430. /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B
  431. /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible
  432. /// with the order in which protoc provides descriptors to plugins.</param>
  433. /// <returns>The file descriptors corresponding to <paramref name="descriptorData"/>.</returns>
  434. public static IReadOnlyList<FileDescriptor> BuildFromByteStrings(IEnumerable<ByteString> descriptorData)
  435. {
  436. ProtoPreconditions.CheckNotNull(descriptorData, nameof(descriptorData));
  437. // TODO: See if we can build a single DescriptorPool instead of building lots of them.
  438. // This will all behave correctly, but it's less efficient than we'd like.
  439. var descriptors = new List<FileDescriptor>();
  440. var descriptorsByName = new Dictionary<string, FileDescriptor>();
  441. foreach (var data in descriptorData)
  442. {
  443. var proto = FileDescriptorProto.Parser.ParseFrom(data);
  444. var dependencies = new List<FileDescriptor>();
  445. foreach (var dependencyName in proto.Dependency)
  446. {
  447. FileDescriptor dependency;
  448. if (!descriptorsByName.TryGetValue(dependencyName, out dependency))
  449. {
  450. throw new ArgumentException($"Dependency missing: {dependencyName}");
  451. }
  452. dependencies.Add(dependency);
  453. }
  454. var pool = new DescriptorPool(dependencies);
  455. FileDescriptor descriptor = new FileDescriptor(
  456. data, proto, dependencies, pool,
  457. allowUnknownDependencies: false, generatedCodeInfo: null);
  458. descriptor.CrossLink();
  459. descriptors.Add(descriptor);
  460. if (descriptorsByName.ContainsKey(descriptor.Name))
  461. {
  462. throw new ArgumentException($"Duplicate descriptor name: {descriptor.Name}");
  463. }
  464. descriptorsByName.Add(descriptor.Name, descriptor);
  465. }
  466. return new ReadOnlyCollection<FileDescriptor>(descriptors);
  467. }
  468. /// <summary>
  469. /// Returns a <see cref="System.String" /> that represents this instance.
  470. /// </summary>
  471. /// <returns>
  472. /// A <see cref="System.String" /> that represents this instance.
  473. /// </returns>
  474. public override string ToString()
  475. {
  476. return $"FileDescriptor for {Name}";
  477. }
  478. /// <summary>
  479. /// Returns the file descriptor for descriptor.proto.
  480. /// </summary>
  481. /// <remarks>
  482. /// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
  483. /// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
  484. /// runtime for reflection purposes. The messages are internal to the runtime as they would require
  485. /// proto2 semantics for full support, but the file descriptor is available via this property. The
  486. /// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
  487. /// </remarks>
  488. /// <value>
  489. /// The file descriptor for <c>descriptor.proto</c>.
  490. /// </value>
  491. public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
  492. /// <summary>
  493. /// The (possibly empty) set of custom options for this file.
  494. /// </summary>
  495. [Obsolete("CustomOptions are obsolete. Use GetOption")]
  496. public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
  497. /// <summary>
  498. /// Gets a single value file option for this descriptor
  499. /// </summary>
  500. public T GetOption<T>(Extension<FileOptions, T> extension)
  501. {
  502. var value = Proto.Options.GetExtension(extension);
  503. return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value;
  504. }
  505. /// <summary>
  506. /// Gets a repeated value file option for this descriptor
  507. /// </summary>
  508. public RepeatedField<T> GetOption<T>(RepeatedExtension<FileOptions, T> extension)
  509. {
  510. return Proto.Options.GetExtension(extension).Clone();
  511. }
  512. /// <summary>
  513. /// Performs initialization for the given generic type argument.
  514. /// </summary>
  515. /// <remarks>
  516. /// This method is present for the sake of AOT compilers. It allows code (whether handwritten or generated)
  517. /// to make calls into the reflection machinery of this library to express an intention to use that type
  518. /// reflectively (e.g. for JSON parsing and formatting). The call itself does almost nothing, but AOT compilers
  519. /// attempting to determine which generic type arguments need to be handled will spot the code path and act
  520. /// accordingly.
  521. /// </remarks>
  522. /// <typeparam name="T">The type to force initialization for.</typeparam>
  523. public static void ForceReflectionInitialization<T>() => ReflectionUtil.ForceInitialize<T>();
  524. }
  525. }