forked from protocolbuffers/protobuf
/
cpp_message.cc
4144 lines (3668 loc) · 142 KB
/
cpp_message.cc
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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/cpp/cpp_message.h>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include <google/protobuf/compiler/cpp/cpp_enum.h>
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
#include <google/protobuf/compiler/cpp/cpp_parse_function_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/hash.h>
// Must be included last.
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
using internal::WireFormat;
using internal::WireFormatLite;
namespace {
static constexpr int kNoHasbit = -1;
// Create an expression that evaluates to
// "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
// masks is allowed to be shorter than _has_bits_, but at least one element of
// masks must be non-zero.
std::string ConditionalToCheckBitmasks(
const std::vector<uint32_t>& masks, bool return_success = true,
StringPiece has_bits_var = "_has_bits_") {
std::vector<std::string> parts;
for (int i = 0; i < masks.size(); i++) {
if (masks[i] == 0) continue;
std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
// Each xor evaluates to 0 if the expected bits are present.
parts.push_back(
StrCat("((", has_bits_var, "[", i, "] & ", m, ") ^ ", m, ")"));
}
GOOGLE_CHECK(!parts.empty());
// If we have multiple parts, each expected to be 0, then bitwise-or them.
std::string result =
parts.size() == 1
? parts[0]
: StrCat("(", Join(parts, "\n | "), ")");
return result + (return_success ? " == 0" : " != 0");
}
void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
const std::vector<int>& has_bit_indices,
io::Printer* printer, int* cached_has_word_index) {
if (!field->options().weak()) {
int has_bit_index = has_bit_indices[field->index()];
if (*cached_has_word_index != (has_bit_index / 32)) {
*cached_has_word_index = (has_bit_index / 32);
format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_word_index);
}
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("if (cached_has_bits & 0x$1$u) {\n", mask);
} else {
format("if (has_$1$()) {\n", FieldName(field));
}
format.Indent();
}
struct FieldOrderingByNumber {
inline bool operator()(const FieldDescriptor* a,
const FieldDescriptor* b) const {
return a->number() < b->number();
}
};
// Sort the fields of the given Descriptor by number into a new[]'d array
// and return it.
std::vector<const FieldDescriptor*> SortFieldsByNumber(
const Descriptor* descriptor) {
std::vector<const FieldDescriptor*> fields(descriptor->field_count());
for (int i = 0; i < descriptor->field_count(); i++) {
fields[i] = descriptor->field(i);
}
std::sort(fields.begin(), fields.end(), 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;
}
};
bool IsPOD(const FieldDescriptor* field) {
if (field->is_repeated() || field->is_extension()) return false;
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
case FieldDescriptor::CPPTYPE_INT32:
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT32:
case FieldDescriptor::CPPTYPE_UINT64:
case FieldDescriptor::CPPTYPE_FLOAT:
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_BOOL:
return true;
case FieldDescriptor::CPPTYPE_STRING:
return false;
default:
return false;
}
}
// Helper for the code that emits the SharedCtor() and InternalSwap() methods.
// Anything that is a POD or a "normal" message (represented by a pointer) can
// be manipulated as raw bytes.
bool CanBeManipulatedAsRawBytes(const FieldDescriptor* field,
const Options& options,
MessageSCCAnalyzer* scc_analyzer) {
bool ret = CanInitializeByZeroing(field);
// Non-repeated, non-lazy message fields are simply raw pointers, so we can
// swap them or use memset to initialize these in SharedCtor. We cannot use
// this in Clear, as we need to potentially delete the existing value.
ret =
ret || (!field->is_repeated() && !IsLazy(field, options, scc_analyzer) &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
return ret;
}
// Finds runs of fields for which `predicate` is true.
// RunMap maps from fields that start each run to the number of fields in that
// run. This is optimized for the common case that there are very few runs in
// a message and that most of the eligible fields appear together.
using RunMap = std::unordered_map<const FieldDescriptor*, size_t>;
RunMap FindRuns(const std::vector<const FieldDescriptor*>& fields,
const std::function<bool(const FieldDescriptor*)>& predicate) {
RunMap runs;
const FieldDescriptor* last_start = nullptr;
for (auto field : fields) {
if (predicate(field)) {
if (last_start == nullptr) {
last_start = field;
}
runs[last_start]++;
} else {
last_start = nullptr;
}
}
return runs;
}
// Emits an if-statement with a condition that evaluates to true if |field| is
// considered non-default (will be sent over the wire), for message types
// without true field presence. Should only be called if
// !HasHasbit(field).
bool EmitFieldNonDefaultCondition(io::Printer* printer,
const std::string& prefix,
const FieldDescriptor* field) {
GOOGLE_CHECK(!HasHasbit(field));
Formatter format(printer);
format.Set("prefix", prefix);
format.Set("name", FieldName(field));
// Merge and serialize semantics: primitive fields are merged/serialized only
// if non-zero (numeric) or non-empty (string).
if (!field->is_repeated() && !field->containing_oneof()) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
format("if (!$prefix$_internal_$name$().empty()) {\n");
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Message fields still have has_$name$() methods.
format("if ($prefix$_internal_has_$name$()) {\n");
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE ||
field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT) {
// Handle float comparison to prevent -Wfloat-equal warnings
format(
"if (!($prefix$_internal_$name$() <= 0 && $prefix$_internal_$name$() "
">= 0)) {\n");
} else {
format("if ($prefix$_internal_$name$() != 0) {\n");
}
format.Indent();
return true;
} else if (field->real_containing_oneof()) {
format("if (_internal_has_$name$()) {\n");
format.Indent();
return true;
}
return false;
}
// Does the given field have a has_$name$() method?
bool HasHasMethod(const FieldDescriptor* field) {
if (!IsProto3(field->file())) {
// In proto1/proto2, every field has a has_$name$() method.
return true;
}
// For message types without true field presence, only fields with a message
// type or inside an one-of have a has_$name$() method.
return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
field->has_optional_keyword() || field->real_containing_oneof();
}
// Collects map entry message type information.
void CollectMapInfo(const Options& options, const Descriptor* descriptor,
std::map<std::string, std::string>* variables) {
GOOGLE_CHECK(IsMapEntryMessage(descriptor));
std::map<std::string, std::string>& vars = *variables;
const FieldDescriptor* key = descriptor->FindFieldByName("key");
const FieldDescriptor* val = descriptor->FindFieldByName("value");
vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
vars["val_cpp"] = FieldMessageTypeName(val, options);
break;
case FieldDescriptor::CPPTYPE_ENUM:
vars["val_cpp"] = ClassName(val->enum_type(), true);
break;
default:
vars["val_cpp"] = PrimitiveTypeName(options, val->cpp_type());
}
vars["key_wire_type"] =
"TYPE_" + ToUpper(DeclaredTypeMethodName(key->type()));
vars["val_wire_type"] =
"TYPE_" + ToUpper(DeclaredTypeMethodName(val->type()));
}
// Does the given field have a private (internal helper only) has_$name$()
// method?
bool HasPrivateHasMethod(const FieldDescriptor* field) {
// Only for oneofs in message types with no field presence. has_$name$(),
// based on the oneof case, is still useful internally for generated code.
return IsProto3(field->file()) && field->real_containing_oneof();
}
// TODO(ckennelly): Cull these exclusions if/when these protos do not have
// their methods overridden by subclasses.
bool ShouldMarkClassAsFinal(const Descriptor* descriptor,
const Options& options) {
return true;
}
bool ShouldMarkClearAsFinal(const Descriptor* descriptor,
const Options& options) {
static std::set<std::string> exclusions{
};
const std::string name = ClassName(descriptor, true);
return exclusions.find(name) == exclusions.end() ||
options.opensource_runtime;
}
// Returns true to make the message serialize in order, decided by the following
// factors in the order of precedence.
// --options().message_set_wire_format() == true
// --the message is in the allowlist (true)
// --GOOGLE_PROTOBUF_SHUFFLE_SERIALIZE is defined (false)
// --a ranage of message names that are allowed to stay in order (true)
bool ShouldSerializeInOrder(const Descriptor* descriptor,
const Options& options) {
return true;
}
bool TableDrivenParsingEnabled(const Descriptor* descriptor,
const Options& options,
MessageSCCAnalyzer* scc_analyzer) {
if (!options.table_driven_parsing) {
return false;
}
// Consider table-driven parsing. We only do this if:
// - We have has_bits for fields. This avoids a check on every field we set
// when are present (the common case).
bool has_hasbit = false;
for (int i = 0; i < descriptor->field_count(); i++) {
if (HasHasbit(descriptor->field(i))) {
has_hasbit = true;
break;
}
}
if (!has_hasbit) return false;
const double table_sparseness = 0.5;
int max_field_number = 0;
for (auto field : FieldRange(descriptor)) {
if (max_field_number < field->number()) {
max_field_number = field->number();
}
// - There are no weak fields.
if (IsWeak(field, options)) {
return false;
}
// - There are no lazy fields (they require the non-lite library).
if (IsLazy(field, options, scc_analyzer)) {
return false;
}
}
// - There range of field numbers is "small"
if (max_field_number >= (2 << 14)) {
return false;
}
// - Field numbers are relatively dense within the actual number of fields.
// We check for strictly greater than in the case where there are no fields
// (only extensions) so max_field_number == descriptor->field_count() == 0.
if (max_field_number * table_sparseness > descriptor->field_count()) {
return false;
}
// - This is not a MapEntryMessage.
if (IsMapEntryMessage(descriptor)) {
return false;
}
return true;
}
bool IsCrossFileMapField(const FieldDescriptor* field) {
if (!field->is_map()) {
return false;
}
const Descriptor* d = field->message_type();
const FieldDescriptor* value = d->FindFieldByNumber(2);
return IsCrossFileMessage(value);
}
bool IsCrossFileMaybeMap(const FieldDescriptor* field) {
if (IsCrossFileMapField(field)) {
return true;
}
return IsCrossFileMessage(field);
}
bool IsRequired(const std::vector<const FieldDescriptor*>& v) {
return v.front()->is_required();
}
// Collects neighboring fields based on a given criteria (equivalent predicate).
template <typename Predicate>
std::vector<std::vector<const FieldDescriptor*>> CollectFields(
const std::vector<const FieldDescriptor*>& fields,
const Predicate& equivalent) {
std::vector<std::vector<const FieldDescriptor*>> chunks;
for (auto field : fields) {
if (chunks.empty() || !equivalent(chunks.back().back(), field)) {
chunks.emplace_back();
}
chunks.back().push_back(field);
}
return chunks;
}
// Returns a bit mask based on has_bit index of "fields" that are typically on
// the same chunk. It is used in a group presence check where _has_bits_ is
// masked to tell if any thing in "fields" is present.
uint32_t GenChunkMask(const std::vector<const FieldDescriptor*>& fields,
const std::vector<int>& has_bit_indices) {
GOOGLE_CHECK(!fields.empty());
int first_index_offset = has_bit_indices[fields.front()->index()] / 32;
uint32_t chunk_mask = 0;
for (auto field : fields) {
// "index" defines where in the _has_bits_ the field appears.
int index = has_bit_indices[field->index()];
GOOGLE_CHECK_EQ(first_index_offset, index / 32);
chunk_mask |= static_cast<uint32_t>(1) << (index % 32);
}
GOOGLE_CHECK_NE(0, chunk_mask);
return chunk_mask;
}
// Return the number of bits set in n, a non-negative integer.
static int popcnt(uint32_t n) {
int result = 0;
while (n != 0) {
result += (n & 1);
n = n / 2;
}
return result;
}
// For a run of cold chunks, opens and closes an external if statement that
// checks multiple has_bits words to skip bulk of cold fields.
class ColdChunkSkipper {
public:
ColdChunkSkipper(
const Options& options,
const std::vector<std::vector<const FieldDescriptor*>>& chunks,
const std::vector<int>& has_bit_indices, const double cold_threshold)
: chunks_(chunks),
has_bit_indices_(has_bit_indices),
access_info_map_(options.access_info_map),
cold_threshold_(cold_threshold) {
SetCommonVars(options, &variables_);
}
// May open an external if check for a batch of cold fields. "from" is the
// prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_".
// Otherwise, it should be "".
void OnStartChunk(int chunk, int cached_has_word_index,
const std::string& from, io::Printer* printer);
bool OnEndChunk(int chunk, io::Printer* printer);
private:
bool IsColdChunk(int chunk);
int HasbitWord(int chunk, int offset) {
return has_bit_indices_[chunks_[chunk][offset]->index()] / 32;
}
const std::vector<std::vector<const FieldDescriptor*>>& chunks_;
const std::vector<int>& has_bit_indices_;
const AccessInfoMap* access_info_map_;
const double cold_threshold_;
std::map<std::string, std::string> variables_;
int limit_chunk_ = -1;
};
// Tuning parameters for ColdChunkSkipper.
const double kColdRatio = 0.005;
bool ColdChunkSkipper::IsColdChunk(int chunk) {
// Mark this variable as used until it is actually used
(void)cold_threshold_;
return false;
}
void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_word_index,
const std::string& from,
io::Printer* printer) {
Formatter format(printer, variables_);
if (!access_info_map_) {
return;
} else if (chunk < limit_chunk_) {
// We are already inside a run of cold chunks.
return;
} else if (!IsColdChunk(chunk)) {
// We can't start a run of cold chunks.
return;
}
// Find the end of consecutive cold chunks.
limit_chunk_ = chunk;
while (limit_chunk_ < chunks_.size() && IsColdChunk(limit_chunk_)) {
limit_chunk_++;
}
if (limit_chunk_ <= chunk + 1) {
// Require at least two chunks to emit external has_bit checks.
limit_chunk_ = -1;
return;
}
// Emit has_bit check for each has_bit_dword index.
format("if (PROTOBUF_PREDICT_FALSE(");
int first_word = HasbitWord(chunk, 0);
while (chunk < limit_chunk_) {
uint32_t mask = 0;
int this_word = HasbitWord(chunk, 0);
// Generate mask for chunks on the same word.
for (; chunk < limit_chunk_ && HasbitWord(chunk, 0) == this_word; chunk++) {
for (auto field : chunks_[chunk]) {
int hasbit_index = has_bit_indices_[field->index()];
// Fields on a chunk must be in the same word.
GOOGLE_CHECK_EQ(this_word, hasbit_index / 32);
mask |= 1 << (hasbit_index % 32);
}
}
if (this_word != first_word) {
format(" ||\n ");
}
format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8));
if (this_word == cached_has_word_index) {
format("(cached_has_bits & 0x$mask$u) != 0");
} else {
format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word);
}
}
format(")) {\n");
format.Indent();
}
bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) {
Formatter format(printer, variables_);
if (chunk != limit_chunk_ - 1) {
return false;
}
format.Outdent();
format("}\n");
return true;
}
} // anonymous namespace
// ===================================================================
MessageGenerator::MessageGenerator(
const Descriptor* descriptor,
const std::map<std::string, std::string>& vars, int index_in_file_messages,
const Options& options, MessageSCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
index_in_file_messages_(index_in_file_messages),
classname_(ClassName(descriptor, false)),
options_(options),
field_generators_(descriptor, options, scc_analyzer),
max_has_bit_index_(0),
num_weak_fields_(0),
scc_analyzer_(scc_analyzer),
variables_(vars) {
if (!message_layout_helper_) {
message_layout_helper_.reset(new PaddingOptimizer());
}
// Variables that apply to this class
variables_["classname"] = classname_;
variables_["classtype"] = QualifiedClassName(descriptor_, options);
variables_["full_name"] = descriptor_->full_name();
variables_["superclass"] = SuperClassName(descriptor_, options_);
variables_["annotate_serialize"] = "";
variables_["annotate_deserialize"] = "";
variables_["annotate_reflection"] = "";
variables_["annotate_bytesize"] = "";
if (options.inject_field_listener_events &&
descriptor->file()->options().optimize_for() !=
google::protobuf::FileOptions::LITE_RUNTIME) {
const std::string injector_template = StrCat(
" {\n"
" auto _listener_ = ::",
variables_["proto_ns"],
"::FieldAccessListener::GetListener();\n"
" if (_listener_) ");
StrAppend(&variables_["annotate_serialize"], injector_template,
"_listener_->OnSerializationAccess(this);\n"
" }\n");
StrAppend(&variables_["annotate_deserialize"], injector_template,
" _listener_->OnDeserializationAccess(this);\n"
" }\n");
// TODO(danilak): Ideally annotate_reflection should not exist and we need
// to annotate all reflective calls on our own, however, as this is a cause
// for side effects, i.e. reading values dynamically, we want the users know
// that dynamic access can happen.
StrAppend(&variables_["annotate_reflection"], injector_template,
"_listener_->OnReflectionAccess(default_instance()"
".GetMetadata().descriptor);\n"
" }\n");
StrAppend(&variables_["annotate_bytesize"], injector_template,
"_listener_->OnByteSizeAccess(this);\n"
" }\n");
}
SetUnknownFieldsVariable(descriptor_, options_, &variables_);
// Compute optimized field order to be used for layout and initialization
// purposes.
for (auto field : FieldRange(descriptor_)) {
if (IsFieldStripped(field, options_)) {
continue;
}
if (IsWeak(field, options_)) {
num_weak_fields_++;
} else if (!field->real_containing_oneof()) {
optimized_order_.push_back(field);
}
}
message_layout_helper_->OptimizeLayout(&optimized_order_, options_,
scc_analyzer_);
// This message has hasbits iff one or more fields need one.
for (auto field : optimized_order_) {
if (HasHasbit(field)) {
if (has_bit_indices_.empty()) {
has_bit_indices_.resize(descriptor_->field_count(), kNoHasbit);
}
has_bit_indices_[field->index()] = max_has_bit_index_++;
}
}
if (!has_bit_indices_.empty()) {
field_generators_.SetHasBitIndices(has_bit_indices_);
}
num_required_fields_ = 0;
for (int i = 0; i < descriptor->field_count(); i++) {
if (descriptor->field(i)->is_required()) {
++num_required_fields_;
}
}
table_driven_ =
TableDrivenParsingEnabled(descriptor_, options_, scc_analyzer_);
parse_function_generator_.reset(new ParseFunctionGenerator(
descriptor_, max_has_bit_index_, has_bit_indices_, options_,
scc_analyzer_, variables_));
}
MessageGenerator::~MessageGenerator() = default;
size_t MessageGenerator::HasBitsSize() const {
return (max_has_bit_index_ + 31) / 32;
}
int MessageGenerator::HasBitIndex(const FieldDescriptor* field) const {
return has_bit_indices_.empty() ? kNoHasbit
: has_bit_indices_[field->index()];
}
int MessageGenerator::HasByteIndex(const FieldDescriptor* field) const {
int hasbit = HasBitIndex(field);
return hasbit == kNoHasbit ? kNoHasbit : hasbit / 8;
}
int MessageGenerator::HasWordIndex(const FieldDescriptor* field) const {
int hasbit = HasBitIndex(field);
return hasbit == kNoHasbit ? kNoHasbit : hasbit / 32;
}
void MessageGenerator::AddGenerators(
std::vector<std::unique_ptr<EnumGenerator>>* enum_generators,
std::vector<std::unique_ptr<ExtensionGenerator>>* extension_generators) {
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators->emplace_back(
new EnumGenerator(descriptor_->enum_type(i), variables_, options_));
enum_generators_.push_back(enum_generators->back().get());
}
for (int i = 0; i < descriptor_->extension_count(); i++) {
extension_generators->emplace_back(
new ExtensionGenerator(descriptor_->extension(i), options_));
extension_generators_.push_back(extension_generators->back().get());
}
}
void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) {
Formatter format(printer, variables_);
// optimized_fields_ does not contain fields where
// field->real_containing_oneof()
// so we need to iterate over those as well.
//
// We place the non-oneof fields in optimized_order_, as that controls the
// order of the _has_bits_ entries and we want GDB's pretty printers to be
// able to infer these indices from the k[FIELDNAME]FieldNumber order.
std::vector<const FieldDescriptor*> ordered_fields;
ordered_fields.reserve(descriptor_->field_count());
ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(),
optimized_order_.end());
for (auto field : FieldRange(descriptor_)) {
if (!field->real_containing_oneof() && !field->options().weak() &&
!IsFieldStripped(field, options_)) {
continue;
}
ordered_fields.push_back(field);
}
if (!ordered_fields.empty()) {
format("enum : int {\n");
for (auto field : ordered_fields) {
Formatter::SaveState save(&format);
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
format.AddMap(vars);
format(" ${1$$2$$}$ = $number$,\n", field, FieldConstantName(field));
}
format("};\n");
}
for (auto field : ordered_fields) {
PrintFieldComment(format, field);
Formatter::SaveState save(&format);
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
format.AddMap(vars);
if (field->is_repeated()) {
format("$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field,
!IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}");
if (!IsFieldStripped(field, options_)) {
format(
"private:\n"
"int ${1$_internal_$name$_size$}$() const;\n"
"public:\n",
field);
}
} else if (HasHasMethod(field)) {
format("$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field,
!IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}");
if (!IsFieldStripped(field, options_)) {
format(
"private:\n"
"bool _internal_has_$name$() const;\n"
"public:\n");
}
} else if (HasPrivateHasMethod(field)) {
if (!IsFieldStripped(field, options_)) {
format(
"private:\n"
"bool ${1$_internal_has_$name$$}$() const;\n"
"public:\n",
field);
}
}
format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field,
!IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}");
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateAccessorDeclarations(printer);
format("\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.
format("$GOOGLE_PROTOBUF$_EXTENSION_ACCESSORS($classname$)\n");
// Generate MessageSet specific APIs for proto2 MessageSet.
// For testing purposes we don't check for bridge.MessageSet, so
// we don't use IsProto2MessageSet
if (descriptor_->options().message_set_wire_format() &&
!options_.opensource_runtime && !options_.lite_implicit_weak_fields) {
// Special-case MessageSet
format("GOOGLE_PROTOBUF_EXTENSION_MESSAGE_SET_ACCESSORS($classname$)\n");
}
}
for (auto oneof : OneOfRange(descriptor_)) {
Formatter::SaveState saver(&format);
format.Set("oneof_name", oneof->name());
format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true));
format(
"void ${1$clear_$oneof_name$$}$();\n"
"$camel_oneof_name$Case $oneof_name$_case() const;\n",
oneof);
}
}
void MessageGenerator::GenerateSingularFieldHasBits(
const FieldDescriptor* field, Formatter format) {
if (IsFieldStripped(field, options_)) {
format(
"inline bool $classname$::has_$name$() const { "
"__builtin_trap(); }\n");
return;
}
if (field->options().weak()) {
format(
"inline bool $classname$::has_$name$() const {\n"
"$annotate_has$"
" return _weak_field_map_.Has($number$);\n"
"}\n");
return;
}
if (HasHasbit(field)) {
int has_bit_index = HasBitIndex(field);
GOOGLE_CHECK_NE(has_bit_index, kNoHasbit);
format.Set("has_array_index", has_bit_index / 32);
format.Set("has_mask",
strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format(
"inline bool $classname$::_internal_has_$name$() const {\n"
" bool value = "
"(_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n");
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!IsLazy(field, options_, scc_analyzer_)) {
// We maintain the invariant that for a submessage x, has_x() returning
// true implies that x_ is not null. By giving this information to the
// compiler, we allow it to eliminate unnecessary null checks later on.
format(" PROTOBUF_ASSUME(!value || $name$_ != nullptr);\n");
}
format(
" return value;\n"
"}\n"
"inline bool $classname$::has_$name$() const {\n"
"$annotate_has$"
" return _internal_has_$name$();\n"
"}\n");
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Message fields have a has_$name$() method.
if (IsLazy(field, options_, scc_analyzer_)) {
format(
"inline bool $classname$::_internal_has_$name$() const {\n"
" return !$name$_.IsCleared();\n"
"}\n");
} else {
format(
"inline bool $classname$::_internal_has_$name$() const {\n"
" return this != internal_default_instance() "
"&& $name$_ != nullptr;\n"
"}\n");
}
format(
"inline bool $classname$::has_$name$() const {\n"
"$annotate_has$"
" return _internal_has_$name$();\n"
"}\n");
}
}
void MessageGenerator::GenerateOneofHasBits(io::Printer* printer) {
Formatter format(printer, variables_);
for (auto oneof : OneOfRange(descriptor_)) {
format.Set("oneof_name", oneof->name());
format.Set("oneof_index", oneof->index());
format.Set("cap_oneof_name", ToUpper(oneof->name()));
format(
"inline bool $classname$::has_$oneof_name$() const {\n"
" return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n"
"}\n"
"inline void $classname$::clear_has_$oneof_name$() {\n"
" _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n"
"}\n");
}
}
void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field,
const Formatter& format) {
if (IsFieldStripped(field, options_)) {
if (HasHasMethod(field)) {
format(
"inline bool $classname$::has_$name$() const { "
"__builtin_trap(); }\n");
}
format(
"inline void $classname$::set_has_$name$() { __builtin_trap(); "
"}\n");
return;
}
// Singular field in a oneof
// N.B.: Without field presence, we do not use has-bits or generate
// has_$name$() methods, but oneofs still have set_has_$name$().
// Oneofs also have has_$name$() but only as a private helper
// method, so that generated code is slightly cleaner (vs. comparing
// _oneof_case_[index] against a constant everywhere).
//
// If has_$name$() is private, there is no need to add an internal accessor.
// Only annotate public accessors.
if (HasHasMethod(field)) {
format(
"inline bool $classname$::_internal_has_$name$() const {\n"
" return $oneof_name$_case() == k$field_name$;\n"
"}\n"
"inline bool $classname$::has_$name$() const {\n"
"$annotate_has$"
" return _internal_has_$name$();\n"
"}\n");
} else if (HasPrivateHasMethod(field)) {
format(
"inline bool $classname$::_internal_has_$name$() const {\n"
" return $oneof_name$_case() == k$field_name$;\n"
"}\n");
}
// set_has_$name$() for oneof fields is always private; hence should not be
// annotated.
format(
"inline void $classname$::set_has_$name$() {\n"
" _oneof_case_[$oneof_index$] = k$field_name$;\n"
"}\n");
}
void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field,
bool is_inline, Formatter format) {
if (IsFieldStripped(field, options_)) {
format("void $classname$::clear_$name$() { __builtin_trap(); }\n");
return;
}
// Generate clear_$name$().
if (is_inline) {
format("inline ");
}
format("void $classname$::clear_$name$() {\n");
format.Indent();
if (field->real_containing_oneof()) {
// Clear this field only if it is the active field in this oneof,
// otherwise ignore
format("if (_internal_has_$name$()) {\n");
format.Indent();
field_generators_.get(field).GenerateClearingCode(format.printer());
format("clear_has_$oneof_name$();\n");
format.Outdent();
format("}\n");
} else {
field_generators_.get(field).GenerateClearingCode(format.printer());
if (HasHasbit(field)) {
int has_bit_index = HasBitIndex(field);
format.Set("has_array_index", has_bit_index / 32);
format.Set("has_mask",
strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n");
}
}
format("$annotate_clear$");
format.Outdent();
format("}\n");
}
void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) {
Formatter format(printer, variables_);
format("// $classname$\n\n");
for (auto field : FieldRange(descriptor_)) {
PrintFieldComment(format, field);
if (IsFieldStripped(field, options_)) {
continue;
}
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
Formatter::SaveState saver(&format);
format.AddMap(vars);
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
if (IsFieldStripped(field, options_)) {
format(
"inline int $classname$::$name$_size() const { "
"__builtin_trap(); }\n");
} else {
format(
"inline int $classname$::_internal_$name$_size() const {\n"
" return $name$_$1$.size();\n"
"}\n"
"inline int $classname$::$name$_size() const {\n"
"$annotate_size$"
" return _internal_$name$_size();\n"
"}\n",