Back to home page

EIC code displayed by LXR

 
 

    


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

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_CPP_FIELD_H__
0013 #define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
0014 
0015 #include <cstddef>
0016 #include <cstdint>
0017 #include <memory>
0018 #include <string>
0019 #include <vector>
0020 
0021 #include "absl/container/flat_hash_map.h"
0022 #include "absl/log/absl_check.h"
0023 #include "absl/strings/string_view.h"
0024 #include "absl/types/optional.h"
0025 #include "absl/types/span.h"
0026 #include "google/protobuf/compiler/cpp/helpers.h"
0027 #include "google/protobuf/compiler/cpp/options.h"
0028 #include "google/protobuf/descriptor.h"
0029 #include "google/protobuf/io/printer.h"
0030 
0031 namespace google {
0032 namespace protobuf {
0033 namespace compiler {
0034 namespace cpp {
0035 
0036 // Customization points for each field codegen type. See FieldGenerator to
0037 // see how each of these functions is used.
0038 //
0039 // TODO: Make every function except the dtor in this generator
0040 // non-pure-virtual. A generator with no implementation should be able to
0041 // automatically not contribute any code to the message it is part of, as a
0042 // matter of clean composability.
0043 class FieldGeneratorBase {
0044  public:
0045   // `GeneratorFunction` defines a subset of generator functions that may have
0046   // additional optimizations or requirements such as 'uses a local `arena`
0047   // variable instead of calling GetArena()'
0048   enum class GeneratorFunction { kMergeFrom };
0049 
0050   FieldGeneratorBase(const FieldDescriptor* field, const Options& options,
0051                      MessageSCCAnalyzer* scc_analyzer);
0052 
0053   FieldGeneratorBase(const FieldGeneratorBase&) = delete;
0054   FieldGeneratorBase& operator=(const FieldGeneratorBase&) = delete;
0055 
0056   virtual ~FieldGeneratorBase() = 0;
0057 
0058   // Returns true if this field should be placed in the cold 'Split' section.
0059   bool should_split() const { return should_split_; }
0060 
0061   // Returns true if this field is trivial. (int, float, double, enum, bool)
0062   bool is_trivial() const { return is_trivial_; }
0063 
0064   // Returns true if the field value itself is trivial, i.e., the field is
0065   // trivial, or a (raw) pointer value to a singular, non lazy message.
0066   bool has_trivial_value() const { return has_trivial_value_; }
0067 
0068   // Returns true if the provided field has a trivial zero default.
0069   // I.e., the field can be initialized with `memset(&field, 0, sizeof(field))`
0070   bool has_trivial_zero_default() const { return has_trivial_zero_default_; }
0071 
0072   // Returns true if the provided field can be initialized with `= {}`.
0073   bool has_brace_default_assign() const { return has_brace_default_assign_; }
0074 
0075   // Returns true if the field is a singular or repeated message.
0076   // This includes group message types. To explicitly check if a message
0077   // type is a group type, use the `is_group()` function,
0078   bool is_message() const { return is_message_; }
0079 
0080   // Returns true if the field is a group message field (TYPE_GROUP).
0081   bool is_group() const { return is_group_; }
0082 
0083   // Returns true if the field is a weak message
0084   bool is_weak() const { return is_weak_; }
0085 
0086   // Returns true if the field is a lazy message.
0087   bool is_lazy() const { return is_lazy_; }
0088 
0089   // Returns true if the field is a foreign message field.
0090   bool is_foreign() const { return is_foreign_; }
0091 
0092   // Returns true if the field is a string field.
0093   bool is_string() const { return is_string_; }
0094 
0095   // Returns true if the field API uses bytes (void) instead of chars.
0096   bool is_bytes() const { return is_bytes_; }
0097 
0098   // Returns true if this field is part of a oneof field.
0099   bool is_oneof() const { return is_oneof_; }
0100 
0101   // Returns true if the field should be inlined instead of dynamically
0102   // allocated. Applies to string and message value.
0103   bool is_inlined() const { return is_inlined_; }
0104 
0105   // Returns true if this field has an appropriate default constexpr
0106   // constructor. i.e., there is no need for an explicit initializer.
0107   bool has_default_constexpr_constructor() const {
0108     return has_default_constexpr_constructor_;
0109   }
0110 
0111   // Returns true if this generator requires an 'arena' parameter on the
0112   // given generator function.
0113   virtual bool RequiresArena(GeneratorFunction) const { return false; }
0114 
0115   virtual std::vector<io::Printer::Sub> MakeVars() const { return {}; }
0116 
0117   virtual void GeneratePrivateMembers(io::Printer* p) const = 0;
0118 
0119   virtual void GenerateStaticMembers(io::Printer* p) const {}
0120 
0121   virtual void GenerateAccessorDeclarations(io::Printer* p) const = 0;
0122 
0123   virtual void GenerateInlineAccessorDefinitions(io::Printer* p) const = 0;
0124 
0125   virtual void GenerateNonInlineAccessorDefinitions(io::Printer* p) const {}
0126 
0127   virtual void GenerateClearingCode(io::Printer* p) const = 0;
0128 
0129   virtual void GenerateMessageClearingCode(io::Printer* p) const {
0130     GenerateClearingCode(p);
0131   }
0132 
0133   virtual void GenerateMergingCode(io::Printer* p) const = 0;
0134 
0135   virtual void GenerateCopyConstructorCode(io::Printer* p) const;
0136 
0137   virtual void GenerateSwappingCode(io::Printer* p) const = 0;
0138 
0139   virtual void GenerateConstructorCode(io::Printer* p) const = 0;
0140 
0141   virtual void GenerateDestructorCode(io::Printer* p) const {}
0142 
0143   virtual void GenerateArenaDestructorCode(io::Printer* p) const {
0144     ABSL_CHECK(NeedsArenaDestructor() == ArenaDtorNeeds::kNone)
0145         << field_->cpp_type_name();
0146   }
0147 
0148   // Generates constexpr member initialization code, e.g.: `foo_{5}`.
0149   // The default implementation generates the following code:
0150   // - repeated fields and maps: `field_{}`
0151   // - all other fields: `field_{<default value>}`
0152   virtual void GenerateMemberConstexprConstructor(io::Printer* p) const;
0153 
0154   // Generates member initialization code, e.g.: `foo_(5)`.
0155   // The default implementation generates the following code:
0156   // - repeated fields and maps: `field_{visibility, arena}`
0157   // - split repeated fields (RawPtr): `field_{}`
0158   // - all other fields: `field_{<default value>}`
0159   virtual void GenerateMemberConstructor(io::Printer* p) const;
0160 
0161   // Generates member copy initialization code, e.g.: `foo_(5)`.
0162   // The default implementation generates the following code:
0163   // - repeated fields and maps: `field_{visibility, arena, from.field_}`
0164   // - all other fields: `field_{from.field_}`
0165   virtual void GenerateMemberCopyConstructor(io::Printer* p) const;
0166 
0167   // Generates 'placement new' copy construction code used to
0168   // explicitly copy initialize oneof field values.
0169   // The default implementation checks the current field to not be repeated,
0170   // an extension or a map, and generates the following code:
0171   // - `field_ = from.field_`
0172   virtual void GenerateOneofCopyConstruct(io::Printer* p) const;
0173 
0174   virtual void GenerateAggregateInitializer(io::Printer* p) const;
0175 
0176   virtual void GenerateConstexprAggregateInitializer(io::Printer* p) const;
0177 
0178   virtual void GenerateCopyAggregateInitializer(io::Printer* p) const;
0179 
0180   virtual void GenerateSerializeWithCachedSizesToArray(
0181       io::Printer* p) const = 0;
0182 
0183   virtual void GenerateByteSize(io::Printer* p) const = 0;
0184 
0185   virtual void GenerateIsInitialized(io::Printer* p) const {
0186     ABSL_CHECK(!NeedsIsInitialized());
0187   }
0188   virtual bool NeedsIsInitialized() const { return false; }
0189 
0190   virtual bool IsInlined() const { return false; }
0191 
0192   virtual ArenaDtorNeeds NeedsArenaDestructor() const {
0193     return ArenaDtorNeeds::kNone;
0194   }
0195 
0196  protected:
0197   const FieldDescriptor* field_;
0198   const Options& options_;
0199   MessageSCCAnalyzer* scc_;
0200   absl::flat_hash_map<absl::string_view, std::string> variables_;
0201 
0202  private:
0203   bool should_split_ = false;
0204   bool is_trivial_ = false;
0205   bool has_trivial_value_ = false;
0206   bool has_trivial_zero_default_ = false;
0207   bool has_brace_default_assign_ = false;
0208   bool is_message_ = false;
0209   bool is_group_ = false;
0210   bool is_string_ = false;
0211   bool is_bytes_ = false;
0212   bool is_inlined_ = false;
0213   bool is_foreign_ = false;
0214   bool is_lazy_ = false;
0215   bool is_weak_ = false;
0216   bool is_oneof_ = false;
0217   bool has_default_constexpr_constructor_ = false;
0218 };
0219 
0220 inline FieldGeneratorBase::~FieldGeneratorBase() = default;
0221 
0222 class FieldGenerator {
0223  private:
0224   // This function must be defined here so that the inline definitions below
0225   // can see it, which is required because it has deduced return type.
0226   auto PushVarsForCall(io::Printer* p) const {
0227     // NOTE: we use a struct here because:
0228     // * We want to ensure that order of evaluation below is well-defined,
0229     //   which {...} guarantees but (...) does not.
0230     // * We do not require C++17 as of writing and therefore cannot use
0231     //   std::tuple with CTAD.
0232     // * std::make_tuple uses (...), not {...}.
0233     struct Vars {
0234       decltype(p->WithVars(field_vars_)) cleanup1;
0235       decltype(p->WithVars(tracker_vars_)) cleanup2;
0236       decltype(p->WithVars(per_generator_vars_)) cleanup3;
0237     };
0238 
0239     return Vars{p->WithVars(field_vars_), p->WithVars(tracker_vars_),
0240                 p->WithVars(per_generator_vars_)};
0241   }
0242 
0243  public:
0244   using GeneratorFunction = FieldGeneratorBase::GeneratorFunction;
0245 
0246   FieldGenerator(const FieldGenerator&) = delete;
0247   FieldGenerator& operator=(const FieldGenerator&) = delete;
0248   FieldGenerator(FieldGenerator&&) = default;
0249   FieldGenerator& operator=(FieldGenerator&&) = default;
0250 
0251   // Properties: see FieldGeneratorBase for documentation
0252   bool should_split() const { return impl_->should_split(); }
0253   bool is_trivial() const { return impl_->is_trivial(); }
0254   bool has_trivial_value() const { return impl_->has_trivial_value(); }
0255   bool has_trivial_zero_default() const {
0256     return impl_->has_trivial_zero_default();
0257   }
0258   bool has_brace_default_assign() const {
0259     return impl_->has_brace_default_assign();
0260   }
0261   bool is_message() const { return impl_->is_message(); }
0262   bool is_group() const { return impl_->is_group(); }
0263   bool is_weak() const { return impl_->is_weak(); }
0264   bool is_lazy() const { return impl_->is_lazy(); }
0265   bool is_foreign() const { return impl_->is_foreign(); }
0266   bool is_string() const { return impl_->is_string(); }
0267   bool is_bytes() const { return impl_->is_bytes(); }
0268   bool is_oneof() const { return impl_->is_oneof(); }
0269   bool is_inlined() const { return impl_->is_inlined(); }
0270   bool has_default_constexpr_constructor() const {
0271     return impl_->has_default_constexpr_constructor();
0272   }
0273 
0274   // Requirements: see FieldGeneratorBase for documentation
0275   bool RequiresArena(GeneratorFunction function) const {
0276     return impl_->RequiresArena(function);
0277   }
0278 
0279   // Prints private members needed to represent this field.
0280   //
0281   // These are placed inside the class definition.
0282   void GeneratePrivateMembers(io::Printer* p) const {
0283     auto vars = PushVarsForCall(p);
0284     impl_->GeneratePrivateMembers(p);
0285   }
0286 
0287   // Prints static members needed to represent this field.
0288   //
0289   // These are placed inside the class definition.
0290   void GenerateStaticMembers(io::Printer* p) const {
0291     auto vars = PushVarsForCall(p);
0292     impl_->GenerateStaticMembers(p);
0293   }
0294 
0295   void GenerateMemberConstructor(io::Printer* p) const {
0296     auto vars = PushVarsForCall(p);
0297     impl_->GenerateMemberConstructor(p);
0298   }
0299 
0300   void GenerateMemberCopyConstructor(io::Printer* p) const {
0301     auto vars = PushVarsForCall(p);
0302     impl_->GenerateMemberCopyConstructor(p);
0303   }
0304 
0305   void GenerateOneofCopyConstruct(io::Printer* p) const {
0306     auto vars = PushVarsForCall(p);
0307     impl_->GenerateOneofCopyConstruct(p);
0308   }
0309 
0310   void GenerateMemberConstexprConstructor(io::Printer* p) const {
0311     auto vars = PushVarsForCall(p);
0312     impl_->GenerateMemberConstexprConstructor(p);
0313   }
0314 
0315   // Generates declarations for all of the accessor functions related to this
0316   // field.
0317   //
0318   // These are placed inside the class definition.
0319   void GenerateAccessorDeclarations(io::Printer* p) const {
0320     auto vars = PushVarsForCall(p);
0321     impl_->GenerateAccessorDeclarations(p);
0322   }
0323 
0324   // Generates inline definitions of accessor functions for this field.
0325   //
0326   // These are placed in namespace scope in the header after all class
0327   // definitions.
0328   void GenerateInlineAccessorDefinitions(io::Printer* p) const {
0329     auto vars = PushVarsForCall(p);
0330     impl_->GenerateInlineAccessorDefinitions(p);
0331   }
0332 
0333   // Generates definitions of accessors that aren't inlined.
0334   //
0335   // These are placed in namespace scope in the .cc file.
0336   void GenerateNonInlineAccessorDefinitions(io::Printer* p) const {
0337     auto vars = PushVarsForCall(p);
0338     impl_->GenerateNonInlineAccessorDefinitions(p);
0339   }
0340 
0341   // Generates statements which clear the field.
0342   //
0343   // This is used to define the clear_$name$() method.
0344   void GenerateClearingCode(io::Printer* p) const {
0345     auto vars = PushVarsForCall(p);
0346     impl_->GenerateClearingCode(p);
0347   }
0348 
0349   // Generates statements which clear the field as part of the Clear() method
0350   // for the whole message.
0351   //
0352   // For message types which have field presence bits,
0353   // MessageGenerator::GenerateClear will have already checked the presence
0354   // bits.
0355   void GenerateMessageClearingCode(io::Printer* p) const {
0356     auto vars = PushVarsForCall(p);
0357     impl_->GenerateMessageClearingCode(p);
0358   }
0359 
0360   // Generates statements which merge the contents of the field from the current
0361   // message to the target message, which is stored in the generated code
0362   // variable `from`.
0363   //
0364   // This is used to fill in the MergeFrom method for the whole message.
0365   //
0366   // Details of this usage can be found in message.cc under the
0367   // GenerateMergeFrom method.
0368   void GenerateMergingCode(io::Printer* p) const {
0369     auto vars = PushVarsForCall(p);
0370     impl_->GenerateMergingCode(p);
0371   }
0372 
0373   // Generates a copy constructor
0374   //
0375   // TODO: Document this properly.
0376   void GenerateCopyConstructorCode(io::Printer* p) const {
0377     auto vars = PushVarsForCall(p);
0378     impl_->GenerateCopyConstructorCode(p);
0379   }
0380 
0381   // Generates statements which swap this field and the corresponding field of
0382   // another message, which is stored in the generated code variable `other`.
0383   //
0384   // This is used to define the Swap method. Details of usage can be found in
0385   // message.cc under the GenerateSwap method.
0386   void GenerateSwappingCode(io::Printer* p) const {
0387     auto vars = PushVarsForCall(p);
0388     impl_->GenerateSwappingCode(p);
0389   }
0390 
0391   // Generates initialization code for private members declared by
0392   // GeneratePrivateMembers().
0393   //
0394   // These go into the message class's SharedCtor() method, invoked by each of
0395   // the generated constructors.
0396   void GenerateConstructorCode(io::Printer* p) const {
0397     auto vars = PushVarsForCall(p);
0398     impl_->GenerateConstructorCode(p);
0399   }
0400 
0401   // Generates any code that needs to go in the class's SharedDtor() method,
0402   // invoked by the destructor.
0403   void GenerateDestructorCode(io::Printer* p) const {
0404     auto vars = PushVarsForCall(p);
0405     impl_->GenerateDestructorCode(p);
0406   }
0407 
0408   // Generates a manual destructor invocation for use when the message is on an
0409   // arena.
0410   //
0411   // The code that this method generates will be executed inside a
0412   // shared-for-the-whole-message-class method registered with OwnDestructor().
0413   void GenerateArenaDestructorCode(io::Printer* p) const {
0414     auto vars = PushVarsForCall(p);
0415     impl_->GenerateArenaDestructorCode(p);
0416   }
0417 
0418   // Generates initialization code for private members declared by
0419   // GeneratePrivateMembers().
0420   //
0421   // These go into the SharedCtor's aggregate initialization of the _impl_
0422   // struct and must follow the syntax `decltype($field$){$default$}`.
0423   // Does not include `:` or `,` separators. Default values should be specified
0424   // here when possible.
0425   //
0426   // NOTE: We use `decltype($field$)` for both explicit construction and the
0427   // fact that it's self-documenting. Pre-C++17, copy elision isn't guaranteed
0428   // in aggregate initialization so a valid copy/move constructor must exist
0429   // (even though it's not used). Because of this, we need to comment out the
0430   // decltype and fallback to implicit construction.
0431   void GenerateAggregateInitializer(io::Printer* p) const {
0432     auto vars = PushVarsForCall(p);
0433     impl_->GenerateAggregateInitializer(p);
0434   }
0435 
0436   // Generates constinit initialization code for private members declared by
0437   // GeneratePrivateMembers().
0438   //
0439   // These go into the constexpr constructor's aggregate initialization of the
0440   // _impl_ struct and must follow the syntax `/*decltype($field$)*/{}` (see
0441   // above). Does not include `:` or `,` separators.
0442   void GenerateConstexprAggregateInitializer(io::Printer* p) const {
0443     auto vars = PushVarsForCall(p);
0444     impl_->GenerateConstexprAggregateInitializer(p);
0445   }
0446 
0447   // Generates copy initialization code for private members declared by
0448   // GeneratePrivateMembers().
0449   //
0450   // These go into the copy constructor's aggregate initialization of the _impl_
0451   // struct and must follow the syntax `decltype($field$){from.$field$}` (see
0452   // above). Does not include `:` or `,` separators.
0453   void GenerateCopyAggregateInitializer(io::Printer* p) const {
0454     auto vars = PushVarsForCall(p);
0455     impl_->GenerateCopyAggregateInitializer(p);
0456   }
0457 
0458   // Generates statements to serialize this field directly to the array
0459   // `target`, which are placed within the message's
0460   // SerializeWithCachedSizesToArray() method.
0461   //
0462   // This must also advance `target` past the written bytes.
0463   void GenerateSerializeWithCachedSizesToArray(io::Printer* p) const {
0464     auto vars = PushVarsForCall(p);
0465     impl_->GenerateSerializeWithCachedSizesToArray(p);
0466   }
0467 
0468   // Generates statements to compute the serialized size of this field, which
0469   // are placed in the message's ByteSize() method.
0470   void GenerateByteSize(io::Printer* p) const {
0471     auto vars = PushVarsForCall(p);
0472     impl_->GenerateByteSize(p);
0473   }
0474 
0475   // Generates lines to call IsInitialized() for eligible message fields. Non
0476   // message fields won't need to override this function.
0477   void GenerateIsInitialized(io::Printer* p) const {
0478     auto vars = PushVarsForCall(p);
0479     impl_->GenerateIsInitialized(p);
0480   }
0481 
0482   bool NeedsIsInitialized() const { return impl_->NeedsIsInitialized(); }
0483 
0484   // TODO: Document this properly.
0485   bool IsInlined() const { return impl_->IsInlined(); }
0486 
0487   // TODO: Document this properly.
0488   ArenaDtorNeeds NeedsArenaDestructor() const {
0489     return impl_->NeedsArenaDestructor();
0490   }
0491 
0492  private:
0493   friend class FieldGeneratorTable;
0494   FieldGenerator(const FieldDescriptor* field, const Options& options,
0495                  MessageSCCAnalyzer* scc_analyzer,
0496                  absl::optional<uint32_t> hasbit_index,
0497                  absl::optional<uint32_t> inlined_string_index);
0498 
0499   std::unique_ptr<FieldGeneratorBase> impl_;
0500   std::vector<io::Printer::Sub> field_vars_;
0501   std::vector<io::Printer::Sub> tracker_vars_;
0502   std::vector<io::Printer::Sub> per_generator_vars_;
0503 };
0504 
0505 // Convenience class which constructs FieldGeneratorBases for a Descriptor.
0506 class FieldGeneratorTable {
0507  public:
0508   explicit FieldGeneratorTable(const Descriptor* descriptor)
0509       : descriptor_(descriptor) {}
0510 
0511   FieldGeneratorTable(const FieldGeneratorTable&) = delete;
0512   FieldGeneratorTable& operator=(const FieldGeneratorTable&) = delete;
0513 
0514   void Build(const Options& options, MessageSCCAnalyzer* scc_analyzer,
0515              absl::Span<const int32_t> has_bit_indices,
0516              absl::Span<const int32_t> inlined_string_indices);
0517 
0518   const FieldGenerator& get(const FieldDescriptor* field) const {
0519     ABSL_CHECK_EQ(field->containing_type(), descriptor_);
0520     ABSL_DCHECK_GE(field->index(), 0);
0521     return fields_[static_cast<size_t>(field->index())];
0522   }
0523 
0524  private:
0525   const Descriptor* descriptor_;
0526   std::vector<FieldGenerator> fields_;
0527 };
0528 
0529 // Returns variables common to all fields.
0530 //
0531 // TODO: Make this function .cc-private.
0532 std::vector<io::Printer::Sub> FieldVars(const FieldDescriptor* field,
0533                                         const Options& opts);
0534 }  // namespace cpp
0535 }  // namespace compiler
0536 }  // namespace protobuf
0537 }  // namespace google
0538 
0539 #endif  // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__