DescriptorPool.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System.Collections.Generic;
  2. using System;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace Google.ProtocolBuffers.Descriptors {
  6. /// <summary>
  7. /// Contains lookup tables containing all the descriptors defined in a particular file.
  8. /// </summary>
  9. internal class DescriptorPool {
  10. private readonly IDictionary<string, IDescriptor> descriptorsByName =
  11. new Dictionary<string, IDescriptor>();
  12. private readonly IDictionary<DescriptorIntPair, FieldDescriptor> fieldsByNumber =
  13. new Dictionary<DescriptorIntPair, FieldDescriptor>();
  14. private readonly IDictionary<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber =
  15. new Dictionary<DescriptorIntPair, EnumValueDescriptor>();
  16. private readonly DescriptorPool[] dependencies;
  17. internal DescriptorPool(FileDescriptor[] dependencyFiles) {
  18. dependencies = new DescriptorPool[dependencyFiles.Length];
  19. for (int i = 0; i < dependencyFiles.Length; i++) {
  20. dependencies[i] = dependencyFiles[i].DescriptorPool;
  21. }
  22. foreach (FileDescriptor dependency in dependencyFiles) {
  23. AddPackage(dependency.Package, dependency);
  24. }
  25. }
  26. /// <summary>
  27. /// Finds a symbol of the given name within the pool.
  28. /// </summary>
  29. /// <typeparam name="T">The type of symbol to look for</typeparam>
  30. /// <param name="fullName">Fully-qualified name to look up</param>
  31. /// <returns>The symbol with the given name and type,
  32. /// or null if the symbol doesn't exist or has the wrong type</returns>
  33. internal T FindSymbol<T>(string fullName) where T : class, IDescriptor {
  34. IDescriptor result;
  35. descriptorsByName.TryGetValue(fullName, out result);
  36. T descriptor = result as T;
  37. if (descriptor != null) {
  38. return descriptor;
  39. }
  40. foreach (DescriptorPool dependency in dependencies) {
  41. dependency.descriptorsByName.TryGetValue(fullName, out result);
  42. descriptor = result as T;
  43. if (descriptor != null) {
  44. return descriptor;
  45. }
  46. }
  47. return null;
  48. }
  49. /// <summary>
  50. /// Adds a package to the symbol tables. If a package by the same name
  51. /// already exists, that is fine, but if some other kind of symbol
  52. /// exists under the same name, an exception is thrown. If the package
  53. /// has multiple components, this also adds the parent package(s).
  54. /// </summary>
  55. internal void AddPackage(string fullName, FileDescriptor file) {
  56. int dotpos = fullName.LastIndexOf('.');
  57. String name;
  58. if (dotpos != -1) {
  59. AddPackage(fullName.Substring(0, dotpos), file);
  60. name = fullName.Substring(dotpos + 1);
  61. } else {
  62. name = fullName;
  63. }
  64. IDescriptor old;
  65. if (descriptorsByName.TryGetValue(fullName, out old)) {
  66. if (!(old is PackageDescriptor)) {
  67. throw new DescriptorValidationException(file,
  68. "\"" + name + "\" is already defined (as something other than a " +
  69. "package) in file \"" + old.File.Name + "\".");
  70. }
  71. }
  72. // TODO(jonskeet): Check issue 25 wrt the ordering of these parameters
  73. descriptorsByName[fullName] = new PackageDescriptor(fullName, name, file);
  74. }
  75. /// <summary>
  76. /// Adds a symbol to the symbol table.
  77. /// </summary>
  78. /// <exception cref="DescriptorValidationException">The symbol already existed
  79. /// in the symbol table.</exception>
  80. internal void AddSymbol(IDescriptor descriptor) {
  81. ValidateSymbolName(descriptor);
  82. String fullName = descriptor.FullName;
  83. IDescriptor old;
  84. if (descriptorsByName.TryGetValue(fullName, out old)) {
  85. int dotPos = fullName.LastIndexOf('.');
  86. string message;
  87. if (descriptor.File == old.File) {
  88. if (dotPos == -1) {
  89. message = "\"" + fullName + "\" is already defined.";
  90. } else {
  91. message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" + fullName.Substring(0, dotPos) + "\".";
  92. }
  93. } else {
  94. message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\".";
  95. }
  96. throw new DescriptorValidationException(descriptor, message);
  97. }
  98. descriptorsByName[fullName] = descriptor;
  99. }
  100. private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$", RegexOptions.Compiled);
  101. /// <summary>
  102. /// Verifies that the descriptor's name is valid (i.e. it contains
  103. /// only letters, digits and underscores, and does not start with a digit).
  104. /// </summary>
  105. /// <param name="descriptor"></param>
  106. private static void ValidateSymbolName(IDescriptor descriptor) {
  107. if (descriptor.Name == "") {
  108. throw new DescriptorValidationException(descriptor, "Missing name.");
  109. }
  110. if (!ValidationRegex.IsMatch(descriptor.Name)) {
  111. throw new DescriptorValidationException(descriptor,
  112. "\"" + descriptor.Name + "\" is not a valid identifier.");
  113. }
  114. }
  115. /// <summary>
  116. /// Returns the field with the given number in the given descriptor,
  117. /// or null if it can't be found.
  118. /// </summary>
  119. internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number) {
  120. FieldDescriptor ret;
  121. fieldsByNumber.TryGetValue(new DescriptorIntPair(messageDescriptor, number), out ret);
  122. return ret;
  123. }
  124. internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number) {
  125. EnumValueDescriptor ret;
  126. enumValuesByNumber.TryGetValue(new DescriptorIntPair(enumDescriptor, number), out ret);
  127. return ret;
  128. }
  129. /// <summary>
  130. /// Adds a field to the fieldsByNumber table.
  131. /// </summary>
  132. /// <exception cref="DescriptorValidationException">A field with the same
  133. /// containing type and number already exists.</exception>
  134. internal void AddFieldByNumber(FieldDescriptor field) {
  135. DescriptorIntPair key = new DescriptorIntPair(field.ContainingType, field.FieldNumber);
  136. FieldDescriptor old;
  137. if (fieldsByNumber.TryGetValue(key, out old)) {
  138. throw new DescriptorValidationException(field, "Field number " + field.FieldNumber +
  139. "has already been used in \"" + field.ContainingType.FullName +
  140. "\" by field \"" + old.Name + "\".");
  141. }
  142. fieldsByNumber[key] = field;
  143. }
  144. /// <summary>
  145. /// Adds an enum value to the enumValuesByNumber table. If an enum value
  146. /// with the same type and number already exists, this method does nothing.
  147. /// (This is allowed; the first value defined with the number takes precedence.)
  148. /// </summary>
  149. internal void AddEnumValueByNumber(EnumValueDescriptor enumValue) {
  150. DescriptorIntPair key = new DescriptorIntPair(enumValue.EnumDescriptor, enumValue.Number);
  151. if (!enumValuesByNumber.ContainsKey(key)) {
  152. enumValuesByNumber[key] = enumValue;
  153. }
  154. }
  155. /// <summary>
  156. /// Looks up a descriptor by name, relative to some other descriptor.
  157. /// The name may be fully-qualified (with a leading '.'), partially-qualified,
  158. /// or unqualified. C++-like name lookup semantics are used to search for the
  159. /// matching descriptor.
  160. /// </summary>
  161. public IDescriptor LookupSymbol(string name, IDescriptor relativeTo) {
  162. // TODO(jonskeet): This could be optimized in a number of ways.
  163. IDescriptor result;
  164. if (name.StartsWith(".")) {
  165. // Fully-qualified name.
  166. result = FindSymbol<IDescriptor>(name.Substring(1));
  167. } else {
  168. // If "name" is a compound identifier, we want to search for the
  169. // first component of it, then search within it for the rest.
  170. int firstPartLength = name.IndexOf('.');
  171. string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength);
  172. // We will search each parent scope of "relativeTo" looking for the
  173. // symbol.
  174. StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName);
  175. while (true) {
  176. // Chop off the last component of the scope.
  177. // TODO(jonskeet): Make this more efficient. May not be worth using StringBuilder at all
  178. int dotpos = scopeToTry.ToString().LastIndexOf(".");
  179. if (dotpos == -1) {
  180. result = FindSymbol<IDescriptor>(name);
  181. break;
  182. } else {
  183. scopeToTry.Length = dotpos + 1;
  184. // Append firstPart and try to find.
  185. scopeToTry.Append(firstPart);
  186. result = FindSymbol<IDescriptor>(scopeToTry.ToString());
  187. if (result != null) {
  188. if (firstPartLength != -1) {
  189. // We only found the first part of the symbol. Now look for
  190. // the whole thing. If this fails, we *don't* want to keep
  191. // searching parent scopes.
  192. scopeToTry.Length = dotpos + 1;
  193. scopeToTry.Append(name);
  194. result = FindSymbol<IDescriptor>(scopeToTry.ToString());
  195. }
  196. break;
  197. }
  198. // Not found. Remove the name so we can try again.
  199. scopeToTry.Length = dotpos;
  200. }
  201. }
  202. }
  203. if (result == null) {
  204. throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined.");
  205. } else {
  206. return result;
  207. }
  208. }
  209. /// <summary>
  210. /// Struct used to hold the keys for the fieldByNumber table.
  211. /// </summary>
  212. struct DescriptorIntPair : IEquatable<DescriptorIntPair> {
  213. private readonly int number;
  214. private readonly IDescriptor descriptor;
  215. internal DescriptorIntPair(IDescriptor descriptor, int number) {
  216. this.number = number;
  217. this.descriptor = descriptor;
  218. }
  219. public bool Equals(DescriptorIntPair other) {
  220. return descriptor == other.descriptor
  221. && number == other.number;
  222. }
  223. public override bool Equals(object obj) {
  224. if (obj is DescriptorIntPair) {
  225. return Equals((DescriptorIntPair)obj);
  226. }
  227. return false;
  228. }
  229. public override int GetHashCode() {
  230. return descriptor.GetHashCode() * ((1 << 16) - 1) + number;
  231. }
  232. }
  233. }
  234. }