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/io/printer.h>
41 #include <google/protobuf/descriptor.pb.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 string& annotation_file = "");
64 
65 // Converts a name to camel-case. If cap_first_letter is true, capitalize the
66 // first letter.
67 string UnderscoresToCamelCase(const string& name, bool cap_first_letter);
68 // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
69 // "fooBarBaz" or "FooBarBaz", respectively.
70 string UnderscoresToCamelCase(const FieldDescriptor* field);
71 string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
72 
73 // Similar, but for method names.  (Typically, this merely has the effect
74 // of lower-casing the first letter of the name.)
75 string UnderscoresToCamelCase(const MethodDescriptor* method);
76 
77 // Get an identifier that uniquely identifies this type within the file.
78 // This is used to declare static variables related to this type at the
79 // outermost file scope.
80 string UniqueFileScopeIdentifier(const Descriptor* descriptor);
81 
82 // Strips ".proto" or ".protodevel" from the end of a filename.
83 string StripProto(const string& filename);
84 
85 // Gets the unqualified class name for the file.  For each .proto file, there
86 // will be one Java class containing all the immutable messages and another
87 // Java class containing all the mutable messages.
88 // TODO(xiaofeng): remove the default value after updating client code.
89 string FileClassName(const FileDescriptor* file, bool immutable = true);
90 
91 // Returns the file's Java package name.
92 string FileJavaPackage(const FileDescriptor* file, bool immutable = true);
93 
94 // Returns output directory for the given package name.
95 string JavaPackageToDir(string package_name);
96 
97 // Converts the given fully-qualified name in the proto namespace to its
98 // fully-qualified name in the Java namespace, given that it is in the given
99 // file.
100 // TODO(xiaofeng): this method is deprecated and should be removed in the
101 // future.
102 string ToJavaName(const string& full_name,
103                   const FileDescriptor* file);
104 
105 // TODO(xiaofeng): the following methods are kept for they are exposed
106 // publicly in //google/protobuf/compiler/java/names.h. They return
107 // immutable names only and should be removed after mutable API is
108 // integrated into google3.
109 string ClassName(const Descriptor* descriptor);
110 string ClassName(const EnumDescriptor* descriptor);
111 string ClassName(const ServiceDescriptor* descriptor);
112 string ClassName(const FileDescriptor* descriptor);
113 
114 // Comma-separate list of option-specified interfaces implemented by the
115 // Message, to follow the "implements" declaration of the Message definition.
116 string ExtraMessageInterfaces(const Descriptor* descriptor);
117 // Comma-separate list of option-specified interfaces implemented by the
118 // MutableMessage, to follow the "implements" declaration of the MutableMessage
119 // definition.
120 string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
121 // Comma-separate list of option-specified interfaces implemented by the
122 // Builder, to follow the "implements" declaration of the Builder definition.
123 string ExtraBuilderInterfaces(const Descriptor* descriptor);
124 // Comma-separate list of option-specified interfaces extended by the
125 // MessageOrBuilder, to follow the "extends" declaration of the
126 // MessageOrBuilder definition.
127 string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
128 
129 // Get the unqualified Java class name for mutable messages. i.e. without
130 // package or outer classnames.
ShortMutableJavaClassName(const Descriptor * descriptor)131 inline string ShortMutableJavaClassName(const Descriptor* descriptor) {
132   return descriptor->name();
133 }
134 
135 
136 // Whether we should generate multiple java files for messages.
MultipleJavaFiles(const FileDescriptor * descriptor,bool immutable)137 inline bool MultipleJavaFiles(
138     const FileDescriptor* descriptor, bool immutable) {
139   return descriptor->options().java_multiple_files();
140 }
141 
142 // Returns true if `descriptor` will be written to its own .java file.
143 // `immutable` should be set to true if we're generating for the immutable API.
144 template <typename Descriptor>
IsOwnFile(const Descriptor * descriptor,bool immutable)145 bool IsOwnFile(const Descriptor* descriptor, bool immutable) {
146   return descriptor->containing_type() == NULL &&
147          MultipleJavaFiles(descriptor->file(), immutable);
148 }
149 
150 template <>
IsOwnFile(const ServiceDescriptor * descriptor,bool immutable)151 inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
152   return MultipleJavaFiles(descriptor->file(), immutable);
153 }
154 
155 // If `descriptor` describes an object with its own .java file,
156 // returns the name (relative to that .java file) of the file that stores
157 // annotation data for that descriptor. `suffix` is usually empty, but may
158 // (e.g.) be "OrBuilder" for some generated interfaces.
159 template <typename Descriptor>
AnnotationFileName(const Descriptor * descriptor,const string & suffix)160 string AnnotationFileName(const Descriptor* descriptor, const string& suffix) {
161   return descriptor->name() + suffix + ".java.pb.meta";
162 }
163 
164 template <typename Descriptor>
165 void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
166                                    Descriptor* descriptor, bool immutable,
167                                    const string& suffix = "") {
168   if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) {
169     PrintGeneratedAnnotation(printer, '$',
170                              AnnotationFileName(descriptor, suffix));
171   }
172 }
173 
174 // Get the unqualified name that should be used for a field's field
175 // number constant.
176 string FieldConstantName(const FieldDescriptor *field);
177 
178 // Returns the type of the FieldDescriptor.
179 // This does nothing interesting for the open source release, but is used for
180 // hacks that improve compatibility with version 1 protocol buffers at Google.
181 FieldDescriptor::Type GetType(const FieldDescriptor* field);
182 
183 enum JavaType {
184   JAVATYPE_INT,
185   JAVATYPE_LONG,
186   JAVATYPE_FLOAT,
187   JAVATYPE_DOUBLE,
188   JAVATYPE_BOOLEAN,
189   JAVATYPE_STRING,
190   JAVATYPE_BYTES,
191   JAVATYPE_ENUM,
192   JAVATYPE_MESSAGE
193 };
194 
195 JavaType GetJavaType(const FieldDescriptor* field);
196 
197 const char* PrimitiveTypeName(JavaType type);
198 
199 // Get the fully-qualified class name for a boxed primitive type, e.g.
200 // "java.lang.Integer" for JAVATYPE_INT.  Returns NULL for enum and message
201 // types.
202 const char* BoxedPrimitiveTypeName(JavaType type);
203 
204 // Get the name of the java enum constant representing this type. E.g.,
205 // "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
206 // name is "com.google.protobuf.WireFormat.FieldType.INT32".
207 const char* FieldTypeName(const FieldDescriptor::Type field_type);
208 
209 class ClassNameResolver;
210 string DefaultValue(const FieldDescriptor* field, bool immutable,
211                     ClassNameResolver* name_resolver);
ImmutableDefaultValue(const FieldDescriptor * field,ClassNameResolver * name_resolver)212 inline string ImmutableDefaultValue(const FieldDescriptor* field,
213                                     ClassNameResolver* name_resolver) {
214   return DefaultValue(field, true, name_resolver);
215 }
216 bool IsDefaultValueJavaDefault(const FieldDescriptor* field);
217 bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field);
218 
219 // Does this message class have descriptor and reflection methods?
HasDescriptorMethods(const Descriptor * descriptor,bool enforce_lite)220 inline bool HasDescriptorMethods(const Descriptor* descriptor,
221                                  bool enforce_lite) {
222   return !enforce_lite &&
223          descriptor->file()->options().optimize_for() !=
224              FileOptions::LITE_RUNTIME;
225 }
HasDescriptorMethods(const EnumDescriptor * descriptor,bool enforce_lite)226 inline bool HasDescriptorMethods(const EnumDescriptor* descriptor,
227                                  bool enforce_lite) {
228   return !enforce_lite &&
229          descriptor->file()->options().optimize_for() !=
230              FileOptions::LITE_RUNTIME;
231 }
HasDescriptorMethods(const FileDescriptor * descriptor,bool enforce_lite)232 inline bool HasDescriptorMethods(const FileDescriptor* descriptor,
233                                  bool enforce_lite) {
234   return !enforce_lite &&
235          descriptor->options().optimize_for() != FileOptions::LITE_RUNTIME;
236 }
237 
238 // Should we generate generic services for this file?
HasGenericServices(const FileDescriptor * file,bool enforce_lite)239 inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) {
240   return file->service_count() > 0 &&
241          HasDescriptorMethods(file, enforce_lite) &&
242          file->options().java_generic_services();
243 }
244 
IsLazy(const FieldDescriptor * descriptor,bool enforce_lite)245 inline bool IsLazy(const FieldDescriptor* descriptor, bool enforce_lite) {
246   // Currently, the proto-lite version supports lazy field.
247   // TODO(niwasaki): Support lazy fields also for other proto runtimes.
248   if (HasDescriptorMethods(descriptor->file(), enforce_lite)) {
249     return false;
250   }
251   return descriptor->options().lazy();
252 }
253 
254 // Methods for shared bitfields.
255 
256 // Gets the name of the shared bitfield for the given index.
257 string GetBitFieldName(int index);
258 
259 // Gets the name of the shared bitfield for the given bit index.
260 // Effectively, GetBitFieldName(bitIndex / 32)
261 string GetBitFieldNameForBit(int bitIndex);
262 
263 // Generates the java code for the expression that returns the boolean value
264 // of the bit of the shared bitfields for the given bit index.
265 // Example: "((bitField1_ & 0x04) == 0x04)"
266 string GenerateGetBit(int bitIndex);
267 
268 // Generates the java code for the expression that sets the bit of the shared
269 // bitfields for the given bit index.
270 // Example: "bitField1_ = (bitField1_ | 0x04)"
271 string GenerateSetBit(int bitIndex);
272 
273 // Generates the java code for the expression that clears the bit of the shared
274 // bitfields for the given bit index.
275 // Example: "bitField1_ = (bitField1_ & ~0x04)"
276 string GenerateClearBit(int bitIndex);
277 
278 // Does the same as GenerateGetBit but operates on the bit field on a local
279 // variable. This is used by the builder to copy the value in the builder to
280 // the message.
281 // Example: "((from_bitField1_ & 0x04) == 0x04)"
282 string GenerateGetBitFromLocal(int bitIndex);
283 
284 // Does the same as GenerateSetBit but operates on the bit field on a local
285 // variable. This is used by the builder to copy the value in the builder to
286 // the message.
287 // Example: "to_bitField1_ = (to_bitField1_ | 0x04)"
288 string GenerateSetBitToLocal(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 parsing constructor to record if a repeated
292 // field is mutable.
293 // Example: "((mutable_bitField1_ & 0x04) == 0x04)"
294 string GenerateGetBitMutableLocal(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 parsing constructor to record if a repeated
298 // field is mutable.
299 // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)"
300 string GenerateSetBitMutableLocal(int bitIndex);
301 
302 // Returns whether the JavaType is a reference type.
303 bool IsReferenceType(JavaType type);
304 
305 // Returns the capitalized name for calling relative functions in
306 // CodedInputStream
307 const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable);
308 
309 // For encodings with fixed sizes, returns that size in bytes.  Otherwise
310 // returns -1.
311 int FixedSize(FieldDescriptor::Type type);
312 
313 // Comparators used to sort fields in MessageGenerator
314 struct FieldOrderingByNumber {
operatorFieldOrderingByNumber315   inline bool operator()(const FieldDescriptor* a,
316                          const FieldDescriptor* b) const {
317     return a->number() < b->number();
318   }
319 };
320 
321 struct ExtensionRangeOrdering {
operatorExtensionRangeOrdering322   bool operator()(const Descriptor::ExtensionRange* a,
323                   const Descriptor::ExtensionRange* b) const {
324     return a->start < b->start;
325   }
326 };
327 
328 // Sort the fields of the given Descriptor by number into a new[]'d array
329 // and return it. The caller should delete the returned array.
330 const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor);
331 
332 // Does this message class have any packed fields?
HasPackedFields(const Descriptor * descriptor)333 inline bool HasPackedFields(const Descriptor* descriptor) {
334   for (int i = 0; i < descriptor->field_count(); i++) {
335     if (descriptor->field(i)->is_packed()) {
336       return true;
337     }
338   }
339   return false;
340 }
341 
342 // Check a message type and its sub-message types recursively to see if any of
343 // them has a required field. Return true if a required field is found.
344 bool HasRequiredFields(const Descriptor* descriptor);
345 
346 // Whether a .proto file supports field presence test for non-message types.
SupportFieldPresence(const FileDescriptor * descriptor)347 inline bool SupportFieldPresence(const FileDescriptor* descriptor) {
348   return descriptor->syntax() != FileDescriptor::SYNTAX_PROTO3;
349 }
350 
351 // Whether generate classes expose public PARSER instances.
ExposePublicParser(const FileDescriptor * descriptor)352 inline bool ExposePublicParser(const FileDescriptor* descriptor) {
353   // TODO(liujisi): Mark the PARSER private in 3.1.x releases.
354   return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
355 }
356 
357 // Whether unknown enum values are kept (i.e., not stored in UnknownFieldSet
358 // but in the message and can be queried using additional getters that return
359 // ints.
SupportUnknownEnumValue(const FileDescriptor * descriptor)360 inline bool SupportUnknownEnumValue(const FileDescriptor* descriptor) {
361   return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3;
362 }
363 
364 // Check whether a mesasge has repeated fields.
365 bool HasRepeatedFields(const Descriptor* descriptor);
366 
IsMapEntry(const Descriptor * descriptor)367 inline bool IsMapEntry(const Descriptor* descriptor) {
368   return descriptor->options().map_entry();
369 }
370 
IsMapField(const FieldDescriptor * descriptor)371 inline bool IsMapField(const FieldDescriptor* descriptor) {
372   return descriptor->is_map();
373 }
374 
PreserveUnknownFields(const Descriptor * descriptor)375 inline bool PreserveUnknownFields(const Descriptor* descriptor) {
376   return descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3;
377 }
378 
IsAnyMessage(const Descriptor * descriptor)379 inline bool IsAnyMessage(const Descriptor* descriptor) {
380   return descriptor->full_name() == "google.protobuf.Any";
381 }
382 
CheckUtf8(const FieldDescriptor * descriptor)383 inline bool CheckUtf8(const FieldDescriptor* descriptor) {
384   return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
385       descriptor->file()->options().java_string_check_utf8();
386 }
387 
GeneratedCodeVersionSuffix()388 inline string GeneratedCodeVersionSuffix() {
389   return "V3";
390 }
391 }  // namespace java
392 }  // namespace compiler
393 }  // namespace protobuf
394 
395 }  // namespace google
396 #endif  // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
397