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