Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-31 10:11:58

0001 // Protocol Buffers - Google's data interchange format
0002 // Copyright 2008 Google Inc.  All rights reserved.
0003 //
0004 // Use of this source code is governed by a BSD-style
0005 // license that can be found in the LICENSE file or at
0006 // https://developers.google.com/open-source/licenses/bsd
0007 
0008 // Author: kenton@google.com (Kenton Varda)
0009 //  Based on original Protocol Buffers design by
0010 //  Sanjay Ghemawat, Jeff Dean, and others.
0011 
0012 #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
0013 #define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
0014 
0015 #include <cstdint>
0016 #include <string>
0017 
0018 #include "absl/strings/string_view.h"
0019 #include "google/protobuf/compiler/java/names.h"
0020 #include "google/protobuf/compiler/java/options.h"
0021 #include "google/protobuf/descriptor.h"
0022 #include "google/protobuf/descriptor.pb.h"
0023 #include "google/protobuf/io/printer.h"
0024 
0025 // Must be last.
0026 #include "google/protobuf/port_def.inc"
0027 
0028 namespace google {
0029 namespace protobuf {
0030 namespace compiler {
0031 namespace java {
0032 
0033 // Commonly-used separator comments.  Thick is a line of '=', thin is a line
0034 // of '-'.
0035 extern const char kThickSeparator[];
0036 extern const char kThinSeparator[];
0037 
0038 bool IsForbiddenKotlin(absl::string_view field_name);
0039 
0040 // If annotation_file is non-empty, prints a javax.annotation.Generated
0041 // annotation to the given Printer. annotation_file will be referenced in the
0042 // annotation's comments field. delimiter should be the Printer's delimiter
0043 // character. annotation_file will be included verbatim into a Java literal
0044 // string, so it should not contain quotes or invalid Java escape sequences;
0045 // however, these are unlikely to appear in practice, as the value of
0046 // annotation_file should be generated from the filename of the source file
0047 // being annotated (which in turn must be a Java identifier plus ".java").
0048 void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
0049                               absl::string_view annotation_file = "",
0050                               Options options = {});
0051 
0052 // If a GeneratedMessageLite contains non-lite enums, then its verifier
0053 // must be instantiated inline, rather than retrieved from the enum class.
0054 void PrintEnumVerifierLogic(
0055     io::Printer* printer, const FieldDescriptor* descriptor,
0056     const absl::flat_hash_map<absl::string_view, std::string>& variables,
0057     absl::string_view var_name, absl::string_view terminating_string,
0058     bool enforce_lite);
0059 
0060 // Prints the Protobuf Java Version validator checking that the runtime and
0061 // gencode versions are compatible.
0062 void PrintGencodeVersionValidator(io::Printer* printer, bool oss_runtime,
0063                                   absl::string_view java_class_name);
0064 
0065 // Converts a name to camel-case. If cap_first_letter is true, capitalize the
0066 // first letter.
0067 std::string ToCamelCase(absl::string_view input, bool lower_first);
0068 
0069 // Similar to UnderscoresToCamelCase, but guarantees that the result is a
0070 // complete Java identifier by adding a _ if needed.
0071 std::string CamelCaseFieldName(const FieldDescriptor* field);
0072 
0073 // Get an identifier that uniquely identifies this type within the file.
0074 // This is used to declare static variables related to this type at the
0075 // outermost file scope.
0076 std::string UniqueFileScopeIdentifier(const Descriptor* descriptor);
0077 
0078 // Gets the unqualified class name for the file.  For each .proto file, there
0079 // will be one Java class containing all the immutable messages and another
0080 // Java class containing all the mutable messages.
0081 std::string FileClassName(const FileDescriptor* file, bool immutable);
0082 
0083 // Returns the file's Java package name.
0084 std::string FileJavaPackage(const FileDescriptor* file, bool immutable,
0085                             Options options = {});
0086 
0087 // Returns output directory for the given package name.
0088 std::string JavaPackageToDir(std::string package_name);
0089 
0090 // Returns the name with Kotlin keywords enclosed in backticks
0091 std::string EscapeKotlinKeywords(std::string name);
0092 
0093 // Comma-separate list of option-specified interfaces implemented by the
0094 // Message, to follow the "implements" declaration of the Message definition.
0095 std::string ExtraMessageInterfaces(const Descriptor* descriptor);
0096 // Comma-separate list of option-specified interfaces implemented by the
0097 // MutableMessage, to follow the "implements" declaration of the MutableMessage
0098 // definition.
0099 std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
0100 // Comma-separate list of option-specified interfaces implemented by the
0101 // Builder, to follow the "implements" declaration of the Builder definition.
0102 std::string ExtraBuilderInterfaces(const Descriptor* descriptor);
0103 // Comma-separate list of option-specified interfaces extended by the
0104 // MessageOrBuilder, to follow the "extends" declaration of the
0105 // MessageOrBuilder definition.
0106 std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
0107 
0108 // Get the unqualified Java class name for mutable messages. i.e. without
0109 // package or outer classnames.
0110 inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) {
0111   return std::string(descriptor->name());
0112 }
0113 
0114 // Whether the given descriptor is for one of the core descriptor protos. We
0115 // cannot currently use the new runtime with core protos since there is a
0116 // bootstrapping problem with obtaining their descriptors.
0117 inline bool IsDescriptorProto(const Descriptor* descriptor) {
0118   return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" ||
0119          descriptor->file()->name() == "google/protobuf/descriptor.proto";
0120 }
0121 
0122 // Returns the stored type string used by the experimental runtime for oneof
0123 // fields.
0124 std::string GetOneofStoredType(const FieldDescriptor* field);
0125 
0126 // We use either the proto1 enums if the enum is generated, otherwise fall back
0127 // to use integers.
0128 enum class Proto1EnumRepresentation {
0129   kEnum,
0130   kInteger,
0131 };
0132 
0133 // Returns which representation we should use.
0134 inline Proto1EnumRepresentation GetProto1EnumRepresentation(
0135     const EnumDescriptor* descriptor) {
0136   if (descriptor->containing_type() != nullptr) {
0137     return Proto1EnumRepresentation::kEnum;
0138   }
0139   return Proto1EnumRepresentation::kInteger;
0140 }
0141 
0142 // Whether we should generate multiple java files for messages.
0143 inline bool MultipleJavaFiles(const FileDescriptor* descriptor,
0144                               bool immutable) {
0145   (void)immutable;
0146   return descriptor->options().java_multiple_files();
0147 }
0148 
0149 
0150 // Returns true if `descriptor` will be written to its own .java file.
0151 // `immutable` should be set to true if we're generating for the immutable API.
0152 template <typename Descriptor>
0153 bool IsOwnFile(const Descriptor* descriptor, bool immutable) {
0154   return descriptor->containing_type() == nullptr &&
0155          MultipleJavaFiles(descriptor->file(), immutable);
0156 }
0157 
0158 template <>
0159 inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
0160   return MultipleJavaFiles(descriptor->file(), immutable);
0161 }
0162 
0163 // If `descriptor` describes an object with its own .java file,
0164 // returns the name (relative to that .java file) of the file that stores
0165 // annotation data for that descriptor. `suffix` is usually empty, but may
0166 // (e.g.) be "OrBuilder" for some generated interfaces.
0167 template <typename Descriptor>
0168 std::string AnnotationFileName(const Descriptor* descriptor,
0169                                absl::string_view suffix) {
0170   return absl::StrCat(descriptor->name(), suffix, ".java.pb.meta");
0171 }
0172 
0173 // Get the unqualified name that should be used for a field's field
0174 // number constant.
0175 std::string FieldConstantName(const FieldDescriptor* field);
0176 
0177 // Returns the type of the FieldDescriptor.
0178 // This does nothing interesting for the open source release, but is used for
0179 // hacks that improve compatibility with version 1 protocol buffers at Google.
0180 FieldDescriptor::Type GetType(const FieldDescriptor* field);
0181 
0182 enum JavaType {
0183   JAVATYPE_INT,
0184   JAVATYPE_LONG,
0185   JAVATYPE_FLOAT,
0186   JAVATYPE_DOUBLE,
0187   JAVATYPE_BOOLEAN,
0188   JAVATYPE_STRING,
0189   JAVATYPE_BYTES,
0190   JAVATYPE_ENUM,
0191   JAVATYPE_MESSAGE
0192 };
0193 
0194 JavaType GetJavaType(const FieldDescriptor* field);
0195 
0196 absl::string_view PrimitiveTypeName(JavaType type);
0197 
0198 // Get the fully-qualified class name for a boxed primitive type, e.g.
0199 // "java.lang.Integer" for JAVATYPE_INT.  Returns NULL for enum and message
0200 // types.
0201 absl::string_view BoxedPrimitiveTypeName(JavaType type);
0202 
0203 // Kotlin source does not distinguish between primitives and non-primitives,
0204 // but does use Kotlin-specific qualified types for them.
0205 absl::string_view KotlinTypeName(JavaType type);
0206 
0207 // Get the name of the java enum constant representing this type. E.g.,
0208 // "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
0209 // name is "com.google.protobuf.WireFormat.FieldType.INT32".
0210 absl::string_view FieldTypeName(const FieldDescriptor::Type field_type);
0211 
0212 class ClassNameResolver;
0213 std::string DefaultValue(const FieldDescriptor* field, bool immutable,
0214                          ClassNameResolver* name_resolver,
0215                          Options options = {});
0216 inline std::string ImmutableDefaultValue(const FieldDescriptor* field,
0217                                          ClassNameResolver* name_resolver,
0218                                          Options options = {}) {
0219   return DefaultValue(field, true, name_resolver, options);
0220 }
0221 bool IsDefaultValueJavaDefault(const FieldDescriptor* field);
0222 bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field);
0223 
0224 // Does this message class have descriptor and reflection methods?
0225 inline bool HasDescriptorMethods(const Descriptor* /* descriptor */,
0226                                  bool enforce_lite) {
0227   return !enforce_lite;
0228 }
0229 inline bool HasDescriptorMethods(const EnumDescriptor* /* descriptor */,
0230                                  bool enforce_lite) {
0231   return !enforce_lite;
0232 }
0233 inline bool HasDescriptorMethods(const FileDescriptor* /* descriptor */,
0234                                  bool enforce_lite) {
0235   return !enforce_lite;
0236 }
0237 
0238 // Should we generate generic services for this file?
0239 inline bool HasGenericServices(const FileDescriptor* file, bool enforce_lite) {
0240   return file->service_count() > 0 &&
0241          HasDescriptorMethods(file, enforce_lite) &&
0242          file->options().java_generic_services();
0243 }
0244 
0245 // Methods for shared bitfields.
0246 
0247 // Gets the name of the shared bitfield for the given index.
0248 std::string GetBitFieldName(int index);
0249 
0250 // Gets the name of the shared bitfield for the given bit index.
0251 // Effectively, GetBitFieldName(bitIndex / 32)
0252 std::string GetBitFieldNameForBit(int bitIndex);
0253 
0254 // Generates the java code for the expression that returns the boolean value
0255 // of the bit of the shared bitfields for the given bit index.
0256 // Example: "((bitField1_ & 0x04) == 0x04)"
0257 std::string GenerateGetBit(int bitIndex);
0258 
0259 // Generates the java code for the expression that sets the bit of the shared
0260 // bitfields for the given bit index.
0261 // Example: "bitField1_ = (bitField1_ | 0x04)"
0262 std::string GenerateSetBit(int bitIndex);
0263 
0264 // Generates the java code for the expression that clears the bit of the shared
0265 // bitfields for the given bit index.
0266 // Example: "bitField1_ = (bitField1_ & ~0x04)"
0267 std::string GenerateClearBit(int bitIndex);
0268 
0269 // Does the same as GenerateGetBit but operates on the bit field on a local
0270 // variable. This is used by the builder to copy the value in the builder to
0271 // the message.
0272 // Example: "((from_bitField1_ & 0x04) == 0x04)"
0273 std::string GenerateGetBitFromLocal(int bitIndex);
0274 
0275 // Does the same as GenerateSetBit but operates on the bit field on a local
0276 // variable. This is used by the builder to copy the value in the builder to
0277 // the message.
0278 // Example: "to_bitField1_ = (to_bitField1_ | 0x04)"
0279 std::string GenerateSetBitToLocal(int bitIndex);
0280 
0281 // Does the same as GenerateGetBit but operates on the bit field on a local
0282 // variable. This is used by the parsing constructor to record if a repeated
0283 // field is mutable.
0284 // Example: "((mutable_bitField1_ & 0x04) == 0x04)"
0285 std::string GenerateGetBitMutableLocal(int bitIndex);
0286 
0287 // Does the same as GenerateSetBit but operates on the bit field on a local
0288 // variable. This is used by the parsing constructor to record if a repeated
0289 // field is mutable.
0290 // Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)"
0291 std::string GenerateSetBitMutableLocal(int bitIndex);
0292 
0293 // Returns whether the JavaType is a reference type.
0294 bool IsReferenceType(JavaType type);
0295 
0296 // Returns the capitalized name for calling relative functions in
0297 // CodedInputStream
0298 absl::string_view GetCapitalizedType(const FieldDescriptor* field,
0299                                      bool immutable, Options options);
0300 
0301 // For encodings with fixed sizes, returns that size in bytes.  Otherwise
0302 // returns -1.
0303 int FixedSize(FieldDescriptor::Type type);
0304 
0305 // Comparators used to sort fields in MessageGenerator
0306 struct FieldOrderingByNumber {
0307   inline bool operator()(const FieldDescriptor* a,
0308                          const FieldDescriptor* b) const {
0309     return a->number() < b->number();
0310   }
0311 };
0312 
0313 struct ExtensionRangeOrdering {
0314   bool operator()(const Descriptor::ExtensionRange* a,
0315                   const Descriptor::ExtensionRange* b) const {
0316     return a->start_number() < b->start_number();
0317   }
0318 };
0319 
0320 // Sort the fields of the given Descriptor by number into a new[]'d array
0321 // and return it. The caller should delete the returned array.
0322 const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor);
0323 
0324 // Does this message class have any packed fields?
0325 inline bool HasPackedFields(const Descriptor* descriptor) {
0326   for (int i = 0; i < descriptor->field_count(); i++) {
0327     if (descriptor->field(i)->is_packed()) {
0328       return true;
0329     }
0330   }
0331   return false;
0332 }
0333 
0334 // Check a message type and its sub-message types recursively to see if any of
0335 // them has a required field. Return true if a required field is found.
0336 bool HasRequiredFields(const Descriptor* descriptor);
0337 
0338 bool IsRealOneof(const FieldDescriptor* descriptor);
0339 
0340 inline bool HasHasbit(const FieldDescriptor* descriptor) {
0341   return internal::cpp::HasHasbit(descriptor);
0342 }
0343 
0344 // Check whether a message has repeated fields.
0345 bool HasRepeatedFields(const Descriptor* descriptor);
0346 
0347 inline bool IsMapEntry(const Descriptor* descriptor) {
0348   return descriptor->options().map_entry();
0349 }
0350 
0351 inline bool IsMapField(const FieldDescriptor* descriptor) {
0352   return descriptor->is_map();
0353 }
0354 
0355 inline bool IsAnyMessage(const Descriptor* descriptor) {
0356   return descriptor->full_name() == "google.protobuf.Any";
0357 }
0358 
0359 inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) {
0360   return descriptor->name() == "google/protobuf/wrappers.proto";
0361 }
0362 
0363 void WriteUInt32ToUtf16CharSequence(uint32_t number,
0364                                     std::vector<uint16_t>* output);
0365 
0366 inline void WriteIntToUtf16CharSequence(int value,
0367                                         std::vector<uint16_t>* output) {
0368   WriteUInt32ToUtf16CharSequence(static_cast<uint32_t>(value), output);
0369 }
0370 
0371 // Escape a UTF-16 character so it can be embedded in a Java string literal.
0372 void EscapeUtf16ToString(uint16_t code, std::string* output);
0373 
0374 // To get the total number of entries need to be built for experimental runtime
0375 // and the first field number that are not in the table part
0376 std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
0377     const FieldDescriptor** fields, int count);
0378 
0379 const FieldDescriptor* MapKeyField(const FieldDescriptor* descriptor);
0380 
0381 const FieldDescriptor* MapValueField(const FieldDescriptor* descriptor);
0382 
0383 }  // namespace java
0384 }  // namespace compiler
0385 }  // namespace protobuf
0386 }  // namespace google
0387 
0388 #include "google/protobuf/port_undef.inc"
0389 #endif  // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__