cpp_message.cc revision fbaaef999ba563838ebd00874ed8a1c01fbf286d
1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// http://code.google.com/p/protobuf/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// Author: kenton@google.com (Kenton Varda)
32//  Based on original Protocol Buffers design by
33//  Sanjay Ghemawat, Jeff Dean, and others.
34
35#include <algorithm>
36#include <google/protobuf/stubs/hash.h>
37#include <map>
38#include <vector>
39#include <google/protobuf/compiler/cpp/cpp_message.h>
40#include <google/protobuf/compiler/cpp/cpp_field.h>
41#include <google/protobuf/compiler/cpp/cpp_enum.h>
42#include <google/protobuf/compiler/cpp/cpp_extension.h>
43#include <google/protobuf/compiler/cpp/cpp_helpers.h>
44#include <google/protobuf/stubs/strutil.h>
45#include <google/protobuf/io/printer.h>
46#include <google/protobuf/io/coded_stream.h>
47#include <google/protobuf/wire_format.h>
48#include <google/protobuf/descriptor.pb.h>
49
50namespace google {
51namespace protobuf {
52namespace compiler {
53namespace cpp {
54
55using internal::WireFormat;
56using internal::WireFormatLite;
57
58namespace {
59
60void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) {
61  // Print the field's proto-syntax definition as a comment.  We don't want to
62  // print group bodies so we cut off after the first line.
63  string def = field->DebugString();
64  printer->Print("// $def$\n",
65    "def", def.substr(0, def.find_first_of('\n')));
66}
67
68struct FieldOrderingByNumber {
69  inline bool operator()(const FieldDescriptor* a,
70                         const FieldDescriptor* b) const {
71    return a->number() < b->number();
72  }
73};
74
75const char* kWireTypeNames[] = {
76  "VARINT",
77  "FIXED64",
78  "LENGTH_DELIMITED",
79  "START_GROUP",
80  "END_GROUP",
81  "FIXED32",
82};
83
84// Sort the fields of the given Descriptor by number into a new[]'d array
85// and return it.
86const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
87  const FieldDescriptor** fields =
88    new const FieldDescriptor*[descriptor->field_count()];
89  for (int i = 0; i < descriptor->field_count(); i++) {
90    fields[i] = descriptor->field(i);
91  }
92  sort(fields, fields + descriptor->field_count(),
93       FieldOrderingByNumber());
94  return fields;
95}
96
97// Functor for sorting extension ranges by their "start" field number.
98struct ExtensionRangeSorter {
99  bool operator()(const Descriptor::ExtensionRange* left,
100                  const Descriptor::ExtensionRange* right) const {
101    return left->start < right->start;
102  }
103};
104
105// Returns true if the message type has any required fields.  If it doesn't,
106// we can optimize out calls to its IsInitialized() method.
107//
108// already_seen is used to avoid checking the same type multiple times
109// (and also to protect against recursion).
110static bool HasRequiredFields(
111    const Descriptor* type,
112    hash_set<const Descriptor*>* already_seen) {
113  if (already_seen->count(type) > 0) {
114    // Since the first occurrence of a required field causes the whole
115    // function to return true, we can assume that if the type is already
116    // in the cache it didn't have any required fields.
117    return false;
118  }
119  already_seen->insert(type);
120
121  // If the type has extensions, an extension with message type could contain
122  // required fields, so we have to be conservative and assume such an
123  // extension exists.
124  if (type->extension_range_count() > 0) return true;
125
126  for (int i = 0; i < type->field_count(); i++) {
127    const FieldDescriptor* field = type->field(i);
128    if (field->is_required()) {
129      return true;
130    }
131    if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
132      if (HasRequiredFields(field->message_type(), already_seen)) {
133        return true;
134      }
135    }
136  }
137
138  return false;
139}
140
141static bool HasRequiredFields(const Descriptor* type) {
142  hash_set<const Descriptor*> already_seen;
143  return HasRequiredFields(type, &already_seen);
144}
145
146}
147
148// ===================================================================
149
150MessageGenerator::MessageGenerator(const Descriptor* descriptor,
151                                   const string& dllexport_decl)
152  : descriptor_(descriptor),
153    classname_(ClassName(descriptor, false)),
154    dllexport_decl_(dllexport_decl),
155    field_generators_(descriptor),
156    nested_generators_(new scoped_ptr<MessageGenerator>[
157      descriptor->nested_type_count()]),
158    enum_generators_(new scoped_ptr<EnumGenerator>[
159      descriptor->enum_type_count()]),
160    extension_generators_(new scoped_ptr<ExtensionGenerator>[
161      descriptor->extension_count()]) {
162
163  for (int i = 0; i < descriptor->nested_type_count(); i++) {
164    nested_generators_[i].reset(
165      new MessageGenerator(descriptor->nested_type(i), dllexport_decl));
166  }
167
168  for (int i = 0; i < descriptor->enum_type_count(); i++) {
169    enum_generators_[i].reset(
170      new EnumGenerator(descriptor->enum_type(i), dllexport_decl));
171  }
172
173  for (int i = 0; i < descriptor->extension_count(); i++) {
174    extension_generators_[i].reset(
175      new ExtensionGenerator(descriptor->extension(i), dllexport_decl));
176  }
177}
178
179MessageGenerator::~MessageGenerator() {}
180
181void MessageGenerator::
182GenerateForwardDeclaration(io::Printer* printer) {
183  printer->Print("class $classname$;\n",
184                 "classname", classname_);
185
186  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
187    nested_generators_[i]->GenerateForwardDeclaration(printer);
188  }
189}
190
191void MessageGenerator::
192GenerateEnumDefinitions(io::Printer* printer) {
193  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
194    nested_generators_[i]->GenerateEnumDefinitions(printer);
195  }
196
197  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
198    enum_generators_[i]->GenerateDefinition(printer);
199  }
200}
201
202void MessageGenerator::
203GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
204  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
205    nested_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
206  }
207  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
208    enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
209  }
210}
211
212void MessageGenerator::
213GenerateFieldAccessorDeclarations(io::Printer* printer) {
214  for (int i = 0; i < descriptor_->field_count(); i++) {
215    const FieldDescriptor* field = descriptor_->field(i);
216
217    PrintFieldComment(printer, field);
218
219    map<string, string> vars;
220    SetCommonFieldVariables(field, &vars);
221    vars["constant_name"] = FieldConstantName(field);
222
223    if (field->is_repeated()) {
224      printer->Print(vars, "inline int $name$_size() const$deprecation$;\n");
225    } else {
226      printer->Print(vars, "inline bool has_$name$() const$deprecation$;\n");
227    }
228
229    printer->Print(vars, "inline void clear_$name$()$deprecation$;\n");
230    printer->Print(vars, "static const int $constant_name$ = $number$;\n");
231
232    // Generate type-specific accessor declarations.
233    field_generators_.get(field).GenerateAccessorDeclarations(printer);
234
235    printer->Print("\n");
236  }
237
238  if (descriptor_->extension_range_count() > 0) {
239    // Generate accessors for extensions.  We just call a macro located in
240    // extension_set.h since the accessors about 80 lines of static code.
241    printer->Print(
242      "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
243      "classname", classname_);
244  }
245}
246
247void MessageGenerator::
248GenerateFieldAccessorDefinitions(io::Printer* printer) {
249  printer->Print("// $classname$\n\n", "classname", classname_);
250
251  for (int i = 0; i < descriptor_->field_count(); i++) {
252    const FieldDescriptor* field = descriptor_->field(i);
253
254    PrintFieldComment(printer, field);
255
256    map<string, string> vars;
257    SetCommonFieldVariables(field, &vars);
258
259    // Generate has_$name$() or $name$_size().
260    if (field->is_repeated()) {
261      printer->Print(vars,
262        "inline int $classname$::$name$_size() const {\n"
263        "  return $name$_.size();\n"
264        "}\n");
265    } else {
266      // Singular field.
267      printer->Print(vars,
268        "inline bool $classname$::has_$name$() const {\n"
269        "  return _has_bit($index$);\n"
270        "}\n");
271    }
272
273    // Generate clear_$name$()
274    printer->Print(vars,
275      "inline void $classname$::clear_$name$() {\n");
276
277    printer->Indent();
278    field_generators_.get(field).GenerateClearingCode(printer);
279    printer->Outdent();
280
281    if (!field->is_repeated()) {
282      printer->Print(vars, "  _clear_bit($index$);\n");
283    }
284
285    printer->Print("}\n");
286
287    // Generate type-specific accessors.
288    field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
289
290    printer->Print("\n");
291  }
292}
293
294void MessageGenerator::
295GenerateClassDefinition(io::Printer* printer) {
296  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
297    nested_generators_[i]->GenerateClassDefinition(printer);
298    printer->Print("\n");
299    printer->Print(kThinSeparator);
300    printer->Print("\n");
301  }
302
303  map<string, string> vars;
304  vars["classname"] = classname_;
305  vars["field_count"] = SimpleItoa(descriptor_->field_count());
306  if (dllexport_decl_.empty()) {
307    vars["dllexport"] = "";
308  } else {
309    vars["dllexport"] = dllexport_decl_ + " ";
310  }
311  vars["superclass"] = HasDescriptorMethods(descriptor_->file()) ?
312                       "Message" : "MessageLite";
313
314  printer->Print(vars,
315    "class $dllexport$$classname$ : public ::google::protobuf::$superclass$ {\n"
316    " public:\n");
317  printer->Indent();
318
319  printer->Print(vars,
320    "$classname$();\n"
321    "virtual ~$classname$();\n"
322    "\n"
323    "$classname$(const $classname$& from);\n"
324    "\n"
325    "inline $classname$& operator=(const $classname$& from) {\n"
326    "  CopyFrom(from);\n"
327    "  return *this;\n"
328    "}\n"
329    "\n");
330
331  if (HasUnknownFields(descriptor_->file())) {
332    printer->Print(
333      "inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {\n"
334      "  return _unknown_fields_;\n"
335      "}\n"
336      "\n"
337      "inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {\n"
338      "  return &_unknown_fields_;\n"
339      "}\n"
340      "\n");
341  }
342
343  // Only generate this member if it's not disabled.
344  if (HasDescriptorMethods(descriptor_->file()) &&
345      !descriptor_->options().no_standard_descriptor_accessor()) {
346    printer->Print(vars,
347      "static const ::google::protobuf::Descriptor* descriptor();\n");
348  }
349
350  printer->Print(vars,
351    "static const $classname$& default_instance();\n"
352    "void Swap($classname$* other);\n"
353    "\n"
354    "// implements Message ----------------------------------------------\n"
355    "\n"
356    "$classname$* New() const;\n");
357
358  if (HasGeneratedMethods(descriptor_->file())) {
359    if (HasDescriptorMethods(descriptor_->file())) {
360      printer->Print(vars,
361        "void CopyFrom(const ::google::protobuf::Message& from);\n"
362        "void MergeFrom(const ::google::protobuf::Message& from);\n");
363    } else {
364      printer->Print(vars,
365        "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);\n");
366    }
367
368    printer->Print(vars,
369      "void CopyFrom(const $classname$& from);\n"
370      "void MergeFrom(const $classname$& from);\n"
371      "void Clear();\n"
372      "bool IsInitialized() const;\n"
373      "\n"
374      "int ByteSize() const;\n"
375      "bool MergePartialFromCodedStream(\n"
376      "    ::google::protobuf::io::CodedInputStream* input);\n"
377      "void SerializeWithCachedSizes(\n"
378      "    ::google::protobuf::io::CodedOutputStream* output) const;\n");
379    if (HasFastArraySerialization(descriptor_->file())) {
380      printer->Print(
381        "::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;\n");
382    }
383  }
384
385  printer->Print(vars,
386    "int GetCachedSize() const { return _cached_size_; }\n"
387    "private:\n"
388    "void SharedCtor();\n"
389    "void SharedDtor();\n"
390    "void SetCachedSize(int size) const { _cached_size_ = size; }\n"
391    "public:\n"
392    "\n");
393
394  if (HasDescriptorMethods(descriptor_->file())) {
395    printer->Print(
396      "::google::protobuf::Metadata GetMetadata() const;\n"
397      "\n");
398  } else {
399    printer->Print(
400      "::std::string GetTypeName() const;\n"
401      "\n");
402  }
403
404  printer->Print(
405    "// nested types ----------------------------------------------------\n"
406    "\n");
407
408  // Import all nested message classes into this class's scope with typedefs.
409  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
410    const Descriptor* nested_type = descriptor_->nested_type(i);
411    printer->Print("typedef $nested_full_name$ $nested_name$;\n",
412                   "nested_name", nested_type->name(),
413                   "nested_full_name", ClassName(nested_type, false));
414  }
415
416  if (descriptor_->nested_type_count() > 0) {
417    printer->Print("\n");
418  }
419
420  // Import all nested enums and their values into this class's scope with
421  // typedefs and constants.
422  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
423    enum_generators_[i]->GenerateSymbolImports(printer);
424    printer->Print("\n");
425  }
426
427  printer->Print(
428    "// accessors -------------------------------------------------------\n"
429    "\n");
430
431  // Generate accessor methods for all fields.
432  GenerateFieldAccessorDeclarations(printer);
433
434  // Declare extension identifiers.
435  for (int i = 0; i < descriptor_->extension_count(); i++) {
436    extension_generators_[i]->GenerateDeclaration(printer);
437  }
438
439  // Generate private members for fields.
440  printer->Outdent();
441  printer->Print(" private:\n");
442  printer->Indent();
443
444  if (descriptor_->extension_range_count() > 0) {
445    printer->Print(
446      "::google::protobuf::internal::ExtensionSet _extensions_;\n");
447  }
448
449  if (HasUnknownFields(descriptor_->file())) {
450    printer->Print(
451      "::google::protobuf::UnknownFieldSet _unknown_fields_;\n");
452  }
453
454  // TODO(kenton):  Make _cached_size_ an atomic<int> when C++ supports it.
455  printer->Print(
456    "mutable int _cached_size_;\n"
457    "\n");
458  for (int i = 0; i < descriptor_->field_count(); i++) {
459    field_generators_.get(descriptor_->field(i))
460                     .GeneratePrivateMembers(printer);
461  }
462
463  // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
464  // friends so that they can access private static variables like
465  // default_instance_ and reflection_.
466  printer->Print(
467    "friend void $dllexport_decl$ $adddescriptorsname$();\n",
468    "dllexport_decl", dllexport_decl_,
469    "adddescriptorsname",
470      GlobalAddDescriptorsName(descriptor_->file()->name()));
471  printer->Print(
472    "friend void $assigndescriptorsname$();\n"
473    "friend void $shutdownfilename$();\n"
474    "\n",
475    "assigndescriptorsname",
476      GlobalAssignDescriptorsName(descriptor_->file()->name()),
477    "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
478
479  // Generate offsets and _has_bits_ boilerplate.
480  if (descriptor_->field_count() > 0) {
481    printer->Print(vars,
482      "::google::protobuf::uint32 _has_bits_[($field_count$ + 31) / 32];\n");
483  } else {
484    // Zero-size arrays aren't technically allowed, and MSVC in particular
485    // doesn't like them.  We still need to declare these arrays to make
486    // other code compile.  Since this is an uncommon case, we'll just declare
487    // them with size 1 and waste some space.  Oh well.
488    printer->Print(
489      "::google::protobuf::uint32 _has_bits_[1];\n");
490  }
491
492  printer->Print(
493    "\n"
494    "// WHY DOES & HAVE LOWER PRECEDENCE THAN != !?\n"
495    "inline bool _has_bit(int index) const {\n"
496    "  return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;\n"
497    "}\n"
498    "inline void _set_bit(int index) {\n"
499    "  _has_bits_[index / 32] |= (1u << (index % 32));\n"
500    "}\n"
501    "inline void _clear_bit(int index) {\n"
502    "  _has_bits_[index / 32] &= ~(1u << (index % 32));\n"
503    "}\n"
504    "\n"
505    "void InitAsDefaultInstance();\n"
506    "static $classname$* default_instance_;\n",
507    "classname", classname_);
508
509  printer->Outdent();
510  printer->Print(vars, "};");
511}
512
513void MessageGenerator::
514GenerateInlineMethods(io::Printer* printer) {
515  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
516    nested_generators_[i]->GenerateInlineMethods(printer);
517    printer->Print(kThinSeparator);
518    printer->Print("\n");
519  }
520
521  GenerateFieldAccessorDefinitions(printer);
522}
523
524void MessageGenerator::
525GenerateDescriptorDeclarations(io::Printer* printer) {
526  printer->Print(
527    "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
528    "const ::google::protobuf::internal::GeneratedMessageReflection*\n"
529    "  $name$_reflection_ = NULL;\n",
530    "name", classname_);
531
532  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
533    nested_generators_[i]->GenerateDescriptorDeclarations(printer);
534  }
535
536  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
537    printer->Print(
538      "const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
539      "name", ClassName(descriptor_->enum_type(i), false));
540  }
541}
542
543void MessageGenerator::
544GenerateDescriptorInitializer(io::Printer* printer, int index) {
545  // TODO(kenton):  Passing the index to this method is redundant; just use
546  //   descriptor_->index() instead.
547  map<string, string> vars;
548  vars["classname"] = classname_;
549  vars["index"] = SimpleItoa(index);
550
551  // Obtain the descriptor from the parent's descriptor.
552  if (descriptor_->containing_type() == NULL) {
553    printer->Print(vars,
554      "$classname$_descriptor_ = file->message_type($index$);\n");
555  } else {
556    vars["parent"] = ClassName(descriptor_->containing_type(), false);
557    printer->Print(vars,
558      "$classname$_descriptor_ = "
559        "$parent$_descriptor_->nested_type($index$);\n");
560  }
561
562  // Generate the offsets.
563  GenerateOffsets(printer);
564
565  // Construct the reflection object.
566  printer->Print(vars,
567    "$classname$_reflection_ =\n"
568    "  new ::google::protobuf::internal::GeneratedMessageReflection(\n"
569    "    $classname$_descriptor_,\n"
570    "    $classname$::default_instance_,\n"
571    "    $classname$_offsets_,\n"
572    "    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n"
573    "    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
574      "$classname$, _unknown_fields_),\n");
575  if (descriptor_->extension_range_count() > 0) {
576    printer->Print(vars,
577      "    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
578        "$classname$, _extensions_),\n");
579  } else {
580    // No extensions.
581    printer->Print(vars,
582      "    -1,\n");
583  }
584  printer->Print(vars,
585    "    ::google::protobuf::DescriptorPool::generated_pool(),\n"
586    "    ::google::protobuf::MessageFactory::generated_factory(),\n"
587    "    sizeof($classname$));\n");
588
589  // Handle nested types.
590  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
591    nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
592  }
593
594  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
595    enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
596  }
597}
598
599void MessageGenerator::
600GenerateTypeRegistrations(io::Printer* printer) {
601  // Register this message type with the message factory.
602  printer->Print(
603    "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
604    "  $classname$_descriptor_, &$classname$::default_instance());\n",
605    "classname", classname_);
606
607  // Handle nested types.
608  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
609    nested_generators_[i]->GenerateTypeRegistrations(printer);
610  }
611}
612
613void MessageGenerator::
614GenerateDefaultInstanceAllocator(io::Printer* printer) {
615  // Construct the default instance.  We can't call InitAsDefaultInstance() yet
616  // because we need to make sure all default instances that this one might
617  // depend on are constructed first.
618  printer->Print(
619    "$classname$::default_instance_ = new $classname$();\n",
620    "classname", classname_);
621
622  // Handle nested types.
623  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
624    nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
625  }
626}
627
628void MessageGenerator::
629GenerateDefaultInstanceInitializer(io::Printer* printer) {
630  printer->Print(
631    "$classname$::default_instance_->InitAsDefaultInstance();\n",
632    "classname", classname_);
633
634  // Register extensions.
635  for (int i = 0; i < descriptor_->extension_count(); i++) {
636    extension_generators_[i]->GenerateRegistration(printer);
637  }
638
639  // Handle nested types.
640  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
641    nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
642  }
643}
644
645void MessageGenerator::
646GenerateShutdownCode(io::Printer* printer) {
647  printer->Print(
648    "delete $classname$::default_instance_;\n",
649    "classname", classname_);
650
651  if (HasDescriptorMethods(descriptor_->file())) {
652    printer->Print(
653      "delete $classname$_reflection_;\n",
654      "classname", classname_);
655  }
656
657  // Handle nested types.
658  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
659    nested_generators_[i]->GenerateShutdownCode(printer);
660  }
661}
662
663void MessageGenerator::
664GenerateClassMethods(io::Printer* printer) {
665  for (int i = 0; i < descriptor_->enum_type_count(); i++) {
666    enum_generators_[i]->GenerateMethods(printer);
667  }
668
669  for (int i = 0; i < descriptor_->nested_type_count(); i++) {
670    nested_generators_[i]->GenerateClassMethods(printer);
671    printer->Print("\n");
672    printer->Print(kThinSeparator);
673    printer->Print("\n");
674  }
675
676  // Generate non-inline field definitions.
677  for (int i = 0; i < descriptor_->field_count(); i++) {
678    field_generators_.get(descriptor_->field(i))
679                     .GenerateNonInlineAccessorDefinitions(printer);
680  }
681
682  // Generate field number constants.
683  printer->Print("#ifndef _MSC_VER\n");
684  for (int i = 0; i < descriptor_->field_count(); i++) {
685    const FieldDescriptor *field = descriptor_->field(i);
686    printer->Print(
687      "const int $classname$::$constant_name$;\n",
688      "classname", ClassName(FieldScope(field), false),
689      "constant_name", FieldConstantName(field));
690  }
691  printer->Print(
692    "#endif  // !_MSC_VER\n"
693    "\n");
694
695  // Define extension identifiers.
696  for (int i = 0; i < descriptor_->extension_count(); i++) {
697    extension_generators_[i]->GenerateDefinition(printer);
698  }
699
700  GenerateStructors(printer);
701  printer->Print("\n");
702
703  if (HasGeneratedMethods(descriptor_->file())) {
704    GenerateClear(printer);
705    printer->Print("\n");
706
707    GenerateMergeFromCodedStream(printer);
708    printer->Print("\n");
709
710    GenerateSerializeWithCachedSizes(printer);
711    printer->Print("\n");
712
713    if (HasFastArraySerialization(descriptor_->file())) {
714      GenerateSerializeWithCachedSizesToArray(printer);
715      printer->Print("\n");
716    }
717
718    GenerateByteSize(printer);
719    printer->Print("\n");
720
721    GenerateMergeFrom(printer);
722    printer->Print("\n");
723
724    GenerateCopyFrom(printer);
725    printer->Print("\n");
726
727    GenerateIsInitialized(printer);
728    printer->Print("\n");
729  }
730
731  GenerateSwap(printer);
732  printer->Print("\n");
733
734  if (HasDescriptorMethods(descriptor_->file())) {
735    printer->Print(
736      "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
737      "  protobuf_AssignDescriptorsOnce();\n"
738      "  ::google::protobuf::Metadata metadata;\n"
739      "  metadata.descriptor = $classname$_descriptor_;\n"
740      "  metadata.reflection = $classname$_reflection_;\n"
741      "  return metadata;\n"
742      "}\n"
743      "\n",
744      "classname", classname_);
745  } else {
746    printer->Print(
747      "::std::string $classname$::GetTypeName() const {\n"
748      "  return \"$type_name$\";\n"
749      "}\n"
750      "\n",
751      "classname", classname_,
752      "type_name", descriptor_->full_name());
753  }
754}
755
756void MessageGenerator::
757GenerateOffsets(io::Printer* printer) {
758  printer->Print(
759    "static const int $classname$_offsets_[$field_count$] = {\n",
760    "classname", classname_,
761    "field_count", SimpleItoa(max(1, descriptor_->field_count())));
762  printer->Indent();
763
764  for (int i = 0; i < descriptor_->field_count(); i++) {
765    const FieldDescriptor* field = descriptor_->field(i);
766    printer->Print(
767      "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
768      "classname", classname_,
769      "name", FieldName(field));
770  }
771
772  printer->Outdent();
773  printer->Print("};\n");
774}
775
776void MessageGenerator::
777GenerateSharedConstructorCode(io::Printer* printer) {
778  printer->Print(
779    "void $classname$::SharedCtor() {\n",
780    "classname", classname_);
781  printer->Indent();
782
783  printer->Print(
784    "_cached_size_ = 0;\n");
785
786  for (int i = 0; i < descriptor_->field_count(); i++) {
787    field_generators_.get(descriptor_->field(i))
788                     .GenerateConstructorCode(printer);
789  }
790
791  printer->Print(
792    "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
793
794  printer->Outdent();
795  printer->Print("}\n\n");
796}
797
798void MessageGenerator::
799GenerateSharedDestructorCode(io::Printer* printer) {
800  printer->Print(
801    "void $classname$::SharedDtor() {\n",
802    "classname", classname_);
803  printer->Indent();
804  // Write the destructors for each field.
805  for (int i = 0; i < descriptor_->field_count(); i++) {
806    field_generators_.get(descriptor_->field(i))
807                     .GenerateDestructorCode(printer);
808  }
809
810  printer->Print(
811    "if (this != default_instance_) {\n");
812
813  // We need to delete all embedded messages.
814  // TODO(kenton):  If we make unset messages point at default instances
815  //   instead of NULL, then it would make sense to move this code into
816  //   MessageFieldGenerator::GenerateDestructorCode().
817  for (int i = 0; i < descriptor_->field_count(); i++) {
818    const FieldDescriptor* field = descriptor_->field(i);
819
820    if (!field->is_repeated() &&
821        field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
822      printer->Print("  delete $name$_;\n",
823                     "name", FieldName(field));
824    }
825  }
826
827  printer->Outdent();
828  printer->Print(
829    "  }\n"
830    "}\n"
831    "\n");
832}
833
834void MessageGenerator::
835GenerateStructors(io::Printer* printer) {
836  // Generate the default constructor.
837  printer->Print(
838    "$classname$::$classname$() {\n"
839    "  SharedCtor();\n"
840    "}\n",
841    "classname", classname_);
842
843  printer->Print(
844    "\n"
845    "void $classname$::InitAsDefaultInstance() {\n",
846    "classname", classname_);
847
848  // The default instance needs all of its embedded message pointers
849  // cross-linked to other default instances.  We can't do this initialization
850  // in the constructor because some other default instances may not have been
851  // constructed yet at that time.
852  // TODO(kenton):  Maybe all message fields (even for non-default messages)
853  //   should be initialized to point at default instances rather than NULL?
854  for (int i = 0; i < descriptor_->field_count(); i++) {
855    const FieldDescriptor* field = descriptor_->field(i);
856
857    if (!field->is_repeated() &&
858        field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
859      printer->Print(
860          "  $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
861          "name", FieldName(field),
862          "type", ClassName(field->message_type(), true));
863    }
864  }
865  printer->Print(
866    "}\n"
867    "\n");
868
869  // Generate the copy constructor.
870  printer->Print(
871    "$classname$::$classname$(const $classname$& from) {\n"
872    "  SharedCtor();\n"
873    "  MergeFrom(from);\n"
874    "}\n"
875    "\n",
876    "classname", classname_);
877
878  // Generate the shared constructor code.
879  GenerateSharedConstructorCode(printer);
880
881  // Generate the destructor.
882  printer->Print(
883    "$classname$::~$classname$() {\n"
884    "  SharedDtor();\n"
885    "}\n"
886    "\n",
887    "classname", classname_);
888
889  // Generate the shared destructor code.
890  GenerateSharedDestructorCode(printer);
891
892  // Only generate this member if it's not disabled.
893  if (HasDescriptorMethods(descriptor_->file()) &&
894      !descriptor_->options().no_standard_descriptor_accessor()) {
895    printer->Print(
896      "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
897      "  protobuf_AssignDescriptorsOnce();\n"
898      "  return $classname$_descriptor_;\n"
899      "}\n"
900      "\n",
901      "classname", classname_,
902      "adddescriptorsname",
903      GlobalAddDescriptorsName(descriptor_->file()->name()));
904  }
905
906  printer->Print(
907    "const $classname$& $classname$::default_instance() {\n"
908    "  if (default_instance_ == NULL) $adddescriptorsname$();"
909    "  return *default_instance_;\n"
910    "}\n"
911    "\n"
912    "$classname$* $classname$::default_instance_ = NULL;\n"
913    "\n"
914    "$classname$* $classname$::New() const {\n"
915    "  return new $classname$;\n"
916    "}\n",
917    "classname", classname_,
918    "adddescriptorsname",
919    GlobalAddDescriptorsName(descriptor_->file()->name()));
920}
921
922void MessageGenerator::
923GenerateClear(io::Printer* printer) {
924  printer->Print("void $classname$::Clear() {\n",
925                 "classname", classname_);
926  printer->Indent();
927
928  int last_index = -1;
929
930  if (descriptor_->extension_range_count() > 0) {
931    printer->Print("_extensions_.Clear();\n");
932  }
933
934  for (int i = 0; i < descriptor_->field_count(); i++) {
935    const FieldDescriptor* field = descriptor_->field(i);
936
937    if (!field->is_repeated()) {
938      map<string, string> vars;
939      vars["index"] = SimpleItoa(field->index());
940
941      // We can use the fact that _has_bits_ is a giant bitfield to our
942      // advantage:  We can check up to 32 bits at a time for equality to
943      // zero, and skip the whole range if so.  This can improve the speed
944      // of Clear() for messages which contain a very large number of
945      // optional fields of which only a few are used at a time.  Here,
946      // we've chosen to check 8 bits at a time rather than 32.
947      if (i / 8 != last_index / 8 || last_index < 0) {
948        if (last_index >= 0) {
949          printer->Outdent();
950          printer->Print("}\n");
951        }
952        printer->Print(vars,
953          "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n");
954        printer->Indent();
955      }
956      last_index = i;
957
958      // It's faster to just overwrite primitive types, but we should
959      // only clear strings and messages if they were set.
960      // TODO(kenton):  Let the CppFieldGenerator decide this somehow.
961      bool should_check_bit =
962        field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
963        field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
964
965      if (should_check_bit) {
966        printer->Print(vars, "if (_has_bit($index$)) {\n");
967        printer->Indent();
968      }
969
970      field_generators_.get(field).GenerateClearingCode(printer);
971
972      if (should_check_bit) {
973        printer->Outdent();
974        printer->Print("}\n");
975      }
976    }
977  }
978
979  if (last_index >= 0) {
980    printer->Outdent();
981    printer->Print("}\n");
982  }
983
984  // Repeated fields don't use _has_bits_ so we clear them in a separate
985  // pass.
986  for (int i = 0; i < descriptor_->field_count(); i++) {
987    const FieldDescriptor* field = descriptor_->field(i);
988
989    if (field->is_repeated()) {
990      field_generators_.get(field).GenerateClearingCode(printer);
991    }
992  }
993
994  printer->Print(
995    "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
996
997  if (HasUnknownFields(descriptor_->file())) {
998    printer->Print(
999      "mutable_unknown_fields()->Clear();\n");
1000  }
1001
1002  printer->Outdent();
1003  printer->Print("}\n");
1004}
1005
1006void MessageGenerator::
1007GenerateSwap(io::Printer* printer) {
1008  // Generate the Swap member function.
1009  printer->Print("void $classname$::Swap($classname$* other) {\n",
1010                 "classname", classname_);
1011  printer->Indent();
1012  printer->Print("if (other != this) {\n");
1013  printer->Indent();
1014
1015  if (HasGeneratedMethods(descriptor_->file())) {
1016    for (int i = 0; i < descriptor_->field_count(); i++) {
1017      const FieldDescriptor* field = descriptor_->field(i);
1018      field_generators_.get(field).GenerateSwappingCode(printer);
1019    }
1020
1021    for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
1022      printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
1023                     "i", SimpleItoa(i));
1024    }
1025
1026    if (HasUnknownFields(descriptor_->file())) {
1027      printer->Print("_unknown_fields_.Swap(&other->_unknown_fields_);\n");
1028    }
1029    printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
1030    if (descriptor_->extension_range_count() > 0) {
1031      printer->Print("_extensions_.Swap(&other->_extensions_);\n");
1032    }
1033  } else {
1034    printer->Print("GetReflection()->Swap(this, other);");
1035  }
1036
1037  printer->Outdent();
1038  printer->Print("}\n");
1039  printer->Outdent();
1040  printer->Print("}\n");
1041}
1042
1043void MessageGenerator::
1044GenerateMergeFrom(io::Printer* printer) {
1045  if (HasDescriptorMethods(descriptor_->file())) {
1046    // Generate the generalized MergeFrom (aka that which takes in the Message
1047    // base class as a parameter).
1048    printer->Print(
1049      "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
1050      "  GOOGLE_CHECK_NE(&from, this);\n",
1051      "classname", classname_);
1052    printer->Indent();
1053
1054    // Cast the message to the proper type. If we find that the message is
1055    // *not* of the proper type, we can still call Merge via the reflection
1056    // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
1057    // for each message.
1058    printer->Print(
1059      "const $classname$* source =\n"
1060      "  ::google::protobuf::internal::dynamic_cast_if_available<const $classname$*>(\n"
1061      "    &from);\n"
1062      "if (source == NULL) {\n"
1063      "  ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
1064      "} else {\n"
1065      "  MergeFrom(*source);\n"
1066      "}\n",
1067      "classname", classname_);
1068
1069    printer->Outdent();
1070    printer->Print("}\n\n");
1071  } else {
1072    // Generate CheckTypeAndMergeFrom().
1073    printer->Print(
1074      "void $classname$::CheckTypeAndMergeFrom(\n"
1075      "    const ::google::protobuf::MessageLite& from) {\n"
1076      "  MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
1077      "}\n"
1078      "\n",
1079      "classname", classname_);
1080  }
1081
1082  // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
1083  printer->Print(
1084    "void $classname$::MergeFrom(const $classname$& from) {\n"
1085    "  GOOGLE_CHECK_NE(&from, this);\n",
1086    "classname", classname_);
1087  printer->Indent();
1088
1089  // Merge Repeated fields. These fields do not require a
1090  // check as we can simply iterate over them.
1091  for (int i = 0; i < descriptor_->field_count(); ++i) {
1092    const FieldDescriptor* field = descriptor_->field(i);
1093
1094    if (field->is_repeated()) {
1095      field_generators_.get(field).GenerateMergingCode(printer);
1096    }
1097  }
1098
1099  // Merge Optional and Required fields (after a _has_bit check).
1100  int last_index = -1;
1101
1102  for (int i = 0; i < descriptor_->field_count(); ++i) {
1103    const FieldDescriptor* field = descriptor_->field(i);
1104
1105    if (!field->is_repeated()) {
1106      map<string, string> vars;
1107      vars["index"] = SimpleItoa(field->index());
1108
1109      // See above in GenerateClear for an explanation of this.
1110      if (i / 8 != last_index / 8 || last_index < 0) {
1111        if (last_index >= 0) {
1112          printer->Outdent();
1113          printer->Print("}\n");
1114        }
1115        printer->Print(vars,
1116          "if (from._has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n");
1117        printer->Indent();
1118      }
1119
1120      last_index = i;
1121
1122      printer->Print(vars,
1123        "if (from._has_bit($index$)) {\n");
1124      printer->Indent();
1125
1126      field_generators_.get(field).GenerateMergingCode(printer);
1127
1128      printer->Outdent();
1129      printer->Print("}\n");
1130    }
1131  }
1132
1133  if (last_index >= 0) {
1134    printer->Outdent();
1135    printer->Print("}\n");
1136  }
1137
1138  if (descriptor_->extension_range_count() > 0) {
1139    printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
1140  }
1141
1142  if (HasUnknownFields(descriptor_->file())) {
1143    printer->Print(
1144      "mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n");
1145  }
1146
1147  printer->Outdent();
1148  printer->Print("}\n");
1149}
1150
1151void MessageGenerator::
1152GenerateCopyFrom(io::Printer* printer) {
1153  if (HasDescriptorMethods(descriptor_->file())) {
1154    // Generate the generalized CopyFrom (aka that which takes in the Message
1155    // base class as a parameter).
1156    printer->Print(
1157      "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n",
1158      "classname", classname_);
1159    printer->Indent();
1160
1161    printer->Print(
1162      "if (&from == this) return;\n"
1163      "Clear();\n"
1164      "MergeFrom(from);\n");
1165
1166    printer->Outdent();
1167    printer->Print("}\n\n");
1168  }
1169
1170  // Generate the class-specific CopyFrom.
1171  printer->Print(
1172    "void $classname$::CopyFrom(const $classname$& from) {\n",
1173    "classname", classname_);
1174  printer->Indent();
1175
1176  printer->Print(
1177    "if (&from == this) return;\n"
1178    "Clear();\n"
1179    "MergeFrom(from);\n");
1180
1181  printer->Outdent();
1182  printer->Print("}\n");
1183}
1184
1185void MessageGenerator::
1186GenerateMergeFromCodedStream(io::Printer* printer) {
1187  if (descriptor_->options().message_set_wire_format()) {
1188    // Special-case MessageSet.
1189    printer->Print(
1190      "bool $classname$::MergePartialFromCodedStream(\n"
1191      "    ::google::protobuf::io::CodedInputStream* input) {\n"
1192      "  return _extensions_.ParseMessageSet(input, default_instance_,\n"
1193      "                                      mutable_unknown_fields());\n"
1194      "}\n",
1195      "classname", classname_);
1196    return;
1197  }
1198
1199  printer->Print(
1200    "bool $classname$::MergePartialFromCodedStream(\n"
1201    "    ::google::protobuf::io::CodedInputStream* input) {\n"
1202    "#define DO_(EXPRESSION) if (!(EXPRESSION)) return false\n"
1203    "  ::google::protobuf::uint32 tag;\n"
1204    "  while ((tag = input->ReadTag()) != 0) {\n",
1205    "classname", classname_);
1206
1207  printer->Indent();
1208  printer->Indent();
1209
1210  if (descriptor_->field_count() > 0) {
1211    // We don't even want to print the switch() if we have no fields because
1212    // MSVC dislikes switch() statements that contain only a default value.
1213
1214    // Note:  If we just switched on the tag rather than the field number, we
1215    // could avoid the need for the if() to check the wire type at the beginning
1216    // of each case.  However, this is actually a bit slower in practice as it
1217    // creates a jump table that is 8x larger and sparser, and meanwhile the
1218    // if()s are highly predictable.
1219    printer->Print(
1220      "switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {\n");
1221
1222    printer->Indent();
1223
1224    scoped_array<const FieldDescriptor*> ordered_fields(
1225      SortFieldsByNumber(descriptor_));
1226
1227    for (int i = 0; i < descriptor_->field_count(); i++) {
1228      const FieldDescriptor* field = ordered_fields[i];
1229
1230      PrintFieldComment(printer, field);
1231
1232      printer->Print(
1233        "case $number$: {\n"
1234        "  if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) !=\n"
1235        "      ::google::protobuf::internal::WireFormatLite::WIRETYPE_$wiretype$) {\n"
1236        "    goto handle_uninterpreted;\n"
1237        "  }\n",
1238        "number", SimpleItoa(field->number()),
1239        "wiretype", kWireTypeNames[WireFormat::WireTypeForField(field)]);
1240
1241      if (i > 0 || (field->is_repeated() && !field->options().packed())) {
1242        printer->Print(
1243          " parse_$name$:\n",
1244          "name", field->name());
1245      }
1246
1247      printer->Indent();
1248
1249      field_generators_.get(field).GenerateMergeFromCodedStream(printer);
1250
1251      // switch() is slow since it can't be predicted well.  Insert some if()s
1252      // here that attempt to predict the next tag.
1253      if (field->is_repeated() && !field->options().packed()) {
1254        // Expect repeats of this field.
1255        printer->Print(
1256          "if (input->ExpectTag($tag$)) goto parse_$name$;\n",
1257          "tag", SimpleItoa(WireFormat::MakeTag(field)),
1258          "name", field->name());
1259      }
1260
1261      if (i + 1 < descriptor_->field_count()) {
1262        // Expect the next field in order.
1263        const FieldDescriptor* next_field = ordered_fields[i + 1];
1264        printer->Print(
1265          "if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
1266          "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
1267          "next_name", next_field->name());
1268      } else {
1269        // Expect EOF.
1270        // TODO(kenton):  Expect group end-tag?
1271        printer->Print(
1272          "if (input->ExpectAtEnd()) return true;\n");
1273      }
1274
1275      printer->Print(
1276        "break;\n");
1277
1278      printer->Outdent();
1279      printer->Print("}\n\n");
1280    }
1281
1282    printer->Print(
1283      "default: {\n"
1284      "handle_uninterpreted:\n");
1285    printer->Indent();
1286  }
1287
1288  // Is this an end-group tag?  If so, this must be the end of the message.
1289  printer->Print(
1290    "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
1291    "    ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
1292    "  return true;\n"
1293    "}\n");
1294
1295  // Handle extension ranges.
1296  if (descriptor_->extension_range_count() > 0) {
1297    printer->Print(
1298      "if (");
1299    for (int i = 0; i < descriptor_->extension_range_count(); i++) {
1300      const Descriptor::ExtensionRange* range =
1301        descriptor_->extension_range(i);
1302      if (i > 0) printer->Print(" ||\n    ");
1303
1304      uint32 start_tag = WireFormatLite::MakeTag(
1305        range->start, static_cast<WireFormatLite::WireType>(0));
1306      uint32 end_tag = WireFormatLite::MakeTag(
1307        range->end, static_cast<WireFormatLite::WireType>(0));
1308
1309      if (range->end > FieldDescriptor::kMaxNumber) {
1310        printer->Print(
1311          "($start$u <= tag)",
1312          "start", SimpleItoa(start_tag));
1313      } else {
1314        printer->Print(
1315          "($start$u <= tag && tag < $end$u)",
1316          "start", SimpleItoa(start_tag),
1317          "end", SimpleItoa(end_tag));
1318      }
1319    }
1320    printer->Print(") {\n");
1321    if (HasUnknownFields(descriptor_->file())) {
1322      printer->Print(
1323        "  DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
1324        "                              mutable_unknown_fields()));\n");
1325    } else {
1326      printer->Print(
1327        "  DO_(_extensions_.ParseField(tag, input, default_instance_));\n");
1328    }
1329    printer->Print(
1330      "  continue;\n"
1331      "}\n");
1332  }
1333
1334  // We really don't recognize this tag.  Skip it.
1335  if (HasUnknownFields(descriptor_->file())) {
1336    printer->Print(
1337      "DO_(::google::protobuf::internal::WireFormat::SkipField(\n"
1338      "      input, tag, mutable_unknown_fields()));\n");
1339  } else {
1340    printer->Print(
1341      "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));\n");
1342  }
1343
1344  if (descriptor_->field_count() > 0) {
1345    printer->Print("break;\n");
1346    printer->Outdent();
1347    printer->Print("}\n");    // default:
1348    printer->Outdent();
1349    printer->Print("}\n");    // switch
1350  }
1351
1352  printer->Outdent();
1353  printer->Outdent();
1354  printer->Print(
1355    "  }\n"                   // while
1356    "  return true;\n"
1357    "#undef DO_\n"
1358    "}\n");
1359}
1360
1361void MessageGenerator::GenerateSerializeOneField(
1362    io::Printer* printer, const FieldDescriptor* field, bool to_array) {
1363  PrintFieldComment(printer, field);
1364
1365  if (!field->is_repeated()) {
1366    printer->Print(
1367      "if (_has_bit($index$)) {\n",
1368      "index", SimpleItoa(field->index()));
1369    printer->Indent();
1370  }
1371
1372  if (to_array) {
1373    field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
1374        printer);
1375  } else {
1376    field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
1377  }
1378
1379  if (!field->is_repeated()) {
1380    printer->Outdent();
1381    printer->Print("}\n");
1382  }
1383  printer->Print("\n");
1384}
1385
1386void MessageGenerator::GenerateSerializeOneExtensionRange(
1387    io::Printer* printer, const Descriptor::ExtensionRange* range,
1388    bool to_array) {
1389  map<string, string> vars;
1390  vars["start"] = SimpleItoa(range->start);
1391  vars["end"] = SimpleItoa(range->end);
1392  printer->Print(vars,
1393    "// Extension range [$start$, $end$)\n");
1394  if (to_array) {
1395    printer->Print(vars,
1396      "target = _extensions_.SerializeWithCachedSizesToArray(\n"
1397      "    $start$, $end$, target);\n\n");
1398  } else {
1399    printer->Print(vars,
1400      "_extensions_.SerializeWithCachedSizes(\n"
1401      "    $start$, $end$, output);\n\n");
1402  }
1403}
1404
1405void MessageGenerator::
1406GenerateSerializeWithCachedSizes(io::Printer* printer) {
1407  if (descriptor_->options().message_set_wire_format()) {
1408    // Special-case MessageSet.
1409    printer->Print(
1410      "void $classname$::SerializeWithCachedSizes(\n"
1411      "    ::google::protobuf::io::CodedOutputStream* output) const {\n"
1412      "  _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
1413      "classname", classname_);
1414    if (HasUnknownFields(descriptor_->file())) {
1415      printer->Print(
1416        "  ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n"
1417        "      unknown_fields(), output);\n");
1418    }
1419    printer->Print(
1420      "}\n");
1421    return;
1422  }
1423
1424  printer->Print(
1425    "void $classname$::SerializeWithCachedSizes(\n"
1426    "    ::google::protobuf::io::CodedOutputStream* output) const {\n",
1427    "classname", classname_);
1428  printer->Indent();
1429
1430  if (HasFastArraySerialization(descriptor_->file())) {
1431    printer->Print(
1432      "::google::protobuf::uint8* raw_buffer = "
1433        "output->GetDirectBufferForNBytesAndAdvance(_cached_size_);\n"
1434      "if (raw_buffer != NULL) {\n"
1435      "  $classname$::SerializeWithCachedSizesToArray(raw_buffer);\n"
1436      "  return;\n"
1437      "}\n"
1438      "\n",
1439      "classname", classname_);
1440  }
1441
1442  GenerateSerializeWithCachedSizesBody(printer, false);
1443
1444  printer->Outdent();
1445  printer->Print(
1446    "}\n");
1447}
1448
1449void MessageGenerator::
1450GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
1451  if (descriptor_->options().message_set_wire_format()) {
1452    // Special-case MessageSet.
1453    printer->Print(
1454      "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
1455      "    ::google::protobuf::uint8* target) const {\n"
1456      "  target =\n"
1457      "      _extensions_.SerializeMessageSetWithCachedSizesToArray(target);\n",
1458      "classname", classname_);
1459    if (HasUnknownFields(descriptor_->file())) {
1460      printer->Print(
1461        "  target = ::google::protobuf::internal::WireFormat::\n"
1462        "             SerializeUnknownMessageSetItemsToArray(\n"
1463        "               unknown_fields(), target);\n");
1464    }
1465    printer->Print(
1466      "  return target;\n"
1467      "}\n");
1468    return;
1469  }
1470
1471  printer->Print(
1472    "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
1473    "    ::google::protobuf::uint8* target) const {\n",
1474    "classname", classname_);
1475  printer->Indent();
1476
1477  GenerateSerializeWithCachedSizesBody(printer, true);
1478
1479  printer->Outdent();
1480  printer->Print(
1481    "  return target;\n"
1482    "}\n");
1483}
1484
1485void MessageGenerator::
1486GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
1487  scoped_array<const FieldDescriptor*> ordered_fields(
1488    SortFieldsByNumber(descriptor_));
1489
1490  vector<const Descriptor::ExtensionRange*> sorted_extensions;
1491  for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
1492    sorted_extensions.push_back(descriptor_->extension_range(i));
1493  }
1494  sort(sorted_extensions.begin(), sorted_extensions.end(),
1495       ExtensionRangeSorter());
1496
1497  // Merge the fields and the extension ranges, both sorted by field number.
1498  int i, j;
1499  for (i = 0, j = 0;
1500       i < descriptor_->field_count() || j < sorted_extensions.size();
1501       ) {
1502    if (i == descriptor_->field_count()) {
1503      GenerateSerializeOneExtensionRange(printer,
1504                                         sorted_extensions[j++],
1505                                         to_array);
1506    } else if (j == sorted_extensions.size()) {
1507      GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
1508    } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
1509      GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
1510    } else {
1511      GenerateSerializeOneExtensionRange(printer,
1512                                         sorted_extensions[j++],
1513                                         to_array);
1514    }
1515  }
1516
1517  if (HasUnknownFields(descriptor_->file())) {
1518    printer->Print("if (!unknown_fields().empty()) {\n");
1519    printer->Indent();
1520    if (to_array) {
1521      printer->Print(
1522        "target = "
1523            "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
1524        "    unknown_fields(), target);\n");
1525    } else {
1526      printer->Print(
1527        "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
1528        "    unknown_fields(), output);\n");
1529    }
1530    printer->Outdent();
1531
1532    printer->Print(
1533      "}\n");
1534  }
1535}
1536
1537void MessageGenerator::
1538GenerateByteSize(io::Printer* printer) {
1539  if (descriptor_->options().message_set_wire_format()) {
1540    // Special-case MessageSet.
1541    printer->Print(
1542      "int $classname$::ByteSize() const {\n"
1543      "  int total_size = _extensions_.MessageSetByteSize();\n",
1544      "classname", classname_);
1545    if (HasUnknownFields(descriptor_->file())) {
1546      printer->Print(
1547        "  total_size += ::google::protobuf::internal::WireFormat::\n"
1548        "      ComputeUnknownMessageSetItemsSize(unknown_fields());\n");
1549    }
1550    printer->Print(
1551      "  _cached_size_ = total_size;\n"
1552      "  return total_size;\n"
1553      "}\n");
1554    return;
1555  }
1556
1557  printer->Print(
1558    "int $classname$::ByteSize() const {\n",
1559    "classname", classname_);
1560  printer->Indent();
1561  printer->Print(
1562    "int total_size = 0;\n"
1563    "\n");
1564
1565  int last_index = -1;
1566
1567  for (int i = 0; i < descriptor_->field_count(); i++) {
1568    const FieldDescriptor* field = descriptor_->field(i);
1569
1570    if (!field->is_repeated()) {
1571      // See above in GenerateClear for an explanation of this.
1572      // TODO(kenton):  Share code?  Unclear how to do so without
1573      //   over-engineering.
1574      if ((i / 8) != (last_index / 8) ||
1575          last_index < 0) {
1576        if (last_index >= 0) {
1577          printer->Outdent();
1578          printer->Print("}\n");
1579        }
1580        printer->Print(
1581          "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
1582          "index", SimpleItoa(field->index()));
1583        printer->Indent();
1584      }
1585      last_index = i;
1586
1587      PrintFieldComment(printer, field);
1588
1589      printer->Print(
1590        "if (has_$name$()) {\n",
1591        "name", FieldName(field));
1592      printer->Indent();
1593
1594      field_generators_.get(field).GenerateByteSize(printer);
1595
1596      printer->Outdent();
1597      printer->Print(
1598        "}\n"
1599        "\n");
1600    }
1601  }
1602
1603  if (last_index >= 0) {
1604    printer->Outdent();
1605    printer->Print("}\n");
1606  }
1607
1608  // Repeated fields don't use _has_bits_ so we count them in a separate
1609  // pass.
1610  for (int i = 0; i < descriptor_->field_count(); i++) {
1611    const FieldDescriptor* field = descriptor_->field(i);
1612
1613    if (field->is_repeated()) {
1614      PrintFieldComment(printer, field);
1615      field_generators_.get(field).GenerateByteSize(printer);
1616      printer->Print("\n");
1617    }
1618  }
1619
1620  if (descriptor_->extension_range_count() > 0) {
1621    printer->Print(
1622      "total_size += _extensions_.ByteSize();\n"
1623      "\n");
1624  }
1625
1626  if (HasUnknownFields(descriptor_->file())) {
1627    printer->Print("if (!unknown_fields().empty()) {\n");
1628    printer->Indent();
1629    printer->Print(
1630      "total_size +=\n"
1631      "  ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n"
1632      "    unknown_fields());\n");
1633    printer->Outdent();
1634    printer->Print("}\n");
1635  }
1636
1637  // We update _cached_size_ even though this is a const method.  In theory,
1638  // this is not thread-compatible, because concurrent writes have undefined
1639  // results.  In practice, since any concurrent writes will be writing the
1640  // exact same value, it works on all common processors.  In a future version
1641  // of C++, _cached_size_ should be made into an atomic<int>.
1642  printer->Print(
1643    "_cached_size_ = total_size;\n"
1644    "return total_size;\n");
1645
1646  printer->Outdent();
1647  printer->Print("}\n");
1648}
1649
1650void MessageGenerator::
1651GenerateIsInitialized(io::Printer* printer) {
1652  printer->Print(
1653    "bool $classname$::IsInitialized() const {\n",
1654    "classname", classname_);
1655  printer->Indent();
1656
1657  // Check that all required fields in this message are set.  We can do this
1658  // most efficiently by checking 32 "has bits" at a time.
1659  int has_bits_array_size = (descriptor_->field_count() + 31) / 32;
1660  for (int i = 0; i < has_bits_array_size; i++) {
1661    uint32 mask = 0;
1662    for (int bit = 0; bit < 32; bit++) {
1663      int index = i * 32 + bit;
1664      if (index >= descriptor_->field_count()) break;
1665      const FieldDescriptor* field = descriptor_->field(index);
1666
1667      if (field->is_required()) {
1668        mask |= 1 << bit;
1669      }
1670    }
1671
1672    if (mask != 0) {
1673      char buffer[kFastToBufferSize];
1674      printer->Print(
1675        "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n",
1676        "i", SimpleItoa(i),
1677        "mask", FastHex32ToBuffer(mask, buffer));
1678    }
1679  }
1680
1681  // Now check that all embedded messages are initialized.
1682  printer->Print("\n");
1683  for (int i = 0; i < descriptor_->field_count(); i++) {
1684    const FieldDescriptor* field = descriptor_->field(i);
1685    if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
1686        HasRequiredFields(field->message_type())) {
1687      if (field->is_repeated()) {
1688        printer->Print(
1689          "for (int i = 0; i < $name$_size(); i++) {\n"
1690          "  if (!this->$name$(i).IsInitialized()) return false;\n"
1691          "}\n",
1692          "name", FieldName(field));
1693      } else {
1694        printer->Print(
1695          "if (has_$name$()) {\n"
1696          "  if (!this->$name$().IsInitialized()) return false;\n"
1697          "}\n",
1698          "name", FieldName(field));
1699      }
1700    }
1701  }
1702
1703  if (descriptor_->extension_range_count() > 0) {
1704    printer->Print(
1705      "\n"
1706      "if (!_extensions_.IsInitialized()) return false;");
1707  }
1708
1709  printer->Outdent();
1710  printer->Print(
1711    "  return true;\n"
1712    "}\n");
1713}
1714
1715}  // namespace cpp
1716}  // namespace compiler
1717}  // namespace protobuf
1718}  // namespace google
1719