FieldGeneratorBase.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System;
  35. using System.Globalization;
  36. using System.Text;
  37. using Google.ProtocolBuffers.Descriptors;
  38. namespace Google.ProtocolBuffers.ProtoGen
  39. {
  40. internal abstract class FieldGeneratorBase : SourceGeneratorBase<FieldDescriptor>
  41. {
  42. private readonly int _fieldOrdinal;
  43. protected FieldGeneratorBase(FieldDescriptor descriptor, int fieldOrdinal)
  44. : base(descriptor)
  45. {
  46. _fieldOrdinal = fieldOrdinal;
  47. }
  48. public abstract void WriteHash(TextGenerator writer);
  49. public abstract void WriteEquals(TextGenerator writer);
  50. public abstract void WriteToString(TextGenerator writer);
  51. public int FieldOrdinal
  52. {
  53. get { return _fieldOrdinal; }
  54. }
  55. private static bool AllPrintableAscii(string text)
  56. {
  57. foreach (char c in text)
  58. {
  59. if (c < 0x20 || c > 0x7e)
  60. {
  61. return false;
  62. }
  63. }
  64. return true;
  65. }
  66. /// <summary>
  67. /// This returns true if the field has a non-default default value. For instance this returns
  68. /// false for numerics with a default of zero '0', or booleans with a default of false.
  69. /// </summary>
  70. protected bool HasDefaultValue
  71. {
  72. get
  73. {
  74. switch (Descriptor.FieldType)
  75. {
  76. case FieldType.Float:
  77. case FieldType.Double:
  78. case FieldType.Int32:
  79. case FieldType.Int64:
  80. case FieldType.SInt32:
  81. case FieldType.SInt64:
  82. case FieldType.SFixed32:
  83. case FieldType.SFixed64:
  84. case FieldType.UInt32:
  85. case FieldType.UInt64:
  86. case FieldType.Fixed32:
  87. case FieldType.Fixed64:
  88. {
  89. IConvertible value = (IConvertible) Descriptor.DefaultValue;
  90. return value.ToString(CultureInfo.InvariantCulture) != "0";
  91. }
  92. case FieldType.Bool:
  93. return ((bool) Descriptor.DefaultValue) == true;
  94. default:
  95. return true;
  96. }
  97. }
  98. }
  99. /// <remarks>Copy exists in ExtensionGenerator.cs</remarks>
  100. protected string DefaultValue
  101. {
  102. get
  103. {
  104. string suffix = "";
  105. switch (Descriptor.FieldType)
  106. {
  107. case FieldType.Float:
  108. suffix = "F";
  109. break;
  110. case FieldType.Double:
  111. suffix = "D";
  112. break;
  113. case FieldType.Int64:
  114. suffix = "L";
  115. break;
  116. case FieldType.UInt64:
  117. suffix = "UL";
  118. break;
  119. }
  120. switch (Descriptor.FieldType)
  121. {
  122. case FieldType.Float:
  123. case FieldType.Double:
  124. case FieldType.Int32:
  125. case FieldType.Int64:
  126. case FieldType.SInt32:
  127. case FieldType.SInt64:
  128. case FieldType.SFixed32:
  129. case FieldType.SFixed64:
  130. case FieldType.UInt32:
  131. case FieldType.UInt64:
  132. case FieldType.Fixed32:
  133. case FieldType.Fixed64:
  134. {
  135. // The simple Object.ToString converts using the current culture.
  136. // We want to always use the invariant culture so it's predictable.
  137. IConvertible value = (IConvertible) Descriptor.DefaultValue;
  138. //a few things that must be handled explicitly
  139. if (Descriptor.FieldType == FieldType.Double && value is double)
  140. {
  141. if (double.IsNaN((double) value))
  142. {
  143. return "double.NaN";
  144. }
  145. if (double.IsPositiveInfinity((double) value))
  146. {
  147. return "double.PositiveInfinity";
  148. }
  149. if (double.IsNegativeInfinity((double) value))
  150. {
  151. return "double.NegativeInfinity";
  152. }
  153. }
  154. else if (Descriptor.FieldType == FieldType.Float && value is float)
  155. {
  156. if (float.IsNaN((float) value))
  157. {
  158. return "float.NaN";
  159. }
  160. if (float.IsPositiveInfinity((float) value))
  161. {
  162. return "float.PositiveInfinity";
  163. }
  164. if (float.IsNegativeInfinity((float) value))
  165. {
  166. return "float.NegativeInfinity";
  167. }
  168. }
  169. return value.ToString(CultureInfo.InvariantCulture) + suffix;
  170. }
  171. case FieldType.Bool:
  172. return (bool) Descriptor.DefaultValue ? "true" : "false";
  173. case FieldType.Bytes:
  174. if (!Descriptor.HasDefaultValue)
  175. {
  176. return "pb::ByteString.Empty";
  177. }
  178. if (UseLiteRuntime && Descriptor.DefaultValue is ByteString)
  179. {
  180. string temp = (((ByteString) Descriptor.DefaultValue).ToBase64());
  181. return String.Format("pb::ByteString.FromBase64(\"{0}\")", temp);
  182. }
  183. return string.Format("(pb::ByteString) {0}.Descriptor.Fields[{1}].DefaultValue",
  184. GetClassName(Descriptor.ContainingType), Descriptor.Index);
  185. case FieldType.String:
  186. if (AllPrintableAscii(Descriptor.Proto.DefaultValue))
  187. {
  188. // All chars are ASCII and printable. In this case we only
  189. // need to escape quotes and backslashes.
  190. return "\"" + Descriptor.Proto.DefaultValue
  191. .Replace("\\", "\\\\")
  192. .Replace("'", "\\'")
  193. .Replace("\"", "\\\"")
  194. + "\"";
  195. }
  196. if (UseLiteRuntime && Descriptor.DefaultValue is String)
  197. {
  198. string temp = Convert.ToBase64String(
  199. Encoding.UTF8.GetBytes((String) Descriptor.DefaultValue));
  200. return String.Format("pb::ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp);
  201. }
  202. return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue",
  203. GetClassName(Descriptor.ContainingType), Descriptor.Index);
  204. case FieldType.Enum:
  205. return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name;
  206. case FieldType.Message:
  207. case FieldType.Group:
  208. return TypeName + ".DefaultInstance";
  209. default:
  210. throw new InvalidOperationException("Invalid field descriptor type");
  211. }
  212. }
  213. }
  214. protected string PropertyName
  215. {
  216. get { return Descriptor.CSharpOptions.PropertyName; }
  217. }
  218. protected string Name
  219. {
  220. get { return NameHelpers.UnderscoresToCamelCase(GetFieldName(Descriptor)); }
  221. }
  222. protected int Number
  223. {
  224. get { return Descriptor.FieldNumber; }
  225. }
  226. protected void AddNullCheck(TextGenerator writer)
  227. {
  228. AddNullCheck(writer, "value");
  229. }
  230. protected void AddNullCheck(TextGenerator writer, string name)
  231. {
  232. if (IsNullableType)
  233. {
  234. writer.WriteLine(" pb::ThrowHelper.ThrowIfNull({0}, \"{0}\");", name);
  235. }
  236. }
  237. protected void AddPublicMemberAttributes(TextGenerator writer)
  238. {
  239. AddDeprecatedFlag(writer);
  240. AddClsComplianceCheck(writer);
  241. }
  242. protected void AddClsComplianceCheck(TextGenerator writer)
  243. {
  244. if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
  245. {
  246. writer.WriteLine("[global::System.CLSCompliant(false)]");
  247. }
  248. }
  249. protected bool IsObsolete { get { return Descriptor.Options.Deprecated; } }
  250. /// <summary>
  251. /// Writes [global::System.ObsoleteAttribute()] if the member is obsolete
  252. /// </summary>
  253. protected void AddDeprecatedFlag(TextGenerator writer)
  254. {
  255. if (IsObsolete)
  256. {
  257. writer.WriteLine("[global::System.ObsoleteAttribute()]");
  258. }
  259. }
  260. /// <summary>
  261. /// For encodings with fixed sizes, returns that size in bytes. Otherwise
  262. /// returns -1. TODO(jonskeet): Make this less ugly.
  263. /// </summary>
  264. protected int FixedSize
  265. {
  266. get
  267. {
  268. switch (Descriptor.FieldType)
  269. {
  270. case FieldType.UInt32:
  271. case FieldType.UInt64:
  272. case FieldType.Int32:
  273. case FieldType.Int64:
  274. case FieldType.SInt32:
  275. case FieldType.SInt64:
  276. case FieldType.Enum:
  277. case FieldType.Bytes:
  278. case FieldType.String:
  279. case FieldType.Message:
  280. case FieldType.Group:
  281. return -1;
  282. case FieldType.Float:
  283. return WireFormat.FloatSize;
  284. case FieldType.SFixed32:
  285. return WireFormat.SFixed32Size;
  286. case FieldType.Fixed32:
  287. return WireFormat.Fixed32Size;
  288. case FieldType.Double:
  289. return WireFormat.DoubleSize;
  290. case FieldType.SFixed64:
  291. return WireFormat.SFixed64Size;
  292. case FieldType.Fixed64:
  293. return WireFormat.Fixed64Size;
  294. case FieldType.Bool:
  295. return WireFormat.BoolSize;
  296. default:
  297. throw new InvalidOperationException("Invalid field descriptor type");
  298. }
  299. }
  300. }
  301. protected bool IsNullableType
  302. {
  303. get
  304. {
  305. switch (Descriptor.FieldType)
  306. {
  307. case FieldType.Float:
  308. case FieldType.Double:
  309. case FieldType.Int32:
  310. case FieldType.Int64:
  311. case FieldType.SInt32:
  312. case FieldType.SInt64:
  313. case FieldType.SFixed32:
  314. case FieldType.SFixed64:
  315. case FieldType.UInt32:
  316. case FieldType.UInt64:
  317. case FieldType.Fixed32:
  318. case FieldType.Fixed64:
  319. case FieldType.Bool:
  320. case FieldType.Enum:
  321. return false;
  322. case FieldType.Bytes:
  323. case FieldType.String:
  324. case FieldType.Message:
  325. case FieldType.Group:
  326. return true;
  327. default:
  328. throw new InvalidOperationException("Invalid field descriptor type");
  329. }
  330. }
  331. }
  332. protected string TypeName
  333. {
  334. get
  335. {
  336. switch (Descriptor.FieldType)
  337. {
  338. case FieldType.Enum:
  339. return GetClassName(Descriptor.EnumType);
  340. case FieldType.Message:
  341. case FieldType.Group:
  342. return GetClassName(Descriptor.MessageType);
  343. default:
  344. return DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
  345. }
  346. }
  347. }
  348. protected string MessageOrGroup
  349. {
  350. get { return Descriptor.FieldType == FieldType.Group ? "Group" : "Message"; }
  351. }
  352. /// <summary>
  353. /// Returns the type name as used in CodedInputStream method names: SFixed32, UInt32 etc.
  354. /// </summary>
  355. protected string CapitalizedTypeName
  356. {
  357. get
  358. {
  359. // Our enum names match perfectly. How serendipitous.
  360. return Descriptor.FieldType.ToString();
  361. }
  362. }
  363. }
  364. }