1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // http://code.google.com/p/protobuf/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Author: kenton@google.com (Kenton Varda)
32 // Based on original Protocol Buffers design by
33 // Sanjay Ghemawat, Jeff Dean, and others.
36 #include <google/protobuf/stubs/hash.h>
40 #include <google/protobuf/compiler/cpp/cpp_message.h>
41 #include <google/protobuf/compiler/cpp/cpp_field.h>
42 #include <google/protobuf/compiler/cpp/cpp_enum.h>
43 #include <google/protobuf/compiler/cpp/cpp_extension.h>
44 #include <google/protobuf/compiler/cpp/cpp_helpers.h>
45 #include <google/protobuf/stubs/strutil.h>
46 #include <google/protobuf/io/printer.h>
47 #include <google/protobuf/io/coded_stream.h>
48 #include <google/protobuf/wire_format.h>
49 #include <google/protobuf/descriptor.pb.h>
57 using internal::WireFormat;
58 using internal::WireFormatLite;
62 void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) {
63 // Print the field's proto-syntax definition as a comment. We don't want to
64 // print group bodies so we cut off after the first line.
65 string def = field->DebugString();
66 printer->Print("// $def$\n",
67 "def", def.substr(0, def.find_first_of('\n')));
70 struct FieldOrderingByNumber {
71 inline bool operator()(const FieldDescriptor* a,
72 const FieldDescriptor* b) const {
73 return a->number() < b->number();
77 const char* kWireTypeNames[] = {
86 // Sort the fields of the given Descriptor by number into a new[]'d array
88 const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
89 const FieldDescriptor** fields =
90 new const FieldDescriptor*[descriptor->field_count()];
91 for (int i = 0; i < descriptor->field_count(); i++) {
92 fields[i] = descriptor->field(i);
94 sort(fields, fields + descriptor->field_count(),
95 FieldOrderingByNumber());
99 // Functor for sorting extension ranges by their "start" field number.
100 struct ExtensionRangeSorter {
101 bool operator()(const Descriptor::ExtensionRange* left,
102 const Descriptor::ExtensionRange* right) const {
103 return left->start < right->start;
107 // Returns true if the "required" restriction check should be ignored for the
109 inline static bool ShouldIgnoreRequiredFieldCheck(
110 const FieldDescriptor* field) {
114 // Returns true if the message type has any required fields. If it doesn't,
115 // we can optimize out calls to its IsInitialized() method.
117 // already_seen is used to avoid checking the same type multiple times
118 // (and also to protect against recursion).
119 static bool HasRequiredFields(
120 const Descriptor* type,
121 hash_set<const Descriptor*>* already_seen) {
122 if (already_seen->count(type) > 0) {
123 // Since the first occurrence of a required field causes the whole
124 // function to return true, we can assume that if the type is already
125 // in the cache it didn't have any required fields.
128 already_seen->insert(type);
130 // If the type has extensions, an extension with message type could contain
131 // required fields, so we have to be conservative and assume such an
133 if (type->extension_range_count() > 0) return true;
135 for (int i = 0; i < type->field_count(); i++) {
136 const FieldDescriptor* field = type->field(i);
137 if (field->is_required()) {
140 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
141 !ShouldIgnoreRequiredFieldCheck(field)) {
142 if (HasRequiredFields(field->message_type(), already_seen)) {
151 static bool HasRequiredFields(const Descriptor* type) {
152 hash_set<const Descriptor*> already_seen;
153 return HasRequiredFields(type, &already_seen);
156 // This returns an estimate of the compiler's alignment for the field. This
157 // can't guarantee to be correct because the generated code could be compiled on
158 // different systems with different alignment rules. The estimates below assume
160 int EstimateAlignmentSize(const FieldDescriptor* field) {
161 if (field == NULL) return 0;
162 if (field->is_repeated()) return 8;
163 switch (field->cpp_type()) {
164 case FieldDescriptor::CPPTYPE_BOOL:
167 case FieldDescriptor::CPPTYPE_INT32:
168 case FieldDescriptor::CPPTYPE_UINT32:
169 case FieldDescriptor::CPPTYPE_ENUM:
170 case FieldDescriptor::CPPTYPE_FLOAT:
173 case FieldDescriptor::CPPTYPE_INT64:
174 case FieldDescriptor::CPPTYPE_UINT64:
175 case FieldDescriptor::CPPTYPE_DOUBLE:
176 case FieldDescriptor::CPPTYPE_STRING:
177 case FieldDescriptor::CPPTYPE_MESSAGE:
180 GOOGLE_LOG(FATAL) << "Can't get here.";
181 return -1; // Make compiler happy.
184 // FieldGroup is just a helper for OptimizePadding below. It holds a vector of
185 // fields that are grouped together because they have compatible alignment, and
186 // a preferred location in the final field ordering.
190 : preferred_location_(0) {}
192 // A group with a single field.
193 FieldGroup(float preferred_location, const FieldDescriptor* field)
194 : preferred_location_(preferred_location),
197 // Append the fields in 'other' to this group.
198 void Append(const FieldGroup& other) {
199 if (other.fields_.empty()) {
202 // Preferred location is the average among all the fields, so we weight by
203 // the number of fields on each FieldGroup object.
204 preferred_location_ =
205 (preferred_location_ * fields_.size() +
206 (other.preferred_location_ * other.fields_.size())) /
207 (fields_.size() + other.fields_.size());
208 fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
211 void SetPreferredLocation(float location) { preferred_location_ = location; }
212 const vector<const FieldDescriptor*>& fields() const { return fields_; }
214 // FieldGroup objects sort by their preferred location.
215 bool operator<(const FieldGroup& other) const {
216 return preferred_location_ < other.preferred_location_;
220 // "preferred_location_" is an estimate of where this group should go in the
221 // final list of fields. We compute this by taking the average index of each
222 // field in this group in the original ordering of fields. This is very
223 // approximate, but should put this group close to where its member fields
225 float preferred_location_;
226 vector<const FieldDescriptor*> fields_;
227 // We rely on the default copy constructor and operator= so this type can be
231 // Reorder 'fields' so that if the fields are output into a c++ class in the new
232 // order, the alignment padding is minimized. We try to do this while keeping
233 // each field as close as possible to its original position so that we don't
234 // reduce cache locality much for function that access each field in order.
235 void OptimizePadding(vector<const FieldDescriptor*>* fields) {
236 // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
237 vector<FieldGroup> aligned_to_1, aligned_to_4, aligned_to_8;
238 for (int i = 0; i < fields->size(); ++i) {
239 switch (EstimateAlignmentSize((*fields)[i])) {
240 case 1: aligned_to_1.push_back(FieldGroup(i, (*fields)[i])); break;
241 case 4: aligned_to_4.push_back(FieldGroup(i, (*fields)[i])); break;
242 case 8: aligned_to_8.push_back(FieldGroup(i, (*fields)[i])); break;
244 GOOGLE_LOG(FATAL) << "Unknown alignment size.";
248 // Now group fields aligned to 1 byte into sets of 4, and treat those like a
249 // single field aligned to 4 bytes.
250 for (int i = 0; i < aligned_to_1.size(); i += 4) {
251 FieldGroup field_group;
252 for (int j = i; j < aligned_to_1.size() && j < i + 4; ++j) {
253 field_group.Append(aligned_to_1[j]);
255 aligned_to_4.push_back(field_group);
257 // Sort by preferred location to keep fields as close to their original
258 // location as possible.
259 sort(aligned_to_4.begin(), aligned_to_4.end());
261 // Now group fields aligned to 4 bytes (or the 4-field groups created above)
262 // into pairs, and treat those like a single field aligned to 8 bytes.
263 for (int i = 0; i < aligned_to_4.size(); i += 2) {
264 FieldGroup field_group;
265 for (int j = i; j < aligned_to_4.size() && j < i + 2; ++j) {
266 field_group.Append(aligned_to_4[j]);
268 if (i == aligned_to_4.size() - 1) {
269 // Move incomplete 4-byte block to the end.
270 field_group.SetPreferredLocation(fields->size() + 1);
272 aligned_to_8.push_back(field_group);
274 // Sort by preferred location to keep fields as close to their original
275 // location as possible.
276 sort(aligned_to_8.begin(), aligned_to_8.end());
278 // Now pull out all the FieldDescriptors in order.
280 for (int i = 0; i < aligned_to_8.size(); ++i) {
281 fields->insert(fields->end(),
282 aligned_to_8[i].fields().begin(),
283 aligned_to_8[i].fields().end());
289 // ===================================================================
291 MessageGenerator::MessageGenerator(const Descriptor* descriptor,
292 const Options& options)
293 : descriptor_(descriptor),
294 classname_(ClassName(descriptor, false)),
296 field_generators_(descriptor, options),
297 nested_generators_(new scoped_ptr<MessageGenerator>[
298 descriptor->nested_type_count()]),
299 enum_generators_(new scoped_ptr<EnumGenerator>[
300 descriptor->enum_type_count()]),
301 extension_generators_(new scoped_ptr<ExtensionGenerator>[
302 descriptor->extension_count()]) {
304 for (int i = 0; i < descriptor->nested_type_count(); i++) {
305 nested_generators_[i].reset(
306 new MessageGenerator(descriptor->nested_type(i), options));
309 for (int i = 0; i < descriptor->enum_type_count(); i++) {
310 enum_generators_[i].reset(
311 new EnumGenerator(descriptor->enum_type(i), options));
314 for (int i = 0; i < descriptor->extension_count(); i++) {
315 extension_generators_[i].reset(
316 new ExtensionGenerator(descriptor->extension(i), options));
320 MessageGenerator::~MessageGenerator() {}
322 void MessageGenerator::
323 GenerateForwardDeclaration(io::Printer* printer) {
324 printer->Print("class $classname$;\n",
325 "classname", classname_);
327 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
328 nested_generators_[i]->GenerateForwardDeclaration(printer);
332 void MessageGenerator::
333 GenerateEnumDefinitions(io::Printer* printer) {
334 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
335 nested_generators_[i]->GenerateEnumDefinitions(printer);
338 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
339 enum_generators_[i]->GenerateDefinition(printer);
343 void MessageGenerator::
344 GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
345 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
346 nested_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
348 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
349 enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
353 void MessageGenerator::
354 GenerateFieldAccessorDeclarations(io::Printer* printer) {
355 for (int i = 0; i < descriptor_->field_count(); i++) {
356 const FieldDescriptor* field = descriptor_->field(i);
358 PrintFieldComment(printer, field);
360 map<string, string> vars;
361 SetCommonFieldVariables(field, &vars, options_);
362 vars["constant_name"] = FieldConstantName(field);
364 if (field->is_repeated()) {
365 printer->Print(vars, "inline int $name$_size() const$deprecation$;\n");
367 printer->Print(vars, "inline bool has_$name$() const$deprecation$;\n");
370 printer->Print(vars, "inline void clear_$name$()$deprecation$;\n");
371 printer->Print(vars, "static const int $constant_name$ = $number$;\n");
373 // Generate type-specific accessor declarations.
374 field_generators_.get(field).GenerateAccessorDeclarations(printer);
376 printer->Print("\n");
379 if (descriptor_->extension_range_count() > 0) {
380 // Generate accessors for extensions. We just call a macro located in
381 // extension_set.h since the accessors about 80 lines of static code.
383 "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
384 "classname", classname_);
388 void MessageGenerator::
389 GenerateFieldAccessorDefinitions(io::Printer* printer) {
390 printer->Print("// $classname$\n\n", "classname", classname_);
392 for (int i = 0; i < descriptor_->field_count(); i++) {
393 const FieldDescriptor* field = descriptor_->field(i);
395 PrintFieldComment(printer, field);
397 map<string, string> vars;
398 SetCommonFieldVariables(field, &vars, options_);
400 // Generate has_$name$() or $name$_size().
401 if (field->is_repeated()) {
403 "inline int $classname$::$name$_size() const {\n"
404 " return $name$_.size();\n"
408 char buffer[kFastToBufferSize];
409 vars["has_array_index"] = SimpleItoa(field->index() / 32);
410 vars["has_mask"] = FastHex32ToBuffer(1u << (field->index() % 32), buffer);
412 "inline bool $classname$::has_$name$() const {\n"
413 " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
415 "inline void $classname$::set_has_$name$() {\n"
416 " _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
418 "inline void $classname$::clear_has_$name$() {\n"
419 " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
424 // Generate clear_$name$()
426 "inline void $classname$::clear_$name$() {\n");
429 field_generators_.get(field).GenerateClearingCode(printer);
432 if (!field->is_repeated()) {
434 " clear_has_$name$();\n");
437 printer->Print("}\n");
439 // Generate type-specific accessors.
440 field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
442 printer->Print("\n");
446 void MessageGenerator::
447 GenerateClassDefinition(io::Printer* printer) {
448 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
449 nested_generators_[i]->GenerateClassDefinition(printer);
450 printer->Print("\n");
451 printer->Print(kThinSeparator);
452 printer->Print("\n");
455 map<string, string> vars;
456 vars["classname"] = classname_;
457 vars["field_count"] = SimpleItoa(descriptor_->field_count());
458 if (options_.dllexport_decl.empty()) {
459 vars["dllexport"] = "";
461 vars["dllexport"] = options_.dllexport_decl + " ";
463 vars["superclass"] = SuperClassName(descriptor_);
466 "class $dllexport$$classname$ : public $superclass$ {\n"
472 "virtual ~$classname$();\n"
474 "$classname$(const $classname$& from);\n"
476 "inline $classname$& operator=(const $classname$& from) {\n"
482 if (HasUnknownFields(descriptor_->file())) {
484 "inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {\n"
485 " return _unknown_fields_;\n"
488 "inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {\n"
489 " return &_unknown_fields_;\n"
494 // Only generate this member if it's not disabled.
495 if (HasDescriptorMethods(descriptor_->file()) &&
496 !descriptor_->options().no_standard_descriptor_accessor()) {
498 "static const ::google::protobuf::Descriptor* descriptor();\n");
502 "static const $classname$& default_instance();\n"
505 if (!StaticInitializersForced(descriptor_->file())) {
507 "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
508 "// Returns the internal default instance pointer. This function can\n"
509 "// return NULL thus should not be used by the user. This is intended\n"
510 "// for Protobuf internal code. Please use default_instance() declared\n"
511 "// above instead.\n"
512 "static inline const $classname$* internal_default_instance() {\n"
513 " return default_instance_;\n"
521 "void Swap($classname$* other);\n"
523 "// implements Message ----------------------------------------------\n"
525 "$classname$* New() const;\n");
527 if (HasGeneratedMethods(descriptor_->file())) {
528 if (HasDescriptorMethods(descriptor_->file())) {
530 "void CopyFrom(const ::google::protobuf::Message& from);\n"
531 "void MergeFrom(const ::google::protobuf::Message& from);\n");
534 "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);\n");
538 "void CopyFrom(const $classname$& from);\n"
539 "void MergeFrom(const $classname$& from);\n"
541 "bool IsInitialized() const;\n"
543 "int ByteSize() const;\n"
544 "bool MergePartialFromCodedStream(\n"
545 " ::google::protobuf::io::CodedInputStream* input);\n"
546 "void SerializeWithCachedSizes(\n"
547 " ::google::protobuf::io::CodedOutputStream* output) const;\n");
548 if (HasFastArraySerialization(descriptor_->file())) {
550 "::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;\n");
555 "int GetCachedSize() const { return _cached_size_; }\n"
557 "void SharedCtor();\n"
558 "void SharedDtor();\n"
559 "void SetCachedSize(int size) const;\n"
563 if (HasDescriptorMethods(descriptor_->file())) {
565 "::google::protobuf::Metadata GetMetadata() const;\n"
569 "::std::string GetTypeName() const;\n"
574 "// nested types ----------------------------------------------------\n"
577 // Import all nested message classes into this class's scope with typedefs.
578 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
579 const Descriptor* nested_type = descriptor_->nested_type(i);
580 printer->Print("typedef $nested_full_name$ $nested_name$;\n",
581 "nested_name", nested_type->name(),
582 "nested_full_name", ClassName(nested_type, false));
585 if (descriptor_->nested_type_count() > 0) {
586 printer->Print("\n");
589 // Import all nested enums and their values into this class's scope with
590 // typedefs and constants.
591 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
592 enum_generators_[i]->GenerateSymbolImports(printer);
593 printer->Print("\n");
597 "// accessors -------------------------------------------------------\n"
600 // Generate accessor methods for all fields.
601 GenerateFieldAccessorDeclarations(printer);
603 // Declare extension identifiers.
604 for (int i = 0; i < descriptor_->extension_count(); i++) {
605 extension_generators_[i]->GenerateDeclaration(printer);
610 "// @@protoc_insertion_point(class_scope:$full_name$)\n",
611 "full_name", descriptor_->full_name());
613 // Generate private members.
615 printer->Print(" private:\n");
619 for (int i = 0; i < descriptor_->field_count(); i++) {
620 if (!descriptor_->field(i)->is_repeated()) {
622 "inline void set_has_$name$();\n",
623 "name", FieldName(descriptor_->field(i)));
625 "inline void clear_has_$name$();\n",
626 "name", FieldName(descriptor_->field(i)));
629 printer->Print("\n");
631 // To minimize padding, data members are divided into three sections:
632 // (1) members assumed to align to 8 bytes
633 // (2) members corresponding to message fields, re-ordered to optimize
635 // (3) members assumed to align to 4 bytes.
637 // Members assumed to align to 8 bytes:
639 if (descriptor_->extension_range_count() > 0) {
641 "::google::protobuf::internal::ExtensionSet _extensions_;\n"
645 if (HasUnknownFields(descriptor_->file())) {
647 "::google::protobuf::UnknownFieldSet _unknown_fields_;\n"
653 vector<const FieldDescriptor*> fields;
654 for (int i = 0; i < descriptor_->field_count(); i++) {
655 fields.push_back(descriptor_->field(i));
657 OptimizePadding(&fields);
658 for (int i = 0; i < fields.size(); ++i) {
659 field_generators_.get(fields[i]).GeneratePrivateMembers(printer);
662 // Members assumed to align to 4 bytes:
664 // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
667 "mutable int _cached_size_;\n");
669 // Generate _has_bits_.
670 if (descriptor_->field_count() > 0) {
672 "::google::protobuf::uint32 _has_bits_[($field_count$ + 31) / 32];\n"
675 // Zero-size arrays aren't technically allowed, and MSVC in particular
676 // doesn't like them. We still need to declare these arrays to make
677 // other code compile. Since this is an uncommon case, we'll just declare
678 // them with size 1 and waste some space. Oh well.
680 "::google::protobuf::uint32 _has_bits_[1];\n"
684 // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
685 // friends so that they can access private static variables like
686 // default_instance_ and reflection_.
687 PrintHandlingOptionalStaticInitializers(
688 descriptor_->file(), printer,
689 // With static initializers.
690 "friend void $dllexport_decl$ $adddescriptorsname$();\n",
692 "friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
694 "dllexport_decl", options_.dllexport_decl,
695 "adddescriptorsname",
696 GlobalAddDescriptorsName(descriptor_->file()->name()));
699 "friend void $assigndescriptorsname$();\n"
700 "friend void $shutdownfilename$();\n"
702 "assigndescriptorsname",
703 GlobalAssignDescriptorsName(descriptor_->file()->name()),
704 "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
707 "void InitAsDefaultInstance();\n"
708 "static $classname$* default_instance_;\n",
709 "classname", classname_);
712 printer->Print(vars, "};");
715 void MessageGenerator::
716 GenerateInlineMethods(io::Printer* printer) {
717 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
718 nested_generators_[i]->GenerateInlineMethods(printer);
719 printer->Print(kThinSeparator);
720 printer->Print("\n");
723 GenerateFieldAccessorDefinitions(printer);
726 void MessageGenerator::
727 GenerateDescriptorDeclarations(io::Printer* printer) {
729 "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
730 "const ::google::protobuf::internal::GeneratedMessageReflection*\n"
731 " $name$_reflection_ = NULL;\n",
734 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
735 nested_generators_[i]->GenerateDescriptorDeclarations(printer);
738 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
740 "const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
741 "name", ClassName(descriptor_->enum_type(i), false));
745 void MessageGenerator::
746 GenerateDescriptorInitializer(io::Printer* printer, int index) {
747 // TODO(kenton): Passing the index to this method is redundant; just use
748 // descriptor_->index() instead.
749 map<string, string> vars;
750 vars["classname"] = classname_;
751 vars["index"] = SimpleItoa(index);
753 // Obtain the descriptor from the parent's descriptor.
754 if (descriptor_->containing_type() == NULL) {
756 "$classname$_descriptor_ = file->message_type($index$);\n");
758 vars["parent"] = ClassName(descriptor_->containing_type(), false);
760 "$classname$_descriptor_ = "
761 "$parent$_descriptor_->nested_type($index$);\n");
764 // Generate the offsets.
765 GenerateOffsets(printer);
767 // Construct the reflection object.
769 "$classname$_reflection_ =\n"
770 " new ::google::protobuf::internal::GeneratedMessageReflection(\n"
771 " $classname$_descriptor_,\n"
772 " $classname$::default_instance_,\n"
773 " $classname$_offsets_,\n"
774 " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n"
775 " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
776 "$classname$, _unknown_fields_),\n");
777 if (descriptor_->extension_range_count() > 0) {
779 " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
780 "$classname$, _extensions_),\n");
787 " ::google::protobuf::DescriptorPool::generated_pool(),\n");
789 " ::google::protobuf::MessageFactory::generated_factory(),\n");
791 " sizeof($classname$));\n");
793 // Handle nested types.
794 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
795 nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
798 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
799 enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
803 void MessageGenerator::
804 GenerateTypeRegistrations(io::Printer* printer) {
805 // Register this message type with the message factory.
807 "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
808 " $classname$_descriptor_, &$classname$::default_instance());\n",
809 "classname", classname_);
811 // Handle nested types.
812 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
813 nested_generators_[i]->GenerateTypeRegistrations(printer);
817 void MessageGenerator::
818 GenerateDefaultInstanceAllocator(io::Printer* printer) {
819 // Construct the default instances of all fields, as they will be used
820 // when creating the default instance of the entire message.
821 for (int i = 0; i < descriptor_->field_count(); i++) {
822 field_generators_.get(descriptor_->field(i))
823 .GenerateDefaultInstanceAllocator(printer);
826 // Construct the default instance. We can't call InitAsDefaultInstance() yet
827 // because we need to make sure all default instances that this one might
828 // depend on are constructed first.
830 "$classname$::default_instance_ = new $classname$();\n",
831 "classname", classname_);
833 // Handle nested types.
834 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
835 nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
840 void MessageGenerator::
841 GenerateDefaultInstanceInitializer(io::Printer* printer) {
843 "$classname$::default_instance_->InitAsDefaultInstance();\n",
844 "classname", classname_);
846 // Register extensions.
847 for (int i = 0; i < descriptor_->extension_count(); i++) {
848 extension_generators_[i]->GenerateRegistration(printer);
851 // Handle nested types.
852 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
853 nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
857 void MessageGenerator::
858 GenerateShutdownCode(io::Printer* printer) {
860 "delete $classname$::default_instance_;\n",
861 "classname", classname_);
863 if (HasDescriptorMethods(descriptor_->file())) {
865 "delete $classname$_reflection_;\n",
866 "classname", classname_);
869 // Handle default instances of fields.
870 for (int i = 0; i < descriptor_->field_count(); i++) {
871 field_generators_.get(descriptor_->field(i))
872 .GenerateShutdownCode(printer);
875 // Handle nested types.
876 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
877 nested_generators_[i]->GenerateShutdownCode(printer);
881 void MessageGenerator::
882 GenerateClassMethods(io::Printer* printer) {
883 for (int i = 0; i < descriptor_->enum_type_count(); i++) {
884 enum_generators_[i]->GenerateMethods(printer);
887 for (int i = 0; i < descriptor_->nested_type_count(); i++) {
888 nested_generators_[i]->GenerateClassMethods(printer);
889 printer->Print("\n");
890 printer->Print(kThinSeparator);
891 printer->Print("\n");
894 // Generate non-inline field definitions.
895 for (int i = 0; i < descriptor_->field_count(); i++) {
896 field_generators_.get(descriptor_->field(i))
897 .GenerateNonInlineAccessorDefinitions(printer);
900 // Generate field number constants.
901 printer->Print("#ifndef _MSC_VER\n");
902 for (int i = 0; i < descriptor_->field_count(); i++) {
903 const FieldDescriptor *field = descriptor_->field(i);
905 "const int $classname$::$constant_name$;\n",
906 "classname", ClassName(FieldScope(field), false),
907 "constant_name", FieldConstantName(field));
910 "#endif // !_MSC_VER\n"
913 // Define extension identifiers.
914 for (int i = 0; i < descriptor_->extension_count(); i++) {
915 extension_generators_[i]->GenerateDefinition(printer);
918 GenerateStructors(printer);
919 printer->Print("\n");
921 if (HasGeneratedMethods(descriptor_->file())) {
922 GenerateClear(printer);
923 printer->Print("\n");
925 GenerateMergeFromCodedStream(printer);
926 printer->Print("\n");
928 GenerateSerializeWithCachedSizes(printer);
929 printer->Print("\n");
931 if (HasFastArraySerialization(descriptor_->file())) {
932 GenerateSerializeWithCachedSizesToArray(printer);
933 printer->Print("\n");
936 GenerateByteSize(printer);
937 printer->Print("\n");
939 GenerateMergeFrom(printer);
940 printer->Print("\n");
942 GenerateCopyFrom(printer);
943 printer->Print("\n");
945 GenerateIsInitialized(printer);
946 printer->Print("\n");
949 GenerateSwap(printer);
950 printer->Print("\n");
952 if (HasDescriptorMethods(descriptor_->file())) {
954 "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
955 " protobuf_AssignDescriptorsOnce();\n"
956 " ::google::protobuf::Metadata metadata;\n"
957 " metadata.descriptor = $classname$_descriptor_;\n"
958 " metadata.reflection = $classname$_reflection_;\n"
959 " return metadata;\n"
962 "classname", classname_);
965 "::std::string $classname$::GetTypeName() const {\n"
966 " return \"$type_name$\";\n"
969 "classname", classname_,
970 "type_name", descriptor_->full_name());
975 void MessageGenerator::
976 GenerateOffsets(io::Printer* printer) {
978 "static const int $classname$_offsets_[$field_count$] = {\n",
979 "classname", classname_,
980 "field_count", SimpleItoa(max(1, descriptor_->field_count())));
983 for (int i = 0; i < descriptor_->field_count(); i++) {
984 const FieldDescriptor* field = descriptor_->field(i);
986 "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
987 "classname", classname_,
988 "name", FieldName(field));
992 printer->Print("};\n");
995 void MessageGenerator::
996 GenerateSharedConstructorCode(io::Printer* printer) {
998 "void $classname$::SharedCtor() {\n",
999 "classname", classname_);
1003 "_cached_size_ = 0;\n");
1005 for (int i = 0; i < descriptor_->field_count(); i++) {
1006 field_generators_.get(descriptor_->field(i))
1007 .GenerateConstructorCode(printer);
1011 "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
1014 printer->Print("}\n\n");
1017 void MessageGenerator::
1018 GenerateSharedDestructorCode(io::Printer* printer) {
1020 "void $classname$::SharedDtor() {\n",
1021 "classname", classname_);
1023 // Write the destructors for each field.
1024 for (int i = 0; i < descriptor_->field_count(); i++) {
1025 field_generators_.get(descriptor_->field(i))
1026 .GenerateDestructorCode(printer);
1029 PrintHandlingOptionalStaticInitializers(
1030 descriptor_->file(), printer,
1031 // With static initializers.
1032 "if (this != default_instance_) {\n",
1034 "if (this != &default_instance()) {\n");
1036 // We need to delete all embedded messages.
1037 // TODO(kenton): If we make unset messages point at default instances
1038 // instead of NULL, then it would make sense to move this code into
1039 // MessageFieldGenerator::GenerateDestructorCode().
1040 for (int i = 0; i < descriptor_->field_count(); i++) {
1041 const FieldDescriptor* field = descriptor_->field(i);
1043 if (!field->is_repeated() &&
1044 field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
1045 printer->Print(" delete $name$_;\n",
1046 "name", FieldName(field));
1057 void MessageGenerator::
1058 GenerateStructors(io::Printer* printer) {
1059 string superclass = SuperClassName(descriptor_);
1061 // Generate the default constructor.
1063 "$classname$::$classname$()\n"
1064 " : $superclass$() {\n"
1067 "classname", classname_,
1068 "superclass", superclass);
1072 "void $classname$::InitAsDefaultInstance() {\n",
1073 "classname", classname_);
1075 // The default instance needs all of its embedded message pointers
1076 // cross-linked to other default instances. We can't do this initialization
1077 // in the constructor because some other default instances may not have been
1078 // constructed yet at that time.
1079 // TODO(kenton): Maybe all message fields (even for non-default messages)
1080 // should be initialized to point at default instances rather than NULL?
1081 for (int i = 0; i < descriptor_->field_count(); i++) {
1082 const FieldDescriptor* field = descriptor_->field(i);
1084 if (!field->is_repeated() &&
1085 field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
1086 PrintHandlingOptionalStaticInitializers(
1087 descriptor_->file(), printer,
1088 // With static initializers.
1089 " $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
1091 " $name$_ = const_cast< $type$*>(\n"
1092 " $type$::internal_default_instance());\n",
1094 "name", FieldName(field),
1095 "type", FieldMessageTypeName(field));
1102 // Generate the copy constructor.
1104 "$classname$::$classname$(const $classname$& from)\n"
1105 " : $superclass$() {\n"
1107 " MergeFrom(from);\n"
1110 "classname", classname_,
1111 "superclass", superclass);
1113 // Generate the shared constructor code.
1114 GenerateSharedConstructorCode(printer);
1116 // Generate the destructor.
1118 "$classname$::~$classname$() {\n"
1122 "classname", classname_);
1124 // Generate the shared destructor code.
1125 GenerateSharedDestructorCode(printer);
1127 // Generate SetCachedSize.
1129 "void $classname$::SetCachedSize(int size) const {\n"
1130 " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
1131 " _cached_size_ = size;\n"
1132 " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
1134 "classname", classname_);
1136 // Only generate this member if it's not disabled.
1137 if (HasDescriptorMethods(descriptor_->file()) &&
1138 !descriptor_->options().no_standard_descriptor_accessor()) {
1140 "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
1141 " protobuf_AssignDescriptorsOnce();\n"
1142 " return $classname$_descriptor_;\n"
1145 "classname", classname_,
1146 "adddescriptorsname",
1147 GlobalAddDescriptorsName(descriptor_->file()->name()));
1151 "const $classname$& $classname$::default_instance() {\n",
1152 "classname", classname_);
1154 PrintHandlingOptionalStaticInitializers(
1155 descriptor_->file(), printer,
1156 // With static initializers.
1157 " if (default_instance_ == NULL) $adddescriptorsname$();\n",
1159 " $adddescriptorsname$();\n",
1161 "adddescriptorsname",
1162 GlobalAddDescriptorsName(descriptor_->file()->name()));
1165 " return *default_instance_;\n"
1168 "$classname$* $classname$::default_instance_ = NULL;\n"
1170 "$classname$* $classname$::New() const {\n"
1171 " return new $classname$;\n"
1173 "classname", classname_,
1174 "adddescriptorsname",
1175 GlobalAddDescriptorsName(descriptor_->file()->name()));
1178 void MessageGenerator::
1179 GenerateClear(io::Printer* printer) {
1180 printer->Print("void $classname$::Clear() {\n",
1181 "classname", classname_);
1184 int last_index = -1;
1186 if (descriptor_->extension_range_count() > 0) {
1187 printer->Print("_extensions_.Clear();\n");
1190 for (int i = 0; i < descriptor_->field_count(); i++) {
1191 const FieldDescriptor* field = descriptor_->field(i);
1193 if (!field->is_repeated()) {
1194 // We can use the fact that _has_bits_ is a giant bitfield to our
1195 // advantage: We can check up to 32 bits at a time for equality to
1196 // zero, and skip the whole range if so. This can improve the speed
1197 // of Clear() for messages which contain a very large number of
1198 // optional fields of which only a few are used at a time. Here,
1199 // we've chosen to check 8 bits at a time rather than 32.
1200 if (i / 8 != last_index / 8 || last_index < 0) {
1201 if (last_index >= 0) {
1203 printer->Print("}\n");
1206 "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
1207 "index", SimpleItoa(field->index()));
1212 // It's faster to just overwrite primitive types, but we should
1213 // only clear strings and messages if they were set.
1214 // TODO(kenton): Let the CppFieldGenerator decide this somehow.
1215 bool should_check_bit =
1216 field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
1217 field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
1219 if (should_check_bit) {
1221 "if (has_$name$()) {\n",
1222 "name", FieldName(field));
1226 field_generators_.get(field).GenerateClearingCode(printer);
1228 if (should_check_bit) {
1230 printer->Print("}\n");
1235 if (last_index >= 0) {
1237 printer->Print("}\n");
1240 // Repeated fields don't use _has_bits_ so we clear them in a separate
1242 for (int i = 0; i < descriptor_->field_count(); i++) {
1243 const FieldDescriptor* field = descriptor_->field(i);
1245 if (field->is_repeated()) {
1246 field_generators_.get(field).GenerateClearingCode(printer);
1251 "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
1253 if (HasUnknownFields(descriptor_->file())) {
1255 "mutable_unknown_fields()->Clear();\n");
1259 printer->Print("}\n");
1262 void MessageGenerator::
1263 GenerateSwap(io::Printer* printer) {
1264 // Generate the Swap member function.
1265 printer->Print("void $classname$::Swap($classname$* other) {\n",
1266 "classname", classname_);
1268 printer->Print("if (other != this) {\n");
1271 if (HasGeneratedMethods(descriptor_->file())) {
1272 for (int i = 0; i < descriptor_->field_count(); i++) {
1273 const FieldDescriptor* field = descriptor_->field(i);
1274 field_generators_.get(field).GenerateSwappingCode(printer);
1277 for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
1278 printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
1279 "i", SimpleItoa(i));
1282 if (HasUnknownFields(descriptor_->file())) {
1283 printer->Print("_unknown_fields_.Swap(&other->_unknown_fields_);\n");
1285 printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
1286 if (descriptor_->extension_range_count() > 0) {
1287 printer->Print("_extensions_.Swap(&other->_extensions_);\n");
1290 printer->Print("GetReflection()->Swap(this, other);");
1294 printer->Print("}\n");
1296 printer->Print("}\n");
1299 void MessageGenerator::
1300 GenerateMergeFrom(io::Printer* printer) {
1301 if (HasDescriptorMethods(descriptor_->file())) {
1302 // Generate the generalized MergeFrom (aka that which takes in the Message
1303 // base class as a parameter).
1305 "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
1306 " GOOGLE_CHECK_NE(&from, this);\n",
1307 "classname", classname_);
1310 // Cast the message to the proper type. If we find that the message is
1311 // *not* of the proper type, we can still call Merge via the reflection
1312 // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
1313 // for each message.
1315 "const $classname$* source =\n"
1316 " ::google::protobuf::internal::dynamic_cast_if_available<const $classname$*>(\n"
1318 "if (source == NULL) {\n"
1319 " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
1321 " MergeFrom(*source);\n"
1323 "classname", classname_);
1326 printer->Print("}\n\n");
1328 // Generate CheckTypeAndMergeFrom().
1330 "void $classname$::CheckTypeAndMergeFrom(\n"
1331 " const ::google::protobuf::MessageLite& from) {\n"
1332 " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
1335 "classname", classname_);
1338 // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
1340 "void $classname$::MergeFrom(const $classname$& from) {\n"
1341 " GOOGLE_CHECK_NE(&from, this);\n",
1342 "classname", classname_);
1345 // Merge Repeated fields. These fields do not require a
1346 // check as we can simply iterate over them.
1347 for (int i = 0; i < descriptor_->field_count(); ++i) {
1348 const FieldDescriptor* field = descriptor_->field(i);
1350 if (field->is_repeated()) {
1351 field_generators_.get(field).GenerateMergingCode(printer);
1355 // Merge Optional and Required fields (after a _has_bit check).
1356 int last_index = -1;
1358 for (int i = 0; i < descriptor_->field_count(); ++i) {
1359 const FieldDescriptor* field = descriptor_->field(i);
1361 if (!field->is_repeated()) {
1362 // See above in GenerateClear for an explanation of this.
1363 if (i / 8 != last_index / 8 || last_index < 0) {
1364 if (last_index >= 0) {
1366 printer->Print("}\n");
1369 "if (from._has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
1370 "index", SimpleItoa(field->index()));
1377 "if (from.has_$name$()) {\n",
1378 "name", FieldName(field));
1381 field_generators_.get(field).GenerateMergingCode(printer);
1384 printer->Print("}\n");
1388 if (last_index >= 0) {
1390 printer->Print("}\n");
1393 if (descriptor_->extension_range_count() > 0) {
1394 printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
1397 if (HasUnknownFields(descriptor_->file())) {
1399 "mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n");
1403 printer->Print("}\n");
1406 void MessageGenerator::
1407 GenerateCopyFrom(io::Printer* printer) {
1408 if (HasDescriptorMethods(descriptor_->file())) {
1409 // Generate the generalized CopyFrom (aka that which takes in the Message
1410 // base class as a parameter).
1412 "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n",
1413 "classname", classname_);
1417 "if (&from == this) return;\n"
1419 "MergeFrom(from);\n");
1422 printer->Print("}\n\n");
1425 // Generate the class-specific CopyFrom.
1427 "void $classname$::CopyFrom(const $classname$& from) {\n",
1428 "classname", classname_);
1432 "if (&from == this) return;\n"
1434 "MergeFrom(from);\n");
1437 printer->Print("}\n");
1440 void MessageGenerator::
1441 GenerateMergeFromCodedStream(io::Printer* printer) {
1442 if (descriptor_->options().message_set_wire_format()) {
1443 // Special-case MessageSet.
1445 "bool $classname$::MergePartialFromCodedStream(\n"
1446 " ::google::protobuf::io::CodedInputStream* input) {\n",
1447 "classname", classname_);
1449 PrintHandlingOptionalStaticInitializers(
1450 descriptor_->file(), printer,
1451 // With static initializers.
1452 " return _extensions_.ParseMessageSet(input, default_instance_,\n"
1453 " mutable_unknown_fields());\n",
1455 " return _extensions_.ParseMessageSet(input, &default_instance(),\n"
1456 " mutable_unknown_fields());\n",
1458 "classname", classname_);
1466 "bool $classname$::MergePartialFromCodedStream(\n"
1467 " ::google::protobuf::io::CodedInputStream* input) {\n"
1468 "#define DO_(EXPRESSION) if (!(EXPRESSION)) return false\n"
1469 " ::google::protobuf::uint32 tag;\n"
1470 " while ((tag = input->ReadTag()) != 0) {\n",
1471 "classname", classname_);
1476 if (descriptor_->field_count() > 0) {
1477 // We don't even want to print the switch() if we have no fields because
1478 // MSVC dislikes switch() statements that contain only a default value.
1480 // Note: If we just switched on the tag rather than the field number, we
1481 // could avoid the need for the if() to check the wire type at the beginning
1482 // of each case. However, this is actually a bit slower in practice as it
1483 // creates a jump table that is 8x larger and sparser, and meanwhile the
1484 // if()s are highly predictable.
1486 "switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {\n");
1490 scoped_array<const FieldDescriptor*> ordered_fields(
1491 SortFieldsByNumber(descriptor_));
1493 for (int i = 0; i < descriptor_->field_count(); i++) {
1494 const FieldDescriptor* field = ordered_fields[i];
1496 PrintFieldComment(printer, field);
1499 "case $number$: {\n",
1500 "number", SimpleItoa(field->number()));
1502 const FieldGenerator& field_generator = field_generators_.get(field);
1504 // Emit code to parse the common, expected case.
1506 "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
1507 " ::google::protobuf::internal::WireFormatLite::WIRETYPE_$wiretype$) {\n",
1508 "wiretype", kWireTypeNames[WireFormat::WireTypeForField(field)]);
1510 if (i > 0 || (field->is_repeated() && !field->options().packed())) {
1513 "name", field->name());
1517 if (field->options().packed()) {
1518 field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
1520 field_generator.GenerateMergeFromCodedStream(printer);
1524 // Emit code to parse unexpectedly packed or unpacked values.
1525 if (field->is_packable() && field->options().packed()) {
1527 "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
1528 " == ::google::protobuf::internal::WireFormatLite::\n"
1529 " WIRETYPE_$wiretype$) {\n",
1531 kWireTypeNames[WireFormat::WireTypeForFieldType(field->type())]);
1533 field_generator.GenerateMergeFromCodedStream(printer);
1535 } else if (field->is_packable() && !field->options().packed()) {
1537 "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
1538 " == ::google::protobuf::internal::WireFormatLite::\n"
1539 " WIRETYPE_LENGTH_DELIMITED) {\n");
1541 field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
1547 " goto handle_uninterpreted;\n"
1550 // switch() is slow since it can't be predicted well. Insert some if()s
1551 // here that attempt to predict the next tag.
1552 if (field->is_repeated() && !field->options().packed()) {
1553 // Expect repeats of this field.
1555 "if (input->ExpectTag($tag$)) goto parse_$name$;\n",
1556 "tag", SimpleItoa(WireFormat::MakeTag(field)),
1557 "name", field->name());
1560 if (i + 1 < descriptor_->field_count()) {
1561 // Expect the next field in order.
1562 const FieldDescriptor* next_field = ordered_fields[i + 1];
1564 "if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
1565 "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
1566 "next_name", next_field->name());
1569 // TODO(kenton): Expect group end-tag?
1571 "if (input->ExpectAtEnd()) return true;\n");
1578 printer->Print("}\n\n");
1583 "handle_uninterpreted:\n");
1587 // Is this an end-group tag? If so, this must be the end of the message.
1589 "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
1590 " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
1594 // Handle extension ranges.
1595 if (descriptor_->extension_range_count() > 0) {
1598 for (int i = 0; i < descriptor_->extension_range_count(); i++) {
1599 const Descriptor::ExtensionRange* range =
1600 descriptor_->extension_range(i);
1601 if (i > 0) printer->Print(" ||\n ");
1603 uint32 start_tag = WireFormatLite::MakeTag(
1604 range->start, static_cast<WireFormatLite::WireType>(0));
1605 uint32 end_tag = WireFormatLite::MakeTag(
1606 range->end, static_cast<WireFormatLite::WireType>(0));
1608 if (range->end > FieldDescriptor::kMaxNumber) {
1610 "($start$u <= tag)",
1611 "start", SimpleItoa(start_tag));
1614 "($start$u <= tag && tag < $end$u)",
1615 "start", SimpleItoa(start_tag),
1616 "end", SimpleItoa(end_tag));
1619 printer->Print(") {\n");
1620 if (HasUnknownFields(descriptor_->file())) {
1621 PrintHandlingOptionalStaticInitializers(
1622 descriptor_->file(), printer,
1623 // With static initializers.
1624 " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
1625 " mutable_unknown_fields()));\n",
1627 " DO_(_extensions_.ParseField(tag, input, &default_instance(),\n"
1628 " mutable_unknown_fields()));\n");
1630 PrintHandlingOptionalStaticInitializers(
1631 descriptor_->file(), printer,
1632 // With static initializers.
1633 " DO_(_extensions_.ParseField(tag, input, default_instance_, NULL));\n",
1635 " DO_(_extensions_.ParseField(tag, input, &default_instance(), NULL));\n");
1642 // We really don't recognize this tag. Skip it.
1643 if (HasUnknownFields(descriptor_->file())) {
1645 "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag, mutable_unknown_fields()));\n");
1648 "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag, NULL));\n");
1651 if (descriptor_->field_count() > 0) {
1652 printer->Print("break;\n");
1654 printer->Print("}\n"); // default:
1656 printer->Print("}\n"); // switch
1668 void MessageGenerator::GenerateSerializeOneField(
1669 io::Printer* printer, const FieldDescriptor* field, bool to_array) {
1670 PrintFieldComment(printer, field);
1672 if (!field->is_repeated()) {
1674 "if (has_$name$()) {\n",
1675 "name", FieldName(field));
1680 field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
1683 field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
1686 if (!field->is_repeated()) {
1688 printer->Print("}\n");
1690 printer->Print("\n");
1693 void MessageGenerator::GenerateSerializeOneExtensionRange(
1694 io::Printer* printer, const Descriptor::ExtensionRange* range,
1696 map<string, string> vars;
1697 vars["start"] = SimpleItoa(range->start);
1698 vars["end"] = SimpleItoa(range->end);
1699 printer->Print(vars,
1700 "// Extension range [$start$, $end$)\n");
1702 printer->Print(vars,
1703 "target = _extensions_.SerializeWithCachedSizesToArray(\n"
1704 " $start$, $end$, target);\n\n");
1706 printer->Print(vars,
1707 "_extensions_.SerializeWithCachedSizes(\n"
1708 " $start$, $end$, output);\n\n");
1712 void MessageGenerator::
1713 GenerateSerializeWithCachedSizes(io::Printer* printer) {
1714 if (descriptor_->options().message_set_wire_format()) {
1715 // Special-case MessageSet.
1717 "void $classname$::SerializeWithCachedSizes(\n"
1718 " ::google::protobuf::io::CodedOutputStream* output) const {\n"
1719 " _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
1720 "classname", classname_);
1721 if (HasUnknownFields(descriptor_->file())) {
1723 " ::google::protobuf::internal::WireFormatLite::SerializeUnknownMessageSetItems(\n"
1724 " unknown_fields(), output);\n");
1732 "void $classname$::SerializeWithCachedSizes(\n"
1733 " ::google::protobuf::io::CodedOutputStream* output) const {\n",
1734 "classname", classname_);
1737 GenerateSerializeWithCachedSizesBody(printer, false);
1744 void MessageGenerator::
1745 GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
1746 if (descriptor_->options().message_set_wire_format()) {
1747 // Special-case MessageSet.
1749 "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
1750 " ::google::protobuf::uint8* target) const {\n"
1752 " _extensions_.SerializeMessageSetWithCachedSizesToArray(target);\n",
1753 "classname", classname_);
1754 if (HasUnknownFields(descriptor_->file())) {
1756 " target = ::google::protobuf::internal::WireFormatLite::\n"
1757 " SerializeUnknownMessageSetItemsToArray(\n"
1758 " unknown_fields(), target);\n");
1767 "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
1768 " ::google::protobuf::uint8* target) const {\n",
1769 "classname", classname_);
1772 GenerateSerializeWithCachedSizesBody(printer, true);
1780 void MessageGenerator::
1781 GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
1782 scoped_array<const FieldDescriptor*> ordered_fields(
1783 SortFieldsByNumber(descriptor_));
1785 vector<const Descriptor::ExtensionRange*> sorted_extensions;
1786 for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
1787 sorted_extensions.push_back(descriptor_->extension_range(i));
1789 sort(sorted_extensions.begin(), sorted_extensions.end(),
1790 ExtensionRangeSorter());
1792 // Merge the fields and the extension ranges, both sorted by field number.
1795 i < descriptor_->field_count() || j < sorted_extensions.size();
1797 if (i == descriptor_->field_count()) {
1798 GenerateSerializeOneExtensionRange(printer,
1799 sorted_extensions[j++],
1801 } else if (j == sorted_extensions.size()) {
1802 GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
1803 } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
1804 GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
1806 GenerateSerializeOneExtensionRange(printer,
1807 sorted_extensions[j++],
1812 if (HasUnknownFields(descriptor_->file())) {
1813 printer->Print("if (!unknown_fields().empty()) {\n");
1818 "::google::protobuf::internal::WireFormatLite::SerializeUnknownFieldsToArray(\n"
1819 " unknown_fields(), target);\n");
1822 "::google::protobuf::internal::WireFormatLite::SerializeUnknownFields(\n"
1823 " unknown_fields(), output);\n");
1832 void MessageGenerator::
1833 GenerateByteSize(io::Printer* printer) {
1834 if (descriptor_->options().message_set_wire_format()) {
1835 // Special-case MessageSet.
1837 "int $classname$::ByteSize() const {\n"
1838 " int total_size = _extensions_.MessageSetByteSize();\n",
1839 "classname", classname_);
1840 if (HasUnknownFields(descriptor_->file())) {
1842 " total_size += ::google::protobuf::internal::WireFormatLite::\n"
1843 " ComputeUnknownMessageSetItemsSize(unknown_fields());\n");
1846 " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
1847 " _cached_size_ = total_size;\n"
1848 " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
1849 " return total_size;\n"
1855 "int $classname$::ByteSize() const {\n",
1856 "classname", classname_);
1859 "int total_size = 0;\n"
1862 int last_index = -1;
1864 for (int i = 0; i < descriptor_->field_count(); i++) {
1865 const FieldDescriptor* field = descriptor_->field(i);
1867 if (!field->is_repeated()) {
1868 // See above in GenerateClear for an explanation of this.
1869 // TODO(kenton): Share code? Unclear how to do so without
1870 // over-engineering.
1871 if ((i / 8) != (last_index / 8) ||
1873 if (last_index >= 0) {
1875 printer->Print("}\n");
1878 "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
1879 "index", SimpleItoa(field->index()));
1884 PrintFieldComment(printer, field);
1887 "if (has_$name$()) {\n",
1888 "name", FieldName(field));
1891 field_generators_.get(field).GenerateByteSize(printer);
1900 if (last_index >= 0) {
1902 printer->Print("}\n");
1905 // Repeated fields don't use _has_bits_ so we count them in a separate
1907 for (int i = 0; i < descriptor_->field_count(); i++) {
1908 const FieldDescriptor* field = descriptor_->field(i);
1910 if (field->is_repeated()) {
1911 PrintFieldComment(printer, field);
1912 field_generators_.get(field).GenerateByteSize(printer);
1913 printer->Print("\n");
1917 if (descriptor_->extension_range_count() > 0) {
1919 "total_size += _extensions_.ByteSize();\n"
1923 if (HasUnknownFields(descriptor_->file())) {
1924 printer->Print("if (!unknown_fields().empty()) {\n");
1928 " ::google::protobuf::internal::WireFormatLite::ComputeUnknownFieldsSize(\n"
1929 " unknown_fields());\n");
1931 printer->Print("}\n");
1934 // We update _cached_size_ even though this is a const method. In theory,
1935 // this is not thread-compatible, because concurrent writes have undefined
1936 // results. In practice, since any concurrent writes will be writing the
1937 // exact same value, it works on all common processors. In a future version
1938 // of C++, _cached_size_ should be made into an atomic<int>.
1940 "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
1941 "_cached_size_ = total_size;\n"
1942 "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
1943 "return total_size;\n");
1946 printer->Print("}\n");
1949 void MessageGenerator::
1950 GenerateIsInitialized(io::Printer* printer) {
1952 "bool $classname$::IsInitialized() const {\n",
1953 "classname", classname_);
1956 // Check that all required fields in this message are set. We can do this
1957 // most efficiently by checking 32 "has bits" at a time.
1958 int has_bits_array_size = (descriptor_->field_count() + 31) / 32;
1959 for (int i = 0; i < has_bits_array_size; i++) {
1961 for (int bit = 0; bit < 32; bit++) {
1962 int index = i * 32 + bit;
1963 if (index >= descriptor_->field_count()) break;
1964 const FieldDescriptor* field = descriptor_->field(index);
1966 if (field->is_required()) {
1972 char buffer[kFastToBufferSize];
1974 "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n",
1976 "mask", FastHex32ToBuffer(mask, buffer));
1980 // Now check that all embedded messages are initialized.
1981 printer->Print("\n");
1982 for (int i = 0; i < descriptor_->field_count(); i++) {
1983 const FieldDescriptor* field = descriptor_->field(i);
1984 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
1985 !ShouldIgnoreRequiredFieldCheck(field) &&
1986 HasRequiredFields(field->message_type())) {
1987 if (field->is_repeated()) {
1989 "for (int i = 0; i < $name$_size(); i++) {\n"
1990 " if (!this->$name$(i).IsInitialized()) return false;\n"
1992 "name", FieldName(field));
1995 "if (has_$name$()) {\n"
1996 " if (!this->$name$().IsInitialized()) return false;\n"
1998 "name", FieldName(field));
2003 if (descriptor_->extension_range_count() > 0) {
2006 "if (!_extensions_.IsInitialized()) return false;");
2017 } // namespace compiler
2018 } // namespace protobuf
2019 } // namespace google