DescriptorPool.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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.Text;
  35. using System.Text.RegularExpressions;
  36. namespace Google.ProtocolBuffers.Descriptors
  37. {
  38. /// <summary>
  39. /// Contains lookup tables containing all the descriptors defined in a particular file.
  40. /// </summary>
  41. internal sealed class DescriptorPool
  42. {
  43. private readonly IDictionary<string, IDescriptor> descriptorsByName =
  44. new Dictionary<string, IDescriptor>();
  45. private readonly IDictionary<DescriptorIntPair, FieldDescriptor> fieldsByNumber =
  46. new Dictionary<DescriptorIntPair, FieldDescriptor>();
  47. private readonly IDictionary<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber =
  48. new Dictionary<DescriptorIntPair, EnumValueDescriptor>();
  49. private readonly DescriptorPool[] dependencies;
  50. internal DescriptorPool(FileDescriptor[] dependencyFiles)
  51. {
  52. dependencies = new DescriptorPool[dependencyFiles.Length];
  53. for (int i = 0; i < dependencyFiles.Length; i++)
  54. {
  55. dependencies[i] = dependencyFiles[i].DescriptorPool;
  56. }
  57. foreach (FileDescriptor dependency in dependencyFiles)
  58. {
  59. AddPackage(dependency.Package, dependency);
  60. }
  61. }
  62. /// <summary>
  63. /// Finds a symbol of the given name within the pool.
  64. /// </summary>
  65. /// <typeparam name="T">The type of symbol to look for</typeparam>
  66. /// <param name="fullName">Fully-qualified name to look up</param>
  67. /// <returns>The symbol with the given name and type,
  68. /// or null if the symbol doesn't exist or has the wrong type</returns>
  69. internal T FindSymbol<T>(string fullName) where T : class, IDescriptor
  70. {
  71. IDescriptor result;
  72. descriptorsByName.TryGetValue(fullName, out result);
  73. T descriptor = result as T;
  74. if (descriptor != null)
  75. {
  76. return descriptor;
  77. }
  78. foreach (DescriptorPool dependency in dependencies)
  79. {
  80. dependency.descriptorsByName.TryGetValue(fullName, out result);
  81. descriptor = result as T;
  82. if (descriptor != null)
  83. {
  84. return descriptor;
  85. }
  86. }
  87. return null;
  88. }
  89. /// <summary>
  90. /// Adds a package to the symbol tables. If a package by the same name
  91. /// already exists, that is fine, but if some other kind of symbol
  92. /// exists under the same name, an exception is thrown. If the package
  93. /// has multiple components, this also adds the parent package(s).
  94. /// </summary>
  95. internal void AddPackage(string fullName, FileDescriptor file)
  96. {
  97. int dotpos = fullName.LastIndexOf('.');
  98. String name;
  99. if (dotpos != -1)
  100. {
  101. AddPackage(fullName.Substring(0, dotpos), file);
  102. name = fullName.Substring(dotpos + 1);
  103. }
  104. else
  105. {
  106. name = fullName;
  107. }
  108. IDescriptor old;
  109. if (descriptorsByName.TryGetValue(fullName, out old))
  110. {
  111. if (!(old is PackageDescriptor))
  112. {
  113. throw new DescriptorValidationException(file,
  114. "\"" + name +
  115. "\" is already defined (as something other than a " +
  116. "package) in file \"" + old.File.Name + "\".");
  117. }
  118. }
  119. descriptorsByName[fullName] = new PackageDescriptor(name, fullName, file);
  120. }
  121. /// <summary>
  122. /// Adds a symbol to the symbol table.
  123. /// </summary>
  124. /// <exception cref="DescriptorValidationException">The symbol already existed
  125. /// in the symbol table.</exception>
  126. internal void AddSymbol(IDescriptor descriptor)
  127. {
  128. ValidateSymbolName(descriptor);
  129. String fullName = descriptor.FullName;
  130. IDescriptor old;
  131. if (descriptorsByName.TryGetValue(fullName, out old))
  132. {
  133. int dotPos = fullName.LastIndexOf('.');
  134. string message;
  135. if (descriptor.File == old.File)
  136. {
  137. if (dotPos == -1)
  138. {
  139. message = "\"" + fullName + "\" is already defined.";
  140. }
  141. else
  142. {
  143. message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" +
  144. fullName.Substring(0, dotPos) + "\".";
  145. }
  146. }
  147. else
  148. {
  149. message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\".";
  150. }
  151. throw new DescriptorValidationException(descriptor, message);
  152. }
  153. descriptorsByName[fullName] = descriptor;
  154. }
  155. private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$",
  156. FrameworkPortability.CompiledRegexWhereAvailable);
  157. /// <summary>
  158. /// Verifies that the descriptor's name is valid (i.e. it contains
  159. /// only letters, digits and underscores, and does not start with a digit).
  160. /// </summary>
  161. /// <param name="descriptor"></param>
  162. private static void ValidateSymbolName(IDescriptor descriptor)
  163. {
  164. if (descriptor.Name == "")
  165. {
  166. throw new DescriptorValidationException(descriptor, "Missing name.");
  167. }
  168. if (!ValidationRegex.IsMatch(descriptor.Name))
  169. {
  170. throw new DescriptorValidationException(descriptor,
  171. "\"" + descriptor.Name + "\" is not a valid identifier.");
  172. }
  173. }
  174. /// <summary>
  175. /// Returns the field with the given number in the given descriptor,
  176. /// or null if it can't be found.
  177. /// </summary>
  178. internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number)
  179. {
  180. FieldDescriptor ret;
  181. fieldsByNumber.TryGetValue(new DescriptorIntPair(messageDescriptor, number), out ret);
  182. return ret;
  183. }
  184. internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number)
  185. {
  186. EnumValueDescriptor ret;
  187. enumValuesByNumber.TryGetValue(new DescriptorIntPair(enumDescriptor, number), out ret);
  188. return ret;
  189. }
  190. /// <summary>
  191. /// Adds a field to the fieldsByNumber table.
  192. /// </summary>
  193. /// <exception cref="DescriptorValidationException">A field with the same
  194. /// containing type and number already exists.</exception>
  195. internal void AddFieldByNumber(FieldDescriptor field)
  196. {
  197. DescriptorIntPair key = new DescriptorIntPair(field.ContainingType, field.FieldNumber);
  198. FieldDescriptor old;
  199. if (fieldsByNumber.TryGetValue(key, out old))
  200. {
  201. throw new DescriptorValidationException(field, "Field number " + field.FieldNumber +
  202. "has already been used in \"" +
  203. field.ContainingType.FullName +
  204. "\" by field \"" + old.Name + "\".");
  205. }
  206. fieldsByNumber[key] = field;
  207. }
  208. /// <summary>
  209. /// Adds an enum value to the enumValuesByNumber table. If an enum value
  210. /// with the same type and number already exists, this method does nothing.
  211. /// (This is allowed; the first value defined with the number takes precedence.)
  212. /// </summary>
  213. internal void AddEnumValueByNumber(EnumValueDescriptor enumValue)
  214. {
  215. DescriptorIntPair key = new DescriptorIntPair(enumValue.EnumDescriptor, enumValue.Number);
  216. if (!enumValuesByNumber.ContainsKey(key))
  217. {
  218. enumValuesByNumber[key] = enumValue;
  219. }
  220. }
  221. /// <summary>
  222. /// Looks up a descriptor by name, relative to some other descriptor.
  223. /// The name may be fully-qualified (with a leading '.'), partially-qualified,
  224. /// or unqualified. C++-like name lookup semantics are used to search for the
  225. /// matching descriptor.
  226. /// </summary>
  227. public IDescriptor LookupSymbol(string name, IDescriptor relativeTo)
  228. {
  229. // TODO(jonskeet): This could be optimized in a number of ways.
  230. IDescriptor result;
  231. if (name.StartsWith("."))
  232. {
  233. // Fully-qualified name.
  234. result = FindSymbol<IDescriptor>(name.Substring(1));
  235. }
  236. else
  237. {
  238. // If "name" is a compound identifier, we want to search for the
  239. // first component of it, then search within it for the rest.
  240. int firstPartLength = name.IndexOf('.');
  241. string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength);
  242. // We will search each parent scope of "relativeTo" looking for the
  243. // symbol.
  244. StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName);
  245. while (true)
  246. {
  247. // Chop off the last component of the scope.
  248. // TODO(jonskeet): Make this more efficient. May not be worth using StringBuilder at all
  249. int dotpos = scopeToTry.ToString().LastIndexOf(".");
  250. if (dotpos == -1)
  251. {
  252. result = FindSymbol<IDescriptor>(name);
  253. break;
  254. }
  255. else
  256. {
  257. scopeToTry.Length = dotpos + 1;
  258. // Append firstPart and try to find.
  259. scopeToTry.Append(firstPart);
  260. result = FindSymbol<IDescriptor>(scopeToTry.ToString());
  261. if (result != null)
  262. {
  263. if (firstPartLength != -1)
  264. {
  265. // We only found the first part of the symbol. Now look for
  266. // the whole thing. If this fails, we *don't* want to keep
  267. // searching parent scopes.
  268. scopeToTry.Length = dotpos + 1;
  269. scopeToTry.Append(name);
  270. result = FindSymbol<IDescriptor>(scopeToTry.ToString());
  271. }
  272. break;
  273. }
  274. // Not found. Remove the name so we can try again.
  275. scopeToTry.Length = dotpos;
  276. }
  277. }
  278. }
  279. if (result == null)
  280. {
  281. throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined.");
  282. }
  283. else
  284. {
  285. return result;
  286. }
  287. }
  288. /// <summary>
  289. /// Struct used to hold the keys for the fieldByNumber table.
  290. /// </summary>
  291. private struct DescriptorIntPair : IEquatable<DescriptorIntPair>
  292. {
  293. private readonly int number;
  294. private readonly IDescriptor descriptor;
  295. internal DescriptorIntPair(IDescriptor descriptor, int number)
  296. {
  297. this.number = number;
  298. this.descriptor = descriptor;
  299. }
  300. public bool Equals(DescriptorIntPair other)
  301. {
  302. return descriptor == other.descriptor
  303. && number == other.number;
  304. }
  305. public override bool Equals(object obj)
  306. {
  307. if (obj is DescriptorIntPair)
  308. {
  309. return Equals((DescriptorIntPair) obj);
  310. }
  311. return false;
  312. }
  313. public override int GetHashCode()
  314. {
  315. return descriptor.GetHashCode()*((1 << 16) - 1) + number;
  316. }
  317. }
  318. }
  319. }