• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
31 // Author: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 
35 #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
36 #define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
37 
38 #include <string>
39 #include <google/protobuf/compiler/java/java_context.h>
40 #include <google/protobuf/descriptor.pb.h>
41 #include <google/protobuf/io/printer.h>
42 #include <google/protobuf/descriptor.h>
43 
44 namespace google {
45 namespace protobuf {
46 namespace compiler {
47 namespace java {
48 
49 // Commonly-used separator comments.  Thick is a line of '=', thin is a line
50 // of '-'.
51 extern const char kThickSeparator[];
52 extern const char kThinSeparator[];
53 
54 // If annotation_file is non-empty, prints a javax.annotation.Generated
55 // annotation to the given Printer. annotation_file will be referenced in the
56 // annotation's comments field. delimiter should be the Printer's delimiter
57 // character. annotation_file will be included verbatim into a Java literal
58 // string, so it should not contain quotes or invalid Java escape sequences;
59 // however, these are unlikely to appear in practice, as the value of
60 // annotation_file should be generated from the filename of the source file
61 // being annotated (which in turn must be a Java identifier plus ".java").
62 void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
63                               const std::string& annotation_file = "");
64 
65 // If a GeneratedMessageLite contains non-lite enums, then its verifier
66 // must be instantiated inline, rather than retrieved from the enum class.
67 void PrintEnumVerifierLogic(io::Printer* printer,
68                             const FieldDescriptor* descriptor,
69                             const std::map<std::string, std::string>& variables,
70                             const char* var_name,
71                             const char* terminating_string, bool enforce_lite);
72 
73 // Converts a name to camel-case. If cap_first_letter is true, capitalize the
74 // first letter.
75 std::string UnderscoresToCamelCase(const std::string& name,
76                                    bool cap_first_letter);
77 // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
78 // "fooBarBaz" or "FooBarBaz", respectively.
79 std::string UnderscoresToCamelCase(const FieldDescriptor* field);
80 std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
81 
82 // Similar, but for method names.  (Typically, this merely has the effect
83 // of lower-casing the first letter of the name.)
84 std::string UnderscoresToCamelCase(const MethodDescriptor* method);
85 
86 // Same as UnderscoresToCamelCase, but checks for reserved keywords
87 std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field);
88 
89 // Similar to UnderscoresToCamelCase, but guarantees that the result is a
90 // complete Java identifier by adding a _ if needed.
91 std::string CamelCaseFieldName(const FieldDescriptor* field);
92 
93 // Get an identifier that uniquely identifies this type within the file.
94 // This is used to declare static variables related to this type at the
95 // outermost file scope.
96 std::string UniqueFileScopeIdentifier(const Descriptor* descriptor);
97 
98 // Strips ".proto" or ".protodevel" from the end of a filename.
99 std::string StripProto(const std::string& filename);
100 
101 // Gets the unqualified class name for the file.  For each .proto file, there
102 // will be one Java class containing all the immutable messages and another
103 // Java class containing all the mutable messages.
104 // TODO(xiaofeng): remove the default value after updating client code.
105 std::string FileClassName(const FileDescriptor* file, bool immutable = true);
106 
107 // Returns the file's Java package name.
108 std::string FileJavaPackage(const FileDescriptor* file);
109 std::string FileJavaPackage(const FileDescriptor* file, bool immutable);
110 
111 // Returns output directory for the given package name.
112 std::string JavaPackageToDir(std::string package_name);
113 
114 // TODO(xiaofeng): the following methods are kept for they are exposed
115 // publicly in //net/proto2/compiler/java/public/names.h. They return
116 // immutable names only and should be removed after mutable API is
117 // integrated into google3.
118 std::string ClassName(const Descriptor* descriptor);
119 std::string ClassName(const EnumDescriptor* descriptor);
120 std::string ClassName(const ServiceDescriptor* descriptor);
121 std::string ClassName(const FileDescriptor* descriptor);
122 
123 // Comma-separate list of option-specified interfaces implemented by the
124 // Message, to follow the "implements" declaration of the Message definition.
125 std::string ExtraMessageInterfaces(const Descriptor* descriptor);
126 // Comma-separate list of option-specified interfaces implemented by the
127 // MutableMessage, to follow the "implements" declaration of the MutableMessage
128 // definition.
129 std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
130 // Comma-separate list of option-specified interfaces implemented by the
131 // Builder, to follow the "implements" declaration of the Builder definition.
132 std::string ExtraBuilderInterfaces(const Descriptor* descriptor);
133 // Comma-separate list of option-specified interfaces extended by the
134 // MessageOrBuilder, to follow the "extends" declaration of the
135 // MessageOrBuilder definition.
136 std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
137 
138 // Get the unqualified Java class name for mutable messages. i.e. without
139 // package or outer classnames.
ShortMutableJavaClassName(const Descriptor * descriptor)140 inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) {
141   return descriptor->name();
142 }
143 
144 // Whether the given descriptor is for one of the core descriptor protos. We
145 // cannot currently use the new runtime with core protos since there is a
146 // bootstrapping problem with obtaining their descriptors.
IsDescriptorProto(const Descriptor * descriptor)147 inline bool IsDescriptorProto(const Descriptor* descriptor) {
148   return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" ||
149          descriptor->file()->name() == "google/protobuf/descriptor.proto";
150 }
151 
152 // Returns the stored type string used by the experimental runtime for oneof
153 // fields.
154 std::string GetOneofStoredType(const FieldDescriptor* field);
155 
156 
157 // Whether we should generate multiple java files for messages.
MultipleJavaFiles(const FileDescriptor * descriptor,bool immutable)158 inline bool MultipleJavaFiles(const FileDescriptor* descriptor,
159                               bool immutable) {
160   return descriptor->options().java_multiple_files();
161 }
162 
163 
164 // Returns true if `descriptor` will be written to its own .java file.
165 // `immutable` should be set to true if we're generating for the immutable API.
166 template <typename Descriptor>
IsOwnFile(const Descriptor * descriptor,bool immutable)167 bool IsOwnFile(const Descriptor* descriptor, bool immutable) {
168   return descriptor->containing_type() == NULL &&
169          MultipleJavaFiles(descriptor->file(), immutable);
170 }
171 
172 template <>
IsOwnFile(const ServiceDescriptor * descriptor,bool immutable)173 inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
174   return MultipleJavaFiles(descriptor->file(), immutable);
175 }
176 
177 // If `descriptor` describes an object with its own .java file,
178 // returns the name (relative to that .java file) of the file that stores
179 // annotation data for that descriptor. `suffix` is usually empty, but may
180 // (e.g.) be "OrBuilder" for some generated interfaces.
181 template <typename Descriptor>
AnnotationFileName(const Descriptor * descriptor,const std::string & suffix)182 std::string AnnotationFileName(const Descriptor* descriptor,
183                                const std::string& suffix) {
184   return descriptor->name() + suffix + ".java.pb.meta";
185 }
186 
187 template <typename Descriptor>
188 void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
189                                    Descriptor* descriptor, bool immutable,
190                                    const std::string& suffix = "") {
191   if (IsOwnFile(descriptor, immutable)) {
192     PrintGeneratedAnnotation(printer, '$',
193                              context->options().annotate_code
194                                  ? AnnotationFileName(descriptor, suffix)
195                                  : "");
196   }
197 }
198 
199 // Get the unqualified name that should be used for a field's field
200 // number constant.
201 std::string FieldConstantName(const FieldDescriptor* field);
202 
203 // Returns the type of the FieldDescriptor.
204 // This does nothing interesting for the open source release, but is used for
205 // hacks that improve compatibility with version 1 protocol buffers at Google.
206 FieldDescriptor::Type GetType(const FieldDescriptor* field);
207 
208 enum JavaType {
209   JAVATYPE_INT,
210   JAVATYPE_LONG,
211   JAVATYPE_FLOAT,
212   JAVATYPE_DOUBLE,
213   JAVATYPE_BOOLEAN,
214   JAVATYPE_STRING,
215   JAVATYPE_BYTES,
216   JAVATYPE_ENUM,
217   JAVATYPE_MESSAGE
218 };
219 
220 JavaType GetJavaType(const FieldDescriptor* field);
221 
222 const char* PrimitiveTypeName(JavaType type);
223 
224 // Get the fully-qualified class name for a boxed primitive type, e.g.
225 // "java.lang.Integer" for JAVATYPE_INT.  Returns NULL for enum and message
226 // types.
227 const char* BoxedPrimitiveTypeName(JavaType type);
228 
229 
230 // Get the name of the java enum constant representing this type. E.g.,
231 // "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
232 // name is "com.google.protobuf.WireFormat.FieldType.INT32".
233 const char* FieldTypeName(const FieldDescriptor::Type field_type);
234 
235 class ClassNameResolver;
236 std::string DefaultValue(const FieldDescriptor* field, bool immutable,
237                          ClassNameResolver* name_resolver);
ImmutableDefaultValue(const FieldDescriptor * field,ClassNameResolver * name_resolver)238 inline std::string ImmutableDefaultValue(const FieldDescriptor* field,
239                                          ClassNameResolver* name_resolver) {
240   return DefaultValue(field, true, name_resolver);
241 }
242 bool IsDefaultValueJavaDefault(const FieldDescriptor* field);
243 bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field);
244 
245 // Does this message class have descriptor and reflection methods?
HasDescriptorMethods(const Descriptor * descriptor,bool enforce_lite)246 inline bool HasDescriptorMethods(const Descriptor* descriptor,
247                                  bool enforce_lite) {
248   return !enforce_lite;
249 }
HasDescriptorMethods(const EnumDescriptor * descriptor,bool enforce_lite)250 inline bool HasDescriptorMethods(const EnumDescriptor* descriptor,
251                                  bool enforce_lite) {
252   return !enforce_lite;
253 }
HasDescriptorMethods(const FileDescriptor * descriptor,bool enforce_lite)254 inline bool HasDescriptorMethods(const FileDescriptor* descriptor,
255                                  bool enforce_lite) {
256   return !enforce_lite;
257 }
258 
259 // Should we generate generic services for this file?
HasGenericServices(const FileDescriptor * file,bool enforce_lite)260 inline bool HasGenericServices(const FileDescriptor* file, bool enforce_lite) {
261   return file->service_count() > 0 &&
262          HasDescriptorMethods(file, enforce_lite) &&
263          file->options().java_generic_services();
264 }
265 
266 // Methods for shared bitfields.
267 
268 // Gets the name of the shared bitfield for the given index.
269 std::string GetBitFieldName(int index);
270 
271 // Gets the name of the shared bitfield for the given bit index.
272 // Effectively, GetBitFieldName(bitIndex / 32)
273 std::string GetBitFieldNameForBit(int bitIndex);
274 
275 // Generates the java code for the expression that returns the boolean value
276 // of the bit of the shared bitfields for the given bit index.
277 // Example: "((bitField1_ & 0x04) == 0x04)"
278 std::string GenerateGetBit(int bitIndex);
279 
280 // Generates the java code for the expression that sets the bit of the shared
281 // bitfields for the given bit index.
282 // Example: "bitField1_ = (bitField1_ | 0x04)"
283 std::string GenerateSetBit(int bitIndex);
284 
285 // Generates the java code for the expression that clears the bit of the shared
286 // bitfields for the given bit index.
287 // Example: "bitField1_ = (bitField1_ & ~0x04)"
288 std::string GenerateClearBit(int bitIndex);
289 
290 // Does the same as GenerateGetBit but operates on the bit field on a local
291 // variable. This is used by the builder to copy the value in the builder to
292 // the message.
293 // Example: "((from_bitField1_ & 0x04) == 0x04)"
294 std::string GenerateGetBitFromLocal(int bitIndex);
295 
296 // Does the same as GenerateSetBit but operates on the bit field on a local
297 // variable. This is used by the builder to copy the value in the builder to
298 // the message.
299 // Example: "to_bitField1_ = (to_bitField1_ | 0x04)"
300 std::string GenerateSetBitToLocal(int bitIndex);
301 
302 // Does the same as GenerateGetBit but operates on the bit field on a local
303 // variable. This is used by the parsing constructor to record if a repeated
304 // field is mutable.
305 // Example: "((mutable_bitField1_ & 0x04) == 0x04)"
306 std::string GenerateGetBitMutableLocal(int bitIndex);
307 
308 // Does the same as GenerateSetBit but operates on the bit field on a local
309 // variable. This is used by the parsing constructor to record if a repeated
310 // field is mutable.
311 // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)"
312 std::string GenerateSetBitMutableLocal(int bitIndex);
313 
314 // Returns whether the JavaType is a reference type.
315 bool IsReferenceType(JavaType type);
316 
317 // Returns the capitalized name for calling relative functions in
318 // CodedInputStream
319 const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable);
320 
321 // For encodings with fixed sizes, returns that size in bytes.  Otherwise
322 // returns -1.
323 int FixedSize(FieldDescriptor::Type type);
324 
325 // Comparators used to sort fields in MessageGenerator
326 struct FieldOrderingByNumber {
operatorFieldOrderingByNumber327   inline bool operator()(const FieldDescriptor* a,
328                          const FieldDescriptor* b) const {
329     return a->number() < b->number();
330   }
331 };
332 
333 struct ExtensionRangeOrdering {
operatorExtensionRangeOrdering334   bool operator()(const Descriptor::ExtensionRange* a,
335                   const Descriptor::ExtensionRange* b) const {
336     return a->start < b->start;
337   }
338 };
339 
340 // Sort the fields of the given Descriptor by number into a new[]'d array
341 // and return it. The caller should delete the returned array.
342 const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor);
343 
344 // Does this message class have any packed fields?
HasPackedFields(const Descriptor * descriptor)345 inline bool HasPackedFields(const Descriptor* descriptor) {
346   for (int i = 0; i < descriptor->field_count(); i++) {
347     if (descriptor->field(i)->is_packed()) {
348       return true;
349     }
350   }
351   return false;
352 }
353 
354 // Check a message type and its sub-message types recursively to see if any of
355 // them has a required field. Return true if a required field is found.
356 bool HasRequiredFields(const Descriptor* descriptor);
357 
IsProto2(const FileDescriptor * descriptor)358 inline bool IsProto2(const FileDescriptor* descriptor) {
359   return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
360 }
361 
SupportFieldPresence(const FieldDescriptor * descriptor)362 inline bool SupportFieldPresence(const FieldDescriptor* descriptor) {
363   // Note that while proto3 oneofs do conceptually support present, we return
364   // false for them because they do not offer a public hazzer. Therefore this
365   // method could be named HasHazzer().
366   return !descriptor->is_repeated() &&
367          (descriptor->message_type() || descriptor->has_optional_keyword() ||
368           IsProto2(descriptor->file()));
369 }
370 
IsRealOneof(const FieldDescriptor * descriptor)371 inline bool IsRealOneof(const FieldDescriptor* descriptor) {
372   return descriptor->containing_oneof() &&
373          !descriptor->containing_oneof()->is_synthetic();
374 }
375 
HasHasbit(const FieldDescriptor * descriptor)376 inline bool HasHasbit(const FieldDescriptor* descriptor) {
377   // Note that currently message fields inside oneofs have hasbits. This is
378   // surprising, as the oneof case should avoid any need for a hasbit. But if
379   // you change this method to remove hasbits for oneofs, a few tests fail.
380   return !descriptor->is_repeated() &&
381          (descriptor->has_optional_keyword() || IsProto2(descriptor->file()));
382 }
383 
384 // Whether generate classes expose public PARSER instances.
ExposePublicParser(const FileDescriptor * descriptor)385 inline bool ExposePublicParser(const FileDescriptor* descriptor) {
386   // TODO(liujisi): Mark the PARSER private in 3.1.x releases.
387   return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
388 }
389 
390 // Whether unknown enum values are kept (i.e., not stored in UnknownFieldSet
391 // but in the message and can be queried using additional getters that return
392 // ints.
SupportUnknownEnumValue(const FileDescriptor * descriptor)393 inline bool SupportUnknownEnumValue(const FileDescriptor* descriptor) {
394   return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3;
395 }
396 
SupportUnknownEnumValue(const FieldDescriptor * field)397 inline bool SupportUnknownEnumValue(const FieldDescriptor* field) {
398   return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
399 }
400 
401 // Check whether a message has repeated fields.
402 bool HasRepeatedFields(const Descriptor* descriptor);
403 
IsMapEntry(const Descriptor * descriptor)404 inline bool IsMapEntry(const Descriptor* descriptor) {
405   return descriptor->options().map_entry();
406 }
407 
IsMapField(const FieldDescriptor * descriptor)408 inline bool IsMapField(const FieldDescriptor* descriptor) {
409   return descriptor->is_map();
410 }
411 
IsAnyMessage(const Descriptor * descriptor)412 inline bool IsAnyMessage(const Descriptor* descriptor) {
413   return descriptor->full_name() == "google.protobuf.Any";
414 }
415 
IsWrappersProtoFile(const FileDescriptor * descriptor)416 inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) {
417   return descriptor->name() == "google/protobuf/wrappers.proto";
418 }
419 
CheckUtf8(const FieldDescriptor * descriptor)420 inline bool CheckUtf8(const FieldDescriptor* descriptor) {
421   return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
422          descriptor->file()->options().java_string_check_utf8();
423 }
424 
GeneratedCodeVersionSuffix()425 inline std::string GeneratedCodeVersionSuffix() {
426   return "V3";
427 }
428 
429 void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector<uint16>* output);
430 
WriteIntToUtf16CharSequence(int value,std::vector<uint16> * output)431 inline void WriteIntToUtf16CharSequence(int value,
432                                         std::vector<uint16>* output) {
433   WriteUInt32ToUtf16CharSequence(static_cast<uint32>(value), output);
434 }
435 
436 // Escape a UTF-16 character so it can be embedded in a Java string literal.
437 void EscapeUtf16ToString(uint16 code, std::string* output);
438 
439 // Only the lowest two bytes of the return value are used. The lowest byte
440 // is the integer value of a j/c/g/protobuf/FieldType enum. For the other
441 // byte:
442 //    bit 0: whether the field is required.
443 //    bit 1: whether the field requires UTF-8 validation.
444 //    bit 2: whether the field needs isInitialized check.
445 //    bit 3: whether the field is a map field with proto2 enum value.
446 //    bits 4-7: unused
447 int GetExperimentalJavaFieldType(const FieldDescriptor* field);
448 
449 // To get the total number of entries need to be built for experimental runtime
450 // and the first field number that are not in the table part
451 std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
452     const FieldDescriptor** fields, int count);
453 }  // namespace java
454 }  // namespace compiler
455 }  // namespace protobuf
456 }  // namespace google
457 
458 #endif  // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
459