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