java_helpers.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
  34. #define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
  35. #include <string>
  36. #include <google/protobuf/compiler/java/java_context.h>
  37. #include <google/protobuf/descriptor.pb.h>
  38. #include <google/protobuf/io/printer.h>
  39. #include <google/protobuf/descriptor.h>
  40. namespace google {
  41. namespace protobuf {
  42. namespace compiler {
  43. namespace java {
  44. // Commonly-used separator comments. Thick is a line of '=', thin is a line
  45. // of '-'.
  46. extern const char kThickSeparator[];
  47. extern const char kThinSeparator[];
  48. // If annotation_file is non-empty, prints a javax.annotation.Generated
  49. // annotation to the given Printer. annotation_file will be referenced in the
  50. // annotation's comments field. delimiter should be the Printer's delimiter
  51. // character. annotation_file will be included verbatim into a Java literal
  52. // string, so it should not contain quotes or invalid Java escape sequences;
  53. // however, these are unlikely to appear in practice, as the value of
  54. // annotation_file should be generated from the filename of the source file
  55. // being annotated (which in turn must be a Java identifier plus ".java").
  56. void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
  57. const std::string& annotation_file = "");
  58. // If a GeneratedMessageLite contains non-lite enums, then its verifier
  59. // must be instantiated inline, rather than retrieved from the enum class.
  60. void PrintEnumVerifierLogic(io::Printer* printer,
  61. const FieldDescriptor* descriptor,
  62. const std::map<std::string, std::string>& variables,
  63. const char* var_name,
  64. const char* terminating_string, bool enforce_lite);
  65. // Converts a name to camel-case. If cap_first_letter is true, capitalize the
  66. // first letter.
  67. std::string UnderscoresToCamelCase(const std::string& name,
  68. bool cap_first_letter);
  69. // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
  70. // "fooBarBaz" or "FooBarBaz", respectively.
  71. std::string UnderscoresToCamelCase(const FieldDescriptor* field);
  72. std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
  73. // Similar, but for method names. (Typically, this merely has the effect
  74. // of lower-casing the first letter of the name.)
  75. std::string UnderscoresToCamelCase(const MethodDescriptor* method);
  76. // Same as UnderscoresToCamelCase, but checks for reserved keywords
  77. std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field);
  78. // Similar to UnderscoresToCamelCase, but guarentees that the result is a
  79. // complete Java identifier by adding a _ if needed.
  80. std::string CamelCaseFieldName(const FieldDescriptor* field);
  81. // Get an identifier that uniquely identifies this type within the file.
  82. // This is used to declare static variables related to this type at the
  83. // outermost file scope.
  84. std::string UniqueFileScopeIdentifier(const Descriptor* descriptor);
  85. // Strips ".proto" or ".protodevel" from the end of a filename.
  86. std::string StripProto(const std::string& filename);
  87. // Gets the unqualified class name for the file. For each .proto file, there
  88. // will be one Java class containing all the immutable messages and another
  89. // Java class containing all the mutable messages.
  90. // TODO(xiaofeng): remove the default value after updating client code.
  91. std::string FileClassName(const FileDescriptor* file, bool immutable = true);
  92. // Returns the file's Java package name.
  93. std::string FileJavaPackage(const FileDescriptor* file);
  94. std::string FileJavaPackage(const FileDescriptor* file, bool immutable);
  95. // Returns output directory for the given package name.
  96. std::string JavaPackageToDir(std::string package_name);
  97. // TODO(xiaofeng): the following methods are kept for they are exposed
  98. // publicly in //net/proto2/compiler/java/public/names.h. They return
  99. // immutable names only and should be removed after mutable API is
  100. // integrated into google3.
  101. std::string ClassName(const Descriptor* descriptor);
  102. std::string ClassName(const EnumDescriptor* descriptor);
  103. std::string ClassName(const ServiceDescriptor* descriptor);
  104. std::string ClassName(const FileDescriptor* descriptor);
  105. // Comma-separate list of option-specified interfaces implemented by the
  106. // Message, to follow the "implements" declaration of the Message definition.
  107. std::string ExtraMessageInterfaces(const Descriptor* descriptor);
  108. // Comma-separate list of option-specified interfaces implemented by the
  109. // MutableMessage, to follow the "implements" declaration of the MutableMessage
  110. // definition.
  111. std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
  112. // Comma-separate list of option-specified interfaces implemented by the
  113. // Builder, to follow the "implements" declaration of the Builder definition.
  114. std::string ExtraBuilderInterfaces(const Descriptor* descriptor);
  115. // Comma-separate list of option-specified interfaces extended by the
  116. // MessageOrBuilder, to follow the "extends" declaration of the
  117. // MessageOrBuilder definition.
  118. std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
  119. // Get the unqualified Java class name for mutable messages. i.e. without
  120. // package or outer classnames.
  121. inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) {
  122. return descriptor->name();
  123. }
  124. // Whether the given descriptor is for one of the core descriptor protos. We
  125. // cannot currently use the new runtime with core protos since there is a
  126. // bootstrapping problem with obtaining their descriptors.
  127. inline bool IsDescriptorProto(const Descriptor* descriptor) {
  128. return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" ||
  129. descriptor->file()->name() == "google/protobuf/descriptor.proto";
  130. }
  131. // Returns the stored type string used by the experimental runtime for oneof
  132. // fields.
  133. std::string GetOneofStoredType(const FieldDescriptor* field);
  134. // Whether we should generate multiple java files for messages.
  135. inline bool MultipleJavaFiles(const FileDescriptor* descriptor,
  136. bool immutable) {
  137. return descriptor->options().java_multiple_files();
  138. }
  139. // Returns true if `descriptor` will be written to its own .java file.
  140. // `immutable` should be set to true if we're generating for the immutable API.
  141. template <typename Descriptor>
  142. bool IsOwnFile(const Descriptor* descriptor, bool immutable) {
  143. return descriptor->containing_type() == NULL &&
  144. MultipleJavaFiles(descriptor->file(), immutable);
  145. }
  146. template <>
  147. inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
  148. return MultipleJavaFiles(descriptor->file(), immutable);
  149. }
  150. // If `descriptor` describes an object with its own .java file,
  151. // returns the name (relative to that .java file) of the file that stores
  152. // annotation data for that descriptor. `suffix` is usually empty, but may
  153. // (e.g.) be "OrBuilder" for some generated interfaces.
  154. template <typename Descriptor>
  155. std::string AnnotationFileName(const Descriptor* descriptor,
  156. const std::string& suffix) {
  157. return descriptor->name() + suffix + ".java.pb.meta";
  158. }
  159. template <typename Descriptor>
  160. void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
  161. Descriptor* descriptor, bool immutable,
  162. const std::string& suffix = "") {
  163. if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) {
  164. PrintGeneratedAnnotation(printer, '$',
  165. AnnotationFileName(descriptor, suffix));
  166. }
  167. }
  168. // Get the unqualified name that should be used for a field's field
  169. // number constant.
  170. std::string FieldConstantName(const FieldDescriptor* field);
  171. // Returns the type of the FieldDescriptor.
  172. // This does nothing interesting for the open source release, but is used for
  173. // hacks that improve compatibility with version 1 protocol buffers at Google.
  174. FieldDescriptor::Type GetType(const FieldDescriptor* field);
  175. enum JavaType {
  176. JAVATYPE_INT,
  177. JAVATYPE_LONG,
  178. JAVATYPE_FLOAT,
  179. JAVATYPE_DOUBLE,
  180. JAVATYPE_BOOLEAN,
  181. JAVATYPE_STRING,
  182. JAVATYPE_BYTES,
  183. JAVATYPE_ENUM,
  184. JAVATYPE_MESSAGE
  185. };
  186. JavaType GetJavaType(const FieldDescriptor* field);
  187. const char* PrimitiveTypeName(JavaType type);
  188. // Get the fully-qualified class name for a boxed primitive type, e.g.
  189. // "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message
  190. // types.
  191. const char* BoxedPrimitiveTypeName(JavaType type);
  192. // Get the name of the java enum constant representing this type. E.g.,
  193. // "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
  194. // name is "com.google.protobuf.WireFormat.FieldType.INT32".
  195. const char* FieldTypeName(const FieldDescriptor::Type field_type);
  196. class ClassNameResolver;
  197. std::string DefaultValue(const FieldDescriptor* field, bool immutable,
  198. ClassNameResolver* name_resolver);
  199. inline std::string ImmutableDefaultValue(const FieldDescriptor* field,
  200. ClassNameResolver* name_resolver) {
  201. return DefaultValue(field, true, name_resolver);
  202. }
  203. bool IsDefaultValueJavaDefault(const FieldDescriptor* field);
  204. bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field);
  205. // Does this message class have descriptor and reflection methods?
  206. inline bool HasDescriptorMethods(const Descriptor* descriptor,
  207. bool enforce_lite) {
  208. return !enforce_lite;
  209. }
  210. inline bool HasDescriptorMethods(const EnumDescriptor* descriptor,
  211. bool enforce_lite) {
  212. return !enforce_lite;
  213. }
  214. inline bool HasDescriptorMethods(const FileDescriptor* descriptor,
  215. bool enforce_lite) {
  216. return !enforce_lite;
  217. }
  218. // Should we generate generic services for this file?
  219. inline bool HasGenericServices(const FileDescriptor* file, bool enforce_lite) {
  220. return file->service_count() > 0 &&
  221. HasDescriptorMethods(file, enforce_lite) &&
  222. file->options().java_generic_services();
  223. }
  224. // Methods for shared bitfields.
  225. // Gets the name of the shared bitfield for the given index.
  226. std::string GetBitFieldName(int index);
  227. // Gets the name of the shared bitfield for the given bit index.
  228. // Effectively, GetBitFieldName(bitIndex / 32)
  229. std::string GetBitFieldNameForBit(int bitIndex);
  230. // Generates the java code for the expression that returns the boolean value
  231. // of the bit of the shared bitfields for the given bit index.
  232. // Example: "((bitField1_ & 0x04) == 0x04)"
  233. std::string GenerateGetBit(int bitIndex);
  234. // Generates the java code for the expression that sets the bit of the shared
  235. // bitfields for the given bit index.
  236. // Example: "bitField1_ = (bitField1_ | 0x04)"
  237. std::string GenerateSetBit(int bitIndex);
  238. // Generates the java code for the expression that clears the bit of the shared
  239. // bitfields for the given bit index.
  240. // Example: "bitField1_ = (bitField1_ & ~0x04)"
  241. std::string GenerateClearBit(int bitIndex);
  242. // Does the same as GenerateGetBit but operates on the bit field on a local
  243. // variable. This is used by the builder to copy the value in the builder to
  244. // the message.
  245. // Example: "((from_bitField1_ & 0x04) == 0x04)"
  246. std::string GenerateGetBitFromLocal(int bitIndex);
  247. // Does the same as GenerateSetBit but operates on the bit field on a local
  248. // variable. This is used by the builder to copy the value in the builder to
  249. // the message.
  250. // Example: "to_bitField1_ = (to_bitField1_ | 0x04)"
  251. std::string GenerateSetBitToLocal(int bitIndex);
  252. // Does the same as GenerateGetBit but operates on the bit field on a local
  253. // variable. This is used by the parsing constructor to record if a repeated
  254. // field is mutable.
  255. // Example: "((mutable_bitField1_ & 0x04) == 0x04)"
  256. std::string GenerateGetBitMutableLocal(int bitIndex);
  257. // Does the same as GenerateSetBit but operates on the bit field on a local
  258. // variable. This is used by the parsing constructor to record if a repeated
  259. // field is mutable.
  260. // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)"
  261. std::string GenerateSetBitMutableLocal(int bitIndex);
  262. // Returns whether the JavaType is a reference type.
  263. bool IsReferenceType(JavaType type);
  264. // Returns the capitalized name for calling relative functions in
  265. // CodedInputStream
  266. const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable);
  267. // For encodings with fixed sizes, returns that size in bytes. Otherwise
  268. // returns -1.
  269. int FixedSize(FieldDescriptor::Type type);
  270. // Comparators used to sort fields in MessageGenerator
  271. struct FieldOrderingByNumber {
  272. inline bool operator()(const FieldDescriptor* a,
  273. const FieldDescriptor* b) const {
  274. return a->number() < b->number();
  275. }
  276. };
  277. struct ExtensionRangeOrdering {
  278. bool operator()(const Descriptor::ExtensionRange* a,
  279. const Descriptor::ExtensionRange* b) const {
  280. return a->start < b->start;
  281. }
  282. };
  283. // Sort the fields of the given Descriptor by number into a new[]'d array
  284. // and return it. The caller should delete the returned array.
  285. const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor);
  286. // Does this message class have any packed fields?
  287. inline bool HasPackedFields(const Descriptor* descriptor) {
  288. for (int i = 0; i < descriptor->field_count(); i++) {
  289. if (descriptor->field(i)->is_packed()) {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. // Check a message type and its sub-message types recursively to see if any of
  296. // them has a required field. Return true if a required field is found.
  297. bool HasRequiredFields(const Descriptor* descriptor);
  298. // Whether a .proto file supports field presence test for non-message types.
  299. inline bool SupportFieldPresence(const FileDescriptor* descriptor) {
  300. return descriptor->syntax() != FileDescriptor::SYNTAX_PROTO3;
  301. }
  302. // Whether generate classes expose public PARSER instances.
  303. inline bool ExposePublicParser(const FileDescriptor* descriptor) {
  304. // TODO(liujisi): Mark the PARSER private in 3.1.x releases.
  305. return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
  306. }
  307. // Whether unknown enum values are kept (i.e., not stored in UnknownFieldSet
  308. // but in the message and can be queried using additional getters that return
  309. // ints.
  310. inline bool SupportUnknownEnumValue(const FileDescriptor* descriptor) {
  311. return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3;
  312. }
  313. // Check whether a mesasge has repeated fields.
  314. bool HasRepeatedFields(const Descriptor* descriptor);
  315. inline bool IsMapEntry(const Descriptor* descriptor) {
  316. return descriptor->options().map_entry();
  317. }
  318. inline bool IsMapField(const FieldDescriptor* descriptor) {
  319. return descriptor->is_map();
  320. }
  321. inline bool IsAnyMessage(const Descriptor* descriptor) {
  322. return descriptor->full_name() == "google.protobuf.Any";
  323. }
  324. inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) {
  325. return descriptor->name() == "google/protobuf/wrappers.proto";
  326. }
  327. inline bool CheckUtf8(const FieldDescriptor* descriptor) {
  328. return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
  329. descriptor->file()->options().java_string_check_utf8();
  330. }
  331. inline std::string GeneratedCodeVersionSuffix() {
  332. return "V3";
  333. }
  334. void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector<uint16>* output);
  335. inline void WriteIntToUtf16CharSequence(int value,
  336. std::vector<uint16>* output) {
  337. WriteUInt32ToUtf16CharSequence(static_cast<uint32>(value), output);
  338. }
  339. // Escape a UTF-16 character so it can be embedded in a Java string literal.
  340. void EscapeUtf16ToString(uint16 code, std::string* output);
  341. // Only the lowest two bytes of the return value are used. The lowest byte
  342. // is the integer value of a j/c/g/protobuf/FieldType enum. For the other
  343. // byte:
  344. // bit 0: whether the field is required.
  345. // bit 1: whether the field requires UTF-8 validation.
  346. // bit 2: whether the field needs isInitialized check.
  347. // bit 3: whether the field is a map field with proto2 enum value.
  348. // bits 4-7: unused
  349. int GetExperimentalJavaFieldType(const FieldDescriptor* field);
  350. // To get the total number of entries need to be built for experimental runtime
  351. // and the first field number that are not in the table part
  352. std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
  353. const FieldDescriptor** fields, int count);
  354. } // namespace java
  355. } // namespace compiler
  356. } // namespace protobuf
  357. } // namespace google
  358. #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__