-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlua_message.cpp
1861 lines (1599 loc) · 66 KB
/
lua_message.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <map>
#include <utility>
#include <vector>
#include <google/protobuf/stubs/hash.h>
#include "lua_message.h"
#include "lua_field.h"
#include "lua_enum.h"
#include "lua_extension.h"
#include "lua_helpers.h"
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/descriptor.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace mwpb_lua {
using internal::WireFormat;
using internal::WireFormatLite;
namespace {
void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) {
// Print the field's proto-syntax definition as a comment. We don't want to
// print group bodies so we cut off after the first line.
string def = field->DebugString();
printer->Print("--// $def$\n",
"def", def.substr(0, def.find_first_of('\n')));
}
struct FieldOrderingByNumber {
inline bool operator()(const FieldDescriptor* a,
const FieldDescriptor* b) const {
return a->number() < b->number();
}
};
const char* kWireTypeNames[] = {
"VARINT",
"FIXED64",
"LENGTH_DELIMITED",
"START_GROUP",
"END_GROUP",
"FIXED32",
};
// Sort the fields of the given Descriptor by number into a new[]'d array
// and return it.
const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
const FieldDescriptor** fields =
new const FieldDescriptor*[descriptor->field_count()];
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
sort(fields, fields + descriptor->field_count(),
FieldOrderingByNumber());
return fields;
}
// Functor for sorting extension ranges by their "start" field number.
struct ExtensionRangeSorter {
bool operator()(const Descriptor::ExtensionRange* left,
const Descriptor::ExtensionRange* right) const {
return left->start < right->start;
}
};
// Returns true if the "required" restriction check should be ignored for the
// given field.
inline static bool ShouldIgnoreRequiredFieldCheck(
const FieldDescriptor* field) {
return false;
}
// Returns true if the message type has any required fields. If it doesn't,
// we can optimize out calls to its IsInitialized() method.
//
// already_seen is used to avoid checking the same type multiple times
// (and also to protect against recursion).
static bool HasRequiredFields(
const Descriptor* type,
hash_set<const Descriptor*>* already_seen) {
if (already_seen->count(type) > 0) {
// Since the first occurrence of a required field causes the whole
// function to return true, we can assume that if the type is already
// in the cache it didn't have any required fields.
return false;
}
already_seen->insert(type);
// If the type has extensions, an extension with message type could contain
// required fields, so we have to be conservative and assume such an
// extension exists.
if (type->extension_range_count() > 0) return true;
for (int i = 0; i < type->field_count(); i++) {
const FieldDescriptor* field = type->field(i);
if (field->is_required()) {
return true;
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field)) {
if (HasRequiredFields(field->message_type(), already_seen)) {
return true;
}
}
}
return false;
}
static bool HasRequiredFields(const Descriptor* type) {
hash_set<const Descriptor*> already_seen;
return HasRequiredFields(type, &already_seen);
}
// This returns an estimate of the compiler's alignment for the field. This
// can't guarantee to be correct because the generated code could be compiled on
// different systems with different alignment rules. The estimates below assume
// 64-bit pointers.
int EstimateAlignmentSize(const FieldDescriptor* field) {
if (field == NULL) return 0;
if (field->is_repeated()) return 8;
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_BOOL:
return 1;
case FieldDescriptor::CPPTYPE_INT32:
case FieldDescriptor::CPPTYPE_UINT32:
case FieldDescriptor::CPPTYPE_ENUM:
case FieldDescriptor::CPPTYPE_FLOAT:
return 4;
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT64:
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_STRING:
case FieldDescriptor::CPPTYPE_MESSAGE:
return 8;
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return -1; // Make compiler happy.
}
// FieldGroup is just a helper for OptimizePadding below. It holds a vector of
// fields that are grouped together because they have compatible alignment, and
// a preferred location in the final field ordering.
class FieldGroup {
public:
FieldGroup()
: preferred_location_(0) {}
// A group with a single field.
FieldGroup(float preferred_location, const FieldDescriptor* field)
: preferred_location_(preferred_location),
fields_(1, field) {}
// Append the fields in 'other' to this group.
void Append(const FieldGroup& other) {
if (other.fields_.empty()) {
return;
}
// Preferred location is the average among all the fields, so we weight by
// the number of fields on each FieldGroup object.
preferred_location_ =
(preferred_location_ * fields_.size() +
(other.preferred_location_ * other.fields_.size())) /
(fields_.size() + other.fields_.size());
fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
}
void SetPreferredLocation(float location) { preferred_location_ = location; }
const vector<const FieldDescriptor*>& fields() const { return fields_; }
// FieldGroup objects sort by their preferred location.
bool operator<(const FieldGroup& other) const {
return preferred_location_ < other.preferred_location_;
}
private:
// "preferred_location_" is an estimate of where this group should go in the
// final list of fields. We compute this by taking the average index of each
// field in this group in the original ordering of fields. This is very
// approximate, but should put this group close to where its member fields
// originally went.
float preferred_location_;
vector<const FieldDescriptor*> fields_;
// We rely on the default copy constructor and operator= so this type can be
// used in a vector.
};
// Reorder 'fields' so that if the fields are output into a c++ class in the new
// order, the alignment padding is minimized. We try to do this while keeping
// each field as close as possible to its original position so that we don't
// reduce cache locality much for function that access each field in order.
void OptimizePadding(vector<const FieldDescriptor*>* fields) {
// First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
vector<FieldGroup> aligned_to_1, aligned_to_4, aligned_to_8;
for (int i = 0; i < fields->size(); ++i) {
switch (EstimateAlignmentSize((*fields)[i])) {
case 1: aligned_to_1.push_back(FieldGroup(i, (*fields)[i])); break;
case 4: aligned_to_4.push_back(FieldGroup(i, (*fields)[i])); break;
case 8: aligned_to_8.push_back(FieldGroup(i, (*fields)[i])); break;
default:
GOOGLE_LOG(FATAL) << "Unknown alignment size.";
}
}
// Now group fields aligned to 1 byte into sets of 4, and treat those like a
// single field aligned to 4 bytes.
for (int i = 0; i < aligned_to_1.size(); i += 4) {
FieldGroup field_group;
for (int j = i; j < aligned_to_1.size() && j < i + 4; ++j) {
field_group.Append(aligned_to_1[j]);
}
aligned_to_4.push_back(field_group);
}
// Sort by preferred location to keep fields as close to their original
// location as possible.
sort(aligned_to_4.begin(), aligned_to_4.end());
// Now group fields aligned to 4 bytes (or the 4-field groups created above)
// into pairs, and treat those like a single field aligned to 8 bytes.
for (int i = 0; i < aligned_to_4.size(); i += 2) {
FieldGroup field_group;
for (int j = i; j < aligned_to_4.size() && j < i + 2; ++j) {
field_group.Append(aligned_to_4[j]);
}
if (i == aligned_to_4.size() - 1) {
// Move incomplete 4-byte block to the end.
field_group.SetPreferredLocation(fields->size() + 1);
}
aligned_to_8.push_back(field_group);
}
// Sort by preferred location to keep fields as close to their original
// location as possible.
sort(aligned_to_8.begin(), aligned_to_8.end());
// Now pull out all the FieldDescriptors in order.
fields->clear();
for (int i = 0; i < aligned_to_8.size(); ++i) {
fields->insert(fields->end(),
aligned_to_8[i].fields().begin(),
aligned_to_8[i].fields().end());
}
}
}
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
classname_(ClassName(descriptor, false)),
options_(options),
field_generators_(descriptor, options),
nested_generators_(new scoped_ptr<MessageGenerator>[
descriptor->nested_type_count()]),
enum_generators_(new scoped_ptr<EnumGenerator>[
descriptor->enum_type_count()]),
extension_generators_(new scoped_ptr<ExtensionGenerator>[
descriptor->extension_count()]) {
for (int i = 0; i < descriptor->nested_type_count(); i++) {
nested_generators_[i].reset(
new MessageGenerator(descriptor->nested_type(i), options));
}
for (int i = 0; i < descriptor->enum_type_count(); i++) {
enum_generators_[i].reset(
new EnumGenerator(descriptor->enum_type(i), options));
}
for (int i = 0; i < descriptor->extension_count(); i++) {
extension_generators_[i].reset(
new ExtensionGenerator(descriptor->extension(i), options));
}
}
MessageGenerator::~MessageGenerator() {}
void MessageGenerator::
GenerateForwardDeclaration(io::Printer* printer) {
printer->Print("class $classname$;\n",
"classname", classname_);
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateForwardDeclaration(printer);
}
}
void MessageGenerator::
GenerateEnumDefinitions(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateEnumDefinitions(printer);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDefinition(printer);
}
}
void MessageGenerator::
GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
}
}
void MessageGenerator::
GenerateFieldAccessorDeclarations(io::Printer* printer) {
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
PrintFieldComment(printer, field);
map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
vars["constant_name"] = FieldConstantName(field);
if (field->is_repeated()) {
//printer->Print(vars, "inline int $name$_size() const$deprecation$;\n");
printer->Print(vars, "$classname$.$name$_size = function()\n");
printer->Indent();
printer->Print(vars, "return table.getn($classname$_Member.$name$_)\n");
printer->Outdent();
printer->Print("end\n\n");
} else {
//printer->Print(vars, "inline bool has_$name$() const$deprecation$;\n");
printer->Print(vars, "$classname$.has_$name$ = function()\n");
printer->Indent();
printer->Print(vars, "return $classname$_Temp.$name$_\n");
printer->Outdent();
printer->Print("end\n\n");
}
//printer->Print(vars, "inline void clear_$name$()$deprecation$;\n");
//printer->Print(vars, "static const int $constant_name$ = $number$;\n");
printer->Print(vars, "$classname$.clear_$name$ = function()\n");
printer->Indent();
printer->Print(vars, "$classname$_Temp.$name$_=false\n");
printer->Outdent();
printer->Print("end\n\n");
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateAccessorDeclarations(printer);
printer->Print("\n");
}
// if (descriptor_->extension_range_count() > 0) {
// // Generate accessors for extensions. We just call a macro located in
// // extension_set.h since the accessors about 80 lines of static code.
// printer->Print(
// "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
// "classname", classname_);
// }
}
void MessageGenerator::
GenerateFieldAccessorDefinitions(io::Printer* printer) {
printer->Print("// $classname$\n\n", "classname", classname_);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
PrintFieldComment(printer, field);
map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
printer->Print(vars,
"inline int $classname$::$name$_size() const {\n"
" return $name$_.size();\n"
"}\n");
} else {
// Singular field.
char buffer[kFastToBufferSize];
vars["has_array_index"] = SimpleItoa(field->index() / 32);
vars["has_mask"] = FastHex32ToBuffer(1u << (field->index() % 32), buffer);
printer->Print(vars,
"inline bool $classname$::has_$name$() const {\n"
" return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
"}\n"
"inline void $classname$::set_has_$name$() {\n"
" _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
"}\n"
"inline void $classname$::clear_has_$name$() {\n"
" _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
"}\n"
);
}
// Generate clear_$name$()
printer->Print(vars,
"inline void $classname$::clear_$name$() {\n");
printer->Indent();
field_generators_.get(field).GenerateClearingCode(printer);
printer->Outdent();
if (!field->is_repeated()) {
printer->Print(vars,
" clear_has_$name$();\n");
}
printer->Print("}\n");
// Generate type-specific accessors.
field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
printer->Print("\n");
}
}
void MessageGenerator::
GenerateClassDefinition(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateClassDefinition(printer);
printer->Print("\n");
printer->Print(kThinSeparator);
printer->Print("\n");
}
map<string, string> vars;
vars["classname"] = classname_;
vars["field_count"] = SimpleItoa(descriptor_->field_count());
// if (options_.dllexport_decl.empty()) {
// vars["dllexport"] = "";
// } else {
// vars["dllexport"] = options_.dllexport_decl + " ";
// }
// vars["superclass"] = SuperClassName(descriptor_);
//
// printer->Print(vars,
// "class $dllexport$$classname$ : public $superclass$ {\n"
// " public:\n");
// 定义class table;
printer->Print(vars,
"$classname$ = {}\n"
);
printer->Print("\n--private: Field members\n");
// 定义变量;
printer->Print(vars,
"local $classname$_Member = {\n"
);
printer->Indent();
//printer->Print(" private:\n");
// Field members:
vector<const FieldDescriptor*> fields;
for (int i = 0; i < descriptor_->field_count(); i++) {
fields.push_back(descriptor_->field(i));
}
OptimizePadding(&fields);
for (int i = 0; i < fields.size(); ++i) {
field_generators_.get(fields[i]).GeneratePrivateMembers(printer);
}
printer->Outdent();
printer->Print("}\n");
printer->Print("\n\n");
// 打印临时变量,主要保存bool变量,是否被设置过;
printer->Print(vars,
"local $classname$_Temp = {\n"
);
printer->Indent();
//vector<const FieldDescriptor*> fields;
fields.clear();
for (int i = 0; i < descriptor_->field_count(); i++) {
fields.push_back(descriptor_->field(i));
}
OptimizePadding(&fields);
for (int i = 0; i < fields.size(); ++i) {
//field_generators_.get(fields[i]).GeneratePrivateMembers(printer);
string field_name_temp = fields[i]->name();
field_name_temp += "_ = false,\n";
printer->Print(field_name_temp.c_str());
}
printer->Outdent();
printer->Print("}\n");
// 打印方法;
printer->Print(
"--// nested types ----------------------------------------------------\n"
"\n");
// Import all nested message classes into this class's scope with typedefs.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
assert(0);
const Descriptor* nested_type = descriptor_->nested_type(i);
printer->Print("typedef $nested_full_name$ $nested_name$;\n",
"nested_name", nested_type->name(),
"nested_full_name", ClassName(nested_type, false));
}
if (descriptor_->nested_type_count() > 0) {
printer->Print("\n");
}
// Import all nested enums and their values into this class's scope with
// typedefs and constants.
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateSymbolImports(printer);
printer->Print("\n");
}
printer->Print(
"--// accessors -------------------------------------------------------\n"
"\n");
// Generate accessor methods for all fields.
GenerateFieldAccessorDeclarations(printer);
// 生成数据的decode 与 encode .
GenerateMergeFromCodedStream(printer);
printer->Print("\n");
printer->Print("\n");
GenerateSerializeWithCachedSizes(printer);
// // Declare extension identifiers.
// for (int i = 0; i < descriptor_->extension_count(); i++) {
// extension_generators_[i]->GenerateDeclaration(printer);
// }
//
//
// printer->Print(
// "// @@protoc_insertion_point(class_scope:$full_name$)\n",
// "full_name", descriptor_->full_name());
// Generate private members.
// printer->Outdent();
//printer->Print(" private:\n");
//printer->Indent();
//
//
// for (int i = 0; i < descriptor_->field_count(); i++) {
// if (!descriptor_->field(i)->is_repeated()) {
// printer->Print(
// "inline void set_has_$name$();\n",
// "name", FieldName(descriptor_->field(i)));
// printer->Print(
// "inline void clear_has_$name$();\n",
// "name", FieldName(descriptor_->field(i)));
// }
// }
// printer->Print("\n");
// // To minimize padding, data members are divided into three sections:
// // (1) members assumed to align to 8 bytes
// // (2) members corresponding to message fields, re-ordered to optimize
// // alignment.
// // (3) members assumed to align to 4 bytes.
//
// // Members assumed to align to 8 bytes:
//
// if (descriptor_->extension_range_count() > 0) {
// printer->Print(
// "::google::protobuf::internal::ExtensionSet _extensions_;\n"
// "\n");
// }
//
// if (HasUnknownFields(descriptor_->file())) {
// printer->Print(
// "::google::protobuf::UnknownFieldSet _unknown_fields_;\n"
// "\n");
// }
// Field members:
// vector<const FieldDescriptor*> fields;
// for (int i = 0; i < descriptor_->field_count(); i++) {
// fields.push_back(descriptor_->field(i));
// }
// OptimizePadding(&fields);
// for (int i = 0; i < fields.size(); ++i) {
// field_generators_.get(fields[i]).GeneratePrivateMembers(printer);
// }
//
// // Members assumed to align to 4 bytes:
//
// // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
// printer->Print(
// "\n"
// "mutable int _cached_size_;\n");
//
// // Generate _has_bits_.
// if (descriptor_->field_count() > 0) {
// printer->Print(vars,
// "::google::protobuf::uint32 _has_bits_[($field_count$ + 31) / 32];\n"
// "\n");
// } else {
// // Zero-size arrays aren't technically allowed, and MSVC in particular
// // doesn't like them. We still need to declare these arrays to make
// // other code compile. Since this is an uncommon case, we'll just declare
// // them with size 1 and waste some space. Oh well.
// printer->Print(
// "::google::protobuf::uint32 _has_bits_[1];\n"
// "\n");
// }
//
// // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
// // friends so that they can access private static variables like
// // default_instance_ and reflection_.
// PrintHandlingOptionalStaticInitializers(
// descriptor_->file(), printer,
// // With static initializers.
// "friend void $dllexport_decl$ $adddescriptorsname$();\n",
// // Without.
// "friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
// // Vars.
// "dllexport_decl", options_.dllexport_decl,
// "adddescriptorsname",
// GlobalAddDescriptorsName(descriptor_->file()->name()));
//
// printer->Print(
// "friend void $assigndescriptorsname$();\n"
// "friend void $shutdownfilename$();\n"
// "\n",
// "assigndescriptorsname",
// GlobalAssignDescriptorsName(descriptor_->file()->name()),
// "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
//
// printer->Print(
// "void InitAsDefaultInstance();\n"
// "static $classname$* default_instance_;\n",
// "classname", classname_);
//
// printer->Outdent();
// printer->Print(vars, "};");
}
void MessageGenerator::
GenerateInlineMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateInlineMethods(printer);
printer->Print(kThinSeparator);
printer->Print("\n");
}
GenerateFieldAccessorDefinitions(printer);
}
void MessageGenerator::
GenerateDescriptorDeclarations(io::Printer* printer) {
printer->Print(
"const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
"const ::google::protobuf::internal::GeneratedMessageReflection*\n"
" $name$_reflection_ = NULL;\n",
"name", classname_);
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateDescriptorDeclarations(printer);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
printer->Print(
"const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
"name", ClassName(descriptor_->enum_type(i), false));
}
}
void MessageGenerator::
GenerateDescriptorInitializer(io::Printer* printer, int index) {
// TODO(kenton): Passing the index to this method is redundant; just use
// descriptor_->index() instead.
map<string, string> vars;
vars["classname"] = classname_;
vars["index"] = SimpleItoa(index);
// Obtain the descriptor from the parent's descriptor.
if (descriptor_->containing_type() == NULL) {
printer->Print(vars,
"$classname$_descriptor_ = file->message_type($index$);\n");
} else {
vars["parent"] = ClassName(descriptor_->containing_type(), false);
printer->Print(vars,
"$classname$_descriptor_ = "
"$parent$_descriptor_->nested_type($index$);\n");
}
// Generate the offsets.
GenerateOffsets(printer);
// Construct the reflection object.
printer->Print(vars,
"$classname$_reflection_ =\n"
" new ::google::protobuf::internal::GeneratedMessageReflection(\n"
" $classname$_descriptor_,\n"
" $classname$::default_instance_,\n"
" $classname$_offsets_,\n"
" GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n"
" GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
"$classname$, _unknown_fields_),\n");
if (descriptor_->extension_range_count() > 0) {
printer->Print(vars,
" GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
"$classname$, _extensions_),\n");
} else {
// No extensions.
printer->Print(vars,
" -1,\n");
}
printer->Print(
" ::google::protobuf::DescriptorPool::generated_pool(),\n");
printer->Print(vars,
" ::google::protobuf::MessageFactory::generated_factory(),\n");
printer->Print(vars,
" sizeof($classname$));\n");
// Handle nested types.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
}
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
}
}
void MessageGenerator::
GenerateTypeRegistrations(io::Printer* printer) {
// Register this message type with the message factory.
printer->Print(
"::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
" $classname$_descriptor_, &$classname$::default_instance());\n",
"classname", classname_);
// Handle nested types.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateTypeRegistrations(printer);
}
}
void MessageGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) {
// Construct the default instances of all fields, as they will be used
// when creating the default instance of the entire message.
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateDefaultInstanceAllocator(printer);
}
// Construct the default instance. We can't call InitAsDefaultInstance() yet
// because we need to make sure all default instances that this one might
// depend on are constructed first.
printer->Print(
"$classname$::default_instance_ = new $classname$();\n",
"classname", classname_);
// Handle nested types.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
}
}
void MessageGenerator::
GenerateDefaultInstanceInitializer(io::Printer* printer) {
printer->Print(
"$classname$::default_instance_->InitAsDefaultInstance();\n",
"classname", classname_);
// Register extensions.
for (int i = 0; i < descriptor_->extension_count(); i++) {
extension_generators_[i]->GenerateRegistration(printer);
}
// Handle nested types.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
}
}
void MessageGenerator::
GenerateShutdownCode(io::Printer* printer) {
printer->Print(
"delete $classname$::default_instance_;\n",
"classname", classname_);
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(
"delete $classname$_reflection_;\n",
"classname", classname_);
}
// Handle default instances of fields.
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateShutdownCode(printer);
}
// Handle nested types.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateShutdownCode(printer);
}
}
void MessageGenerator::
GenerateClassMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateMethods(printer);
}
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
nested_generators_[i]->GenerateClassMethods(printer);
printer->Print("\n");
printer->Print(kThinSeparator);
printer->Print("\n");
}
// Generate non-inline field definitions.
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateNonInlineAccessorDefinitions(printer);
}
// Generate field number constants.
printer->Print("#ifndef _MSC_VER\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor *field = descriptor_->field(i);
printer->Print(
"const int $classname$::$constant_name$;\n",
"classname", ClassName(FieldScope(field), false),
"constant_name", FieldConstantName(field));
}
printer->Print(
"#endif // !_MSC_VER\n"
"\n");
// Define extension identifiers.
for (int i = 0; i < descriptor_->extension_count(); i++) {
extension_generators_[i]->GenerateDefinition(printer);
}
GenerateStructors(printer);
printer->Print("\n");
if (HasGeneratedMethods(descriptor_->file())) {
GenerateClear(printer);
printer->Print("\n");
GenerateMergeFromCodedStream(printer);
printer->Print("\n");
GenerateSerializeWithCachedSizes(printer);
printer->Print("\n");
if (HasFastArraySerialization(descriptor_->file())) {
GenerateSerializeWithCachedSizesToArray(printer);
printer->Print("\n");
}
GenerateByteSize(printer);
printer->Print("\n");
GenerateMergeFrom(printer);
printer->Print("\n");
GenerateCopyFrom(printer);
printer->Print("\n");
GenerateIsInitialized(printer);
printer->Print("\n");
}
GenerateSwap(printer);
printer->Print("\n");
if (HasDescriptorMethods(descriptor_->file())) {
printer->Print(
"::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
" protobuf_AssignDescriptorsOnce();\n"
" ::google::protobuf::Metadata metadata;\n"
" metadata.descriptor = $classname$_descriptor_;\n"
" metadata.reflection = $classname$_reflection_;\n"
" return metadata;\n"
"}\n"
"\n",
"classname", classname_);
} else {
printer->Print(
"::std::string $classname$::GetTypeName() const {\n"
" return \"$type_name$\";\n"
"}\n"
"\n",
"classname", classname_,
"type_name", descriptor_->full_name());
}
}
void MessageGenerator::
GenerateOffsets(io::Printer* printer) {
printer->Print(
"static const int $classname$_offsets_[$field_count$] = {\n",
"classname", classname_,
"field_count", SimpleItoa(max(1, descriptor_->field_count())));
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
printer->Print(
"GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
"classname", classname_,
"name", FieldName(field));
}
printer->Outdent();
printer->Print("};\n");
}
void MessageGenerator::
GenerateSharedConstructorCode(io::Printer* printer) {
printer->Print(
"void $classname$::SharedCtor() {\n",
"classname", classname_);
printer->Indent();
printer->Print(
"_cached_size_ = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateConstructorCode(printer);
}
printer->Print(
"::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
printer->Outdent();
printer->Print("}\n\n");
}
void MessageGenerator::
GenerateSharedDestructorCode(io::Printer* printer) {
printer->Print(
"void $classname$::SharedDtor() {\n",
"classname", classname_);
printer->Indent();
// Write the destructors for each field.
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(descriptor_->field(i))
.GenerateDestructorCode(printer);
}
PrintHandlingOptionalStaticInitializers(
descriptor_->file(), printer,
// With static initializers.
"if (this != default_instance_) {\n",
// Without.
"if (this != &default_instance()) {\n");
// We need to delete all embedded messages.
// TODO(kenton): If we make unset messages point at default instances
// instead of NULL, then it would make sense to move this code into
// MessageFieldGenerator::GenerateDestructorCode().
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (!field->is_repeated() &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(" delete $name$_;\n",
"name", FieldName(field));
}
}
printer->Outdent();
printer->Print(
" }\n"
"}\n"
"\n");
}