Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1514 lines (1410 loc) · 64.1 KB
/
Copy pathmain.cpp
File metadata and controls
1514 lines (1410 loc) · 64.1 KB
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 <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace {
using ::google::protobuf::Descriptor;
using ::google::protobuf::DescriptorPool;
using ::google::protobuf::EnumDescriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::FileDescriptor;
using ::google::protobuf::FileDescriptorSet;
using ::google::protobuf::MethodDescriptor;
using ::google::protobuf::OneofDescriptor;
using ::google::protobuf::ServiceDescriptor;
constexpr const char* kDetailNs = "::brpc_fast::detail::";
constexpr const char* kGeneratedRootNs = "brpc_fast_pb";
struct CodegenOptions {
bool preserve_unknown_fields = false;
};
// ---- Naming & descriptor utilities ----
const std::unordered_set<std::string>& CppKeywords() {
static const std::unordered_set<std::string> kKeywords = {
"alignas", "alignof", "and",
"and_eq", "asm", "auto",
"bitand", "bitor", "bool",
"break", "case", "catch",
"char", "char8_t", "char16_t",
"char32_t", "class", "compl",
"concept", "const", "consteval",
"constexpr", "constinit", "const_cast",
"continue", "co_await", "co_return",
"co_yield", "decltype", "default",
"delete", "do", "double",
"dynamic_cast", "else", "enum",
"explicit", "export", "extern",
"false", "float", "for",
"friend", "goto", "if",
"inline", "int", "long",
"mutable", "namespace", "new",
"noexcept", "not", "not_eq",
"nullptr", "operator", "or",
"or_eq", "private", "protected",
"public", "register", "reinterpret_cast",
"requires", "return", "short",
"signed", "sizeof", "static",
"static_assert", "static_cast", "struct",
"switch", "template", "this",
"thread_local", "throw", "true",
"try", "typedef", "typeid",
"typename", "union", "unsigned",
"using", "virtual", "void",
"volatile", "wchar_t", "while",
"xor", "xor_eq",
};
return kKeywords;
}
std::string SafeIdent(const std::string& name) {
return CppKeywords().count(name) > 0 ? (name + "_") : name;
}
std::string ToPascalCase(const std::string& s) {
std::string out;
out.reserve(s.size());
bool upper_next = true;
for (char c : s) {
if (c == '_') {
upper_next = true;
} else {
out.push_back(upper_next ? static_cast<char>(std::toupper(
static_cast<unsigned char>(c)))
: c);
upper_next = false;
}
}
return out;
}
std::string ReplaceDotsWithColons(const std::string& full_name) {
std::string out;
size_t start = 0;
while (start <= full_name.size()) {
const size_t dot = full_name.find('.', start);
const std::string part = (dot == std::string::npos)
? full_name.substr(start)
: full_name.substr(start, dot - start);
out += "::";
out += SafeIdent(part);
if (dot == std::string::npos) break;
start = dot + 1;
}
return out;
}
std::string GeneratedNamespace(const std::string& pkg) {
if (pkg.empty()) {
return kGeneratedRootNs;
}
return std::string(kGeneratedRootNs) + ReplaceDotsWithColons(pkg);
}
std::string GeneratedCppType(const std::string& full_name) {
return std::string("::") + kGeneratedRootNs +
ReplaceDotsWithColons(full_name);
}
std::string ProtoStem(const std::string& proto_name) {
if (proto_name.size() > 6 &&
proto_name.compare(proto_name.size() - 6, 6, ".proto") == 0) {
return proto_name.substr(0, proto_name.size() - 6);
}
return proto_name;
}
bool IsFieldOptionalWrapped(const FieldDescriptor* f) {
if (f->is_repeated() || f->is_map() ||
f->real_containing_oneof() != nullptr) {
return false;
}
return f->type() == FieldDescriptor::TYPE_MESSAGE || f->has_presence();
}
bool IsProto3ImplicitField(const FieldDescriptor* f) {
return !f->is_map() && !f->is_repeated() && !IsFieldOptionalWrapped(f) &&
f->real_containing_oneof() == nullptr;
}
// 3-bit WireType: field numbers 1..15 are 1-byte tags; 16..2047 are 2-byte
// tags. Both are handled on the speculative fast path via MatchConstTag.
bool HasFastTag(const FieldDescriptor* f) {
return f->number() > 0 && f->number() < 2048;
}
bool MessageUsesSizeTape(const Descriptor* msg) {
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
if (f->is_map() || f->type() == FieldDescriptor::TYPE_MESSAGE ||
f->type() == FieldDescriptor::TYPE_GROUP) {
return true;
}
if (f->is_repeated() && (f->type() == FieldDescriptor::TYPE_STRING ||
f->type() == FieldDescriptor::TYPE_BYTES)) {
return true;
}
}
return false;
}
std::string FieldResetCall(const FieldDescriptor* f) {
return std::string(kDetailNs) + "ResetField(this->" +
SafeIdent(std::string(f->name())) + ")";
}
bool IsAncestorOrSelf(const Descriptor* maybe_ancestor, const Descriptor* d) {
while (d != nullptr) {
if (d == maybe_ancestor) return true;
d = d->containing_type();
}
return false;
}
std::vector<const Descriptor*> TopoSortMessages(
const std::vector<const Descriptor*>& msgs) {
std::unordered_set<const Descriptor*> scope(msgs.begin(), msgs.end());
std::unordered_map<const Descriptor*, int> state;
std::vector<const Descriptor*> ordered;
ordered.reserve(msgs.size());
auto find_enclosing = [&](const Descriptor* d) -> const Descriptor* {
while (d != nullptr) {
if (scope.count(d) > 0) return d;
d = d->containing_type();
}
return nullptr;
};
std::function<void(const Descriptor*)> dfs = [&](const Descriptor* m) {
if (state[m] != 0) return;
state[m] = 1;
std::function<void(const Descriptor*)> scan_deps =
[&](const Descriptor* cur) {
for (int i = 0; i < cur->field_count(); ++i) {
const FieldDescriptor* f = cur->field(i);
const Descriptor* target = nullptr;
if (f->is_map()) {
const FieldDescriptor* val =
f->message_type()->map_value();
if (val->type() == FieldDescriptor::TYPE_MESSAGE) {
target = val->message_type();
} else if (val->type() == FieldDescriptor::TYPE_ENUM) {
target = val->enum_type()->containing_type();
}
} else if (f->type() == FieldDescriptor::TYPE_MESSAGE) {
target = f->message_type();
} else if (f->type() == FieldDescriptor::TYPE_ENUM) {
target = f->enum_type()->containing_type();
}
if (target != nullptr) {
const Descriptor* dep = find_enclosing(target);
if (dep != nullptr && dep != m) dfs(dep);
}
}
for (int i = 0; i < cur->nested_type_count(); ++i) {
const Descriptor* nested = cur->nested_type(i);
if (!nested->options().map_entry()) scan_deps(nested);
}
};
scan_deps(m);
state[m] = 2;
ordered.push_back(m);
};
for (const Descriptor* m : msgs) dfs(m);
return ordered;
}
// Collects all FileDescriptors (other than `root`) referenced by fields, RPC
// methods, or transitive `import public` chains (and transitively within
// google/protobuf/* WKTs).
void CollectPublicDependencies(
const FileDescriptor* file,
std::unordered_set<const FileDescriptor*>& visited_pub,
std::unordered_set<const FileDescriptor*>& visited_ref,
std::unordered_set<const FileDescriptor*>& out);
void CollectReferencedFiles(const FileDescriptor* file,
std::unordered_set<const FileDescriptor*>& visited,
std::unordered_set<const FileDescriptor*>& out) {
if (!visited.insert(file).second) return;
auto record_file = [&](const FileDescriptor* dep) {
if (dep == nullptr || dep == file) return;
out.insert(dep);
if (std::string(dep->name()).rfind("google/protobuf/", 0) == 0) {
CollectReferencedFiles(dep, visited, out);
}
};
std::function<void(const Descriptor*)> scan_msg = [&](const Descriptor* m) {
for (int i = 0; i < m->field_count(); ++i) {
const FieldDescriptor* f = m->field(i);
if (f->is_map()) {
const FieldDescriptor* val = f->message_type()->map_value();
if (val->type() == FieldDescriptor::TYPE_MESSAGE) {
record_file(val->message_type()->file());
} else if (val->type() == FieldDescriptor::TYPE_ENUM) {
record_file(val->enum_type()->file());
}
} else if (f->type() == FieldDescriptor::TYPE_MESSAGE) {
record_file(f->message_type()->file());
} else if (f->type() == FieldDescriptor::TYPE_ENUM) {
record_file(f->enum_type()->file());
}
}
for (int i = 0; i < m->nested_type_count(); ++i) {
const Descriptor* n = m->nested_type(i);
if (!n->options().map_entry()) scan_msg(n);
}
};
for (int i = 0; i < file->message_type_count(); ++i) {
scan_msg(file->message_type(i));
}
for (int i = 0; i < file->service_count(); ++i) {
const ServiceDescriptor* svc = file->service(i);
for (int j = 0; j < svc->method_count(); ++j) {
record_file(svc->method(j)->input_type()->file());
record_file(svc->method(j)->output_type()->file());
}
}
std::unordered_set<const FileDescriptor*> visited_pub;
CollectPublicDependencies(file, visited_pub, visited, out);
}
void CollectPublicDependencies(
const FileDescriptor* file,
std::unordered_set<const FileDescriptor*>& visited_pub,
std::unordered_set<const FileDescriptor*>& visited_ref,
std::unordered_set<const FileDescriptor*>& out) {
if (!visited_pub.insert(file).second) return;
for (int i = 0; i < file->public_dependency_count(); ++i) {
const FileDescriptor* pub = file->public_dependency(i);
if (pub == nullptr || pub == file) continue;
out.insert(pub);
if (std::string(pub->name()).rfind("google/protobuf/", 0) == 0) {
CollectReferencedFiles(pub, visited_ref, out);
}
CollectPublicDependencies(pub, visited_pub, visited_ref, out);
}
}
bool WriteFileAtomic(const std::filesystem::path& path,
const std::string& content) {
std::filesystem::create_directories(path.parent_path());
// Skip rewriting identical files so build timestamps stay stable.
{
std::ifstream ifs(path, std::ios::binary);
if (ifs) {
std::string existing((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
if (existing == content) {
return true;
}
}
}
const auto stamp =
std::chrono::steady_clock::now().time_since_epoch().count();
std::mt19937_64 rng(std::random_device{}() ^ static_cast<uint64_t>(stamp));
std::filesystem::path tmp = path;
tmp += ".tmp." + std::to_string(rng());
{
std::ofstream ofs(tmp, std::ios::binary | std::ios::trunc);
if (!ofs) return false;
ofs << content;
if (!ofs.good()) return false;
}
std::error_code ec;
std::filesystem::rename(tmp, path, ec);
if (ec) {
std::filesystem::remove(tmp, ec);
return false;
}
return true;
}
// ---- C++20 code generator ----
class CodeGenerator {
public:
CodeGenerator(const FileDescriptor* file, const CodegenOptions& opts,
const std::unordered_set<const FileDescriptor*>& ref_files)
: file_(file), opts_(opts), ref_files_(ref_files) {
// Compute top-level and nested emission order in post-order (children
// are emitted before their enclosing message's fields) so cyclic and
// forward references—both top-level and nested—are identified before
// emitting any struct.
std::vector<const Descriptor*> top_msgs;
top_msgs.reserve(file_->message_type_count());
for (int i = 0; i < file_->message_type_count(); ++i) {
top_msgs.push_back(file_->message_type(i));
}
ordered_top_ = TopoSortMessages(top_msgs);
size_t next_order = 0;
std::function<void(const Descriptor*)> index_msg =
[&](const Descriptor* m) {
std::vector<const Descriptor*> nested;
for (int i = 0; i < m->nested_type_count(); ++i) {
const Descriptor* n = m->nested_type(i);
if (!n->options().map_entry()) nested.push_back(n);
}
auto sorted = TopoSortMessages(nested);
for (const Descriptor* n : sorted) {
index_msg(n);
}
ordered_nested_[m] = std::move(sorted);
emit_order_[m] = next_order++;
};
for (const Descriptor* msg : ordered_top_) {
index_msg(msg);
}
}
std::string GenerateHeader() {
std::ostringstream out;
out << "// Generated by brpc_fast_codegen from " << file_->name()
<< ". DO NOT EDIT.\n"
<< "#pragma once\n\n"
<< "#include <brpc_fast/codec.h>\n";
if (file_->service_count() > 0) {
out << "#include <brpc_fast/service.h>\n";
}
out << "\n#include <cstdint>\n#include <optional>\n#include <string>\n"
"#include <unordered_map>\n#include <utility>\n"
"#include <variant>\n#include <vector>\n";
std::unordered_set<const FileDescriptor*> public_deps;
for (int i = 0; i < file_->public_dependency_count(); ++i) {
public_deps.insert(file_->public_dependency(i));
}
std::unordered_set<std::string> emitted_includes;
for (int i = 0; i < file_->dependency_count(); ++i) {
const FileDescriptor* dep = file_->dependency(i);
std::string dep_name(dep->name());
if (dep_name.rfind("google/protobuf/", 0) == 0 &&
public_deps.count(dep) == 0 && ref_files_.count(dep) == 0) {
continue;
}
if (emitted_includes.insert(dep_name).second) {
out << "#include \"" << ProtoStem(dep_name) << ".fast.h\"\n";
}
}
std::vector<std::string> extra_includes;
for (const FileDescriptor* dep : ref_files_) {
if (dep == file_) continue;
std::string dep_name(dep->name());
if (emitted_includes.count(dep_name) == 0) {
extra_includes.push_back(std::move(dep_name));
}
}
std::sort(extra_includes.begin(), extra_includes.end());
for (const std::string& dep_name : extra_includes) {
out << "#include \"" << ProtoStem(dep_name) << ".fast.h\"\n";
}
out << "\n";
EmitNamespaceOpen(out);
for (int i = 0; i < file_->enum_type_count(); ++i) {
EmitEnum(out, file_->enum_type(i), "");
out << "\n";
}
// Hoist nested enums into an internal namespace before any struct
// definitions so cyclic references between messages and nested enums
// always see complete enum types, while structs expose `using` aliases.
bool has_nested_enums = false;
for (const Descriptor* msg : ordered_top_) {
if (MessageHasNestedEnums(msg)) {
has_nested_enums = true;
break;
}
}
if (has_nested_enums) {
out << "namespace _brpc_fast_enums {\n\n";
for (const Descriptor* msg : ordered_top_) {
EmitHoistedNestedEnums(out, msg, "");
}
out << "} // namespace _brpc_fast_enums\n\n";
}
// Forward-declare all top-level messages so mutually-recursive structs
// can reference each other via IndirectOptional / IndirectBox / vector.
for (const Descriptor* msg : ordered_top_) {
out << "struct " << SafeIdent(std::string(msg->name())) << ";\n";
}
if (!ordered_top_.empty()) {
out << "\n";
}
std::vector<const Descriptor*> deferred_method_msgs;
for (const Descriptor* msg : ordered_top_) {
EmitMessage(out, msg, "", deferred_method_msgs);
out << "\n";
}
// Emit out-of-line inline method definitions for any message that had
// forward references to a later-defined sibling/mutual-cycle message.
for (const Descriptor* msg : deferred_method_msgs) {
EmitDeferredMessageMethods(out, msg);
}
for (int i = 0; i < file_->service_count(); ++i) {
EmitServiceHeader(out, file_->service(i));
out << "\n";
}
EmitNamespaceClose(out);
return out.str();
}
std::string GenerateSource() {
std::ostringstream out;
out << "// Generated by brpc_fast_codegen from " << file_->name()
<< ". DO NOT EDIT.\n"
<< "#include \"" << ProtoStem(std::string(file_->name()))
<< ".fast.h\"\n\n";
if (file_->service_count() == 0) return out.str();
EmitNamespaceOpen(out);
for (int i = 0; i < file_->service_count(); ++i) {
EmitServiceSource(out, file_->service(i));
out << "\n";
}
EmitNamespaceClose(out);
return out.str();
}
private:
// True if `target` is incomplete at the moment `enclosing_msg` is being
// laid out (self-recursion, enclosing-ancestor recursion, or a mutual cycle
// back-edge to a top-level or nested message emitted later in this file).
bool IsTargetIncomplete(const Descriptor* enclosing_msg,
const Descriptor* target) const {
if (target->file() != file_) return false;
if (IsAncestorOrSelf(target, enclosing_msg)) return true;
auto it_e = emit_order_.find(enclosing_msg);
auto it_t = emit_order_.find(target);
if (it_e != emit_order_.end() && it_t != emit_order_.end() &&
it_t->second > it_e->second) {
return true;
}
return false;
}
// True if `msg` directly references a message emitted later in the same
// file (making inline method bodies inside `struct msg` see an incomplete
// type; self-recursion alone is already complete at the closing brace).
bool NeedsDeferredMethods(const Descriptor* msg) const {
auto it_e = emit_order_.find(msg);
if (it_e == emit_order_.end()) return false;
const size_t my_ord = it_e->second;
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
const Descriptor* target = nullptr;
if (f->is_map()) {
const FieldDescriptor* val = f->message_type()->map_value();
if (val->type() == FieldDescriptor::TYPE_MESSAGE) {
target = val->message_type();
}
} else if (f->type() == FieldDescriptor::TYPE_MESSAGE) {
target = f->message_type();
}
if (target != nullptr && target->file() == file_ && target != msg) {
if (IsAncestorOrSelf(target, msg)) {
return true;
}
auto it_t = emit_order_.find(target);
if (it_t != emit_order_.end() && it_t->second > my_ord) {
return true;
}
}
}
return false;
}
std::string QualifiedInNamespace(const Descriptor* msg) const {
std::vector<std::string> parts;
for (const Descriptor* d = msg; d != nullptr;
d = d->containing_type()) {
parts.push_back(SafeIdent(std::string(d->name())));
}
std::reverse(parts.begin(), parts.end());
std::string res;
for (size_t i = 0; i < parts.size(); ++i) {
if (i > 0) res += "::";
res += parts[i];
}
return res;
}
void EmitNamespaceOpen(std::ostringstream& out) {
const std::string ns =
GeneratedNamespace(std::string(file_->package()));
out << "namespace " << ns << " {\n\n";
}
void EmitNamespaceClose(std::ostringstream& out) {
const std::string ns =
GeneratedNamespace(std::string(file_->package()));
out << "} // namespace " << ns << "\n";
}
void EmitEnum(std::ostringstream& out, const EnumDescriptor* e,
const std::string& indent) {
out << indent << "enum class " << SafeIdent(std::string(e->name()))
<< " : int32_t {\n";
for (int i = 0; i < e->value_count(); ++i) {
const auto* v = e->value(i);
out << indent << " " << SafeIdent(std::string(v->name()))
<< " = " << v->number() << ",\n";
}
out << indent << "};\n";
}
bool MessageHasNestedEnums(const Descriptor* msg) const {
if (msg->enum_type_count() > 0) return true;
for (int i = 0; i < msg->nested_type_count(); ++i) {
const Descriptor* n = msg->nested_type(i);
if (!n->options().map_entry() && MessageHasNestedEnums(n)) {
return true;
}
}
return false;
}
void EmitHoistedNestedEnums(std::ostringstream& out, const Descriptor* msg,
const std::string& indent) {
if (!MessageHasNestedEnums(msg)) return;
const std::string cls = SafeIdent(std::string(msg->name()));
out << indent << "namespace " << cls << " {\n";
for (int i = 0; i < msg->enum_type_count(); ++i) {
EmitEnum(out, msg->enum_type(i), indent);
}
for (int i = 0; i < msg->nested_type_count(); ++i) {
const Descriptor* n = msg->nested_type(i);
if (!n->options().map_entry()) {
EmitHoistedNestedEnums(out, n, indent);
}
}
out << indent << "} // namespace " << cls << "\n\n";
}
std::string HoistedEnumCppType(const EnumDescriptor* e) const {
return "::" + GeneratedNamespace(std::string(e->file()->package())) +
"::_brpc_fast_enums::" +
QualifiedInNamespace(e->containing_type()) +
"::" + SafeIdent(std::string(e->name()));
}
std::string EnumCppType(const Descriptor* enclosing_msg,
const EnumDescriptor* e) const {
if (e->file() == file_ && e->containing_type() != nullptr &&
IsTargetIncomplete(enclosing_msg, e->containing_type())) {
return HoistedEnumCppType(e);
}
return GeneratedCppType(std::string(e->full_name()));
}
std::string FieldCppType(const Descriptor* enclosing_msg,
const FieldDescriptor* f) const {
switch (f->type()) {
case FieldDescriptor::TYPE_BOOL:
return "bool";
case FieldDescriptor::TYPE_INT32:
case FieldDescriptor::TYPE_SINT32:
case FieldDescriptor::TYPE_SFIXED32:
return "int32_t";
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_FIXED32:
return "uint32_t";
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_SFIXED64:
return "int64_t";
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_FIXED64:
return "uint64_t";
case FieldDescriptor::TYPE_FLOAT:
return "float";
case FieldDescriptor::TYPE_DOUBLE:
return "double";
case FieldDescriptor::TYPE_STRING:
case FieldDescriptor::TYPE_BYTES:
return "std::string";
case FieldDescriptor::TYPE_ENUM:
return EnumCppType(enclosing_msg, f->enum_type());
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_GROUP:
return GeneratedCppType(
std::string(f->message_type()->full_name()));
}
return "/*unsupported*/";
}
std::string FieldDefaultExpr(const Descriptor* enclosing_msg,
const FieldDescriptor* f) const {
switch (f->type()) {
case FieldDescriptor::TYPE_BOOL:
return "false";
case FieldDescriptor::TYPE_INT32:
case FieldDescriptor::TYPE_SINT32:
case FieldDescriptor::TYPE_SFIXED32:
return "0";
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_FIXED32:
return "0u";
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_SFIXED64:
return "0";
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_FIXED64:
return "0u";
case FieldDescriptor::TYPE_FLOAT:
return "0.0f";
case FieldDescriptor::TYPE_DOUBLE:
return "0.0";
case FieldDescriptor::TYPE_ENUM:
return EnumCppType(enclosing_msg, f->enum_type()) + "::" +
SafeIdent(std::string(f->enum_type()->value(0)->name()));
default:
return "";
}
}
void EmitMessage(std::ostringstream& out, const Descriptor* msg,
const std::string& indent,
std::vector<const Descriptor*>& deferred_method_msgs) {
const std::string cls = SafeIdent(std::string(msg->name()));
const std::string inner = indent + " ";
const bool defer = NeedsDeferredMethods(msg);
if (defer) {
deferred_method_msgs.push_back(msg);
}
out << indent << "struct " << cls << " {\n";
for (int i = 0; i < msg->enum_type_count(); ++i) {
const EnumDescriptor* e = msg->enum_type(i);
out << inner << "using " << SafeIdent(std::string(e->name()))
<< " = " << HoistedEnumCppType(e) << ";\n";
}
if (msg->enum_type_count() > 0) {
out << "\n";
}
const auto& nested_msgs = ordered_nested_.at(msg);
for (const Descriptor* n : nested_msgs) {
out << inner << "struct " << SafeIdent(std::string(n->name()))
<< ";\n";
}
if (!nested_msgs.empty()) {
out << "\n";
}
for (const Descriptor* n : nested_msgs) {
EmitMessage(out, n, inner, deferred_method_msgs);
out << "\n";
}
EmitOneofs(out, msg, inner, defer);
EmitFields(out, msg, inner);
if (opts_.preserve_unknown_fields) {
out << inner << kDetailNs
<< "UnknownFieldBuffer _unknown_fields;\n";
}
out << "\n";
if (defer) {
out << inner << "bool operator==(const " << cls << "&) const;\n\n";
out << inner << "static constexpr bool kUsesSizeTape = "
<< (MessageUsesSizeTape(msg) ? "true" : "false") << ";\n\n"
<< inner << "void Clear();\n"
<< inner << "size_t ComputeSize(" << kDetailNs
<< "SizeTape& tape) const;\n"
<< inner
<< "uint8_t* EncodeUnchecked(uint8_t* dst, const uint32_t*& "
"tape) const noexcept;\n"
<< inner
<< "bool DecodeContiguous(const uint8_t* cur, const uint8_t* "
"end, int remaining_depth);\n"
<< inner << "template <bool Overwrite>\n"
<< inner << "BRPC_FAST_NOINLINE bool DecodeLoop(" << kDetailNs
<< "FastReader& r);\n"
<< inner << "bool Decode(" << kDetailNs << "FastReader& r);\n"
<< inner << "bool EncodeTo(::butil::IOBuf* out) const;\n"
<< inner << "bool DecodeFrom(const ::butil::IOBuf& in);\n";
} else {
out << inner << "bool operator==(const " << cls
<< "&) const = default;\n\n";
EmitClearBody(out, msg, inner, "");
EmitEncodeBodies(out, msg, inner, "");
EmitDecodeBodies(out, msg, inner, "");
out << inner
<< "bool EncodeTo(::butil::IOBuf* out) const { return "
"::brpc_fast::EncodeToIOBuf(*this, out); }\n"
<< inner
<< "bool DecodeFrom(const ::butil::IOBuf& in) { return "
"::brpc_fast::DecodeFromIOBuf(in, *this); }\n";
}
out << indent << "};\n";
}
void EmitDeferredMessageMethods(std::ostringstream& out,
const Descriptor* msg) {
const std::string qcls = QualifiedInNamespace(msg);
for (int i = 0; i < msg->real_oneof_decl_count(); ++i) {
const OneofDescriptor* oneof = msg->oneof_decl(i);
const std::string oname = SafeIdent(std::string(oneof->name()));
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* f = oneof->field(j);
if (!IsOneofBranchIndirect(msg, f)) continue;
const std::string ftype = FieldCppType(msg, f);
const int idx = j + 1;
out << "inline " << ftype << "& " << qcls << "::mutable_"
<< f->name() << "() {\n"
<< " if (this->" << oname << ".index() != " << idx
<< ") { this->" << oname << ".emplace<" << idx << ">(); }\n"
<< " return std::get<" << idx << ">(this->" << oname
<< ").get();\n"
<< "}\n\n";
}
}
out << "inline bool " << qcls << "::operator==(const " << qcls
<< "&) const = default;\n\n";
EmitClearBody(out, msg, "", qcls + "::");
EmitEncodeBodies(out, msg, "", qcls + "::");
EmitDecodeBodies(out, msg, "", qcls + "::");
out << "inline bool " << qcls
<< "::EncodeTo(::butil::IOBuf* out) const { return "
"::brpc_fast::EncodeToIOBuf(*this, out); }\n"
<< "inline bool " << qcls
<< "::DecodeFrom(const ::butil::IOBuf& in) { return "
"::brpc_fast::DecodeFromIOBuf(in, *this); }\n\n";
}
bool IsOneofBranchIndirect(const Descriptor* msg,
const FieldDescriptor* f) const {
return f->type() == FieldDescriptor::TYPE_MESSAGE &&
IsTargetIncomplete(msg, f->message_type());
}
std::string OneofVariantType(const Descriptor* msg,
const FieldDescriptor* f) const {
const std::string ftype = FieldCppType(msg, f);
if (IsOneofBranchIndirect(msg, f)) {
return "::brpc_fast::IndirectBox<" + ftype + ">";
}
return ftype;
}
void EmitOneofs(std::ostringstream& out, const Descriptor* msg,
const std::string& inner, bool defer) {
for (int i = 0; i < msg->real_oneof_decl_count(); ++i) {
const OneofDescriptor* oneof = msg->oneof_decl(i);
const std::string oname = SafeIdent(std::string(oneof->name()));
const std::string cenum =
ToPascalCase(std::string(oneof->name())) + "Case";
out << inner << "enum class " << cenum << " : uint32_t {\n"
<< inner << " kNotSet = 0,\n";
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* f = oneof->field(j);
out << inner << " k" << ToPascalCase(std::string(f->name()))
<< " = " << f->number() << ",\n";
}
out << inner << "};\n" << inner << "std::variant<std::monostate";
for (int j = 0; j < oneof->field_count(); ++j) {
out << ", " << OneofVariantType(msg, oneof->field(j));
}
out << "> " << oname << ";\n";
out << inner << cenum << " " << oname
<< "_case() const noexcept {\n"
<< inner << " switch (this->" << oname << ".index()) {\n";
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* f = oneof->field(j);
out << inner << " case " << (j + 1) << ": return "
<< cenum << "::k" << ToPascalCase(std::string(f->name()))
<< ";\n";
}
out << inner << " default: return " << cenum
<< "::kNotSet;\n"
<< inner << " }\n"
<< inner << "}\n";
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* f = oneof->field(j);
const std::string fname = SafeIdent(std::string(f->name()));
const std::string ftype = FieldCppType(msg, f);
const bool indirect = IsOneofBranchIndirect(msg, f);
const std::string deref = indirect ? ".get()" : "";
const int idx = j + 1;
out << inner << "bool has_" << f->name()
<< "() const noexcept { return this->" << oname
<< ".index() == " << idx << "; }\n"
<< inner << "const " << ftype << "& " << fname
<< "() const { return std::get<" << idx << ">(this->"
<< oname << ")" << deref << "; }\n";
if (defer && indirect) {
out << inner << ftype << "& mutable_" << f->name()
<< "();\n";
} else {
out << inner << ftype << "& mutable_" << f->name()
<< "() {\n"
<< inner << " if (this->" << oname
<< ".index() != " << idx << ") { this->" << oname
<< ".emplace<" << idx << ">(); }\n"
<< inner << " return std::get<" << idx << ">(this->"
<< oname << ")" << deref << ";\n"
<< inner << "}\n";
}
out << inner << "template <typename... Args>\n"
<< inner << ftype << "& emplace_" << f->name()
<< "(Args&&... args) {\n"
<< inner << " return this->" << oname << ".emplace<"
<< idx << ">(std::forward<Args>(args)...)" << deref << ";\n"
<< inner << "}\n";
}
out << "\n";
}
}
void EmitFields(std::ostringstream& out, const Descriptor* msg,
const std::string& inner) {
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
if (f->real_containing_oneof() != nullptr) continue;
const std::string fname = SafeIdent(std::string(f->name()));
if (f->is_map()) {
const Descriptor* entry = f->message_type();
const FieldDescriptor* val = entry->map_value();
std::string vtype = FieldCppType(msg, val);
if (val->type() == FieldDescriptor::TYPE_MESSAGE &&
IsTargetIncomplete(msg, val->message_type())) {
vtype = "::brpc_fast::IndirectBox<" + vtype + ">";
}
out << inner << "std::unordered_map<"
<< FieldCppType(msg, entry->map_key()) << ", " << vtype
<< "> " << fname << ";\n";
} else if (f->is_repeated()) {
out << inner << "std::vector<" << FieldCppType(msg, f) << "> "
<< fname << ";\n";
} else if (IsFieldOptionalWrapped(f)) {
const bool indirect =
f->type() == FieldDescriptor::TYPE_MESSAGE &&
IsTargetIncomplete(msg, f->message_type());
out << inner
<< (indirect ? "::brpc_fast::IndirectOptional<"
: "std::optional<")
<< FieldCppType(msg, f) << "> " << fname << ";\n";
} else {
const std::string ftype = FieldCppType(msg, f);
const std::string def = FieldDefaultExpr(msg, f);
out << inner << ftype << " " << fname
<< (def.empty() ? "" : (" = " + def)) << ";\n";
}
}
}
void EmitClearBody(std::ostringstream& out, const Descriptor* msg,
const std::string& inner, const std::string& qual) {
const std::string prefix = qual.empty() ? "" : "inline ";
out << inner << prefix << "void " << qual << "Clear() {\n";
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
if (f->real_containing_oneof() == nullptr) {
out << inner << " " << FieldResetCall(f) << ";\n";
}
}
for (int i = 0; i < msg->real_oneof_decl_count(); ++i) {
out << inner << " this->"
<< SafeIdent(std::string(msg->oneof_decl(i)->name()))
<< ".emplace<0>();\n";
}
if (opts_.preserve_unknown_fields) {
out << inner << " this->_unknown_fields.Clear();\n";
}
out << inner << "}\n\n";
}
void EmitEncodeBodies(std::ostringstream& out, const Descriptor* msg,
const std::string& inner, const std::string& qual) {
const std::string prefix = qual.empty() ? "" : "inline ";
if (qual.empty()) {
out << inner << "static constexpr bool kUsesSizeTape = "
<< (MessageUsesSizeTape(msg) ? "true" : "false") << ";\n\n";
}
// Pass 1: ComputeSize
out << inner << prefix << "size_t " << qual << "ComputeSize("
<< kDetailNs << "SizeTape& tape) const {\n"
<< inner << " (void)tape;\n"
<< inner << " size_t sz = 0;\n";
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
if (f->real_containing_oneof() != nullptr) continue;
out << inner << " sz += " << kDetailNs << "SizeField<"
<< f->number() << "u, "
<< (IsProto3ImplicitField(f) ? "true" : "false") << ">(this->"
<< SafeIdent(std::string(f->name())) << ", tape);\n";
}
for (int i = 0; i < msg->real_oneof_decl_count(); ++i) {
const OneofDescriptor* oneof = msg->oneof_decl(i);
const std::string oname = SafeIdent(std::string(oneof->name()));
out << inner << " switch (this->" << oname << ".index()) {\n";
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* f = oneof->field(j);
out << inner << " case " << (j + 1)
<< ": sz += " << kDetailNs << "SizeField<" << f->number()
<< "u>(std::get<" << (j + 1) << ">(this->" << oname
<< "), tape); break;\n";
}
out << inner << " default: break;\n" << inner << " }\n";
}
if (opts_.preserve_unknown_fields) {
out << inner << " sz += this->_unknown_fields.Size();\n";
}
out << inner << " return sz;\n" << inner << "}\n\n";
// Pass 2: EncodeUnchecked
out << inner << prefix << "uint8_t* " << qual
<< "EncodeUnchecked(uint8_t* dst, const uint32_t*& tape) "
"const noexcept {\n"
<< inner << " (void)tape;\n";
for (int i = 0; i < msg->field_count(); ++i) {
const FieldDescriptor* f = msg->field(i);
if (f->real_containing_oneof() != nullptr) continue;
out << inner << " dst = " << kDetailNs << "EncodeFieldUnchecked<"
<< f->number() << "u, "
<< (IsProto3ImplicitField(f) ? "true" : "false")
<< ">(dst, this->" << SafeIdent(std::string(f->name()))
<< ", tape);\n";