-
Notifications
You must be signed in to change notification settings - Fork 644
Expand file tree
/
Copy patht_mstch_cpp2_generator.cc
More file actions
2782 lines (2584 loc) · 106 KB
/
Copy patht_mstch_cpp2_generator.cc
File metadata and controls
2782 lines (2584 loc) · 106 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <cassert>
#include <filesystem>
#include <memory>
#include <queue>
#include <unordered_map>
#include <utility>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <fmt/format.h>
#include <thrift/compiler/ast/t_const.h>
#include <thrift/compiler/ast/t_field.h>
#include <thrift/compiler/ast/t_list.h>
#include <thrift/compiler/ast/t_map.h>
#include <thrift/compiler/ast/t_set.h>
#include <thrift/compiler/ast/type_visitor.h>
#include <thrift/compiler/ast/uri.h>
#include <thrift/compiler/generate/common.h>
#include <thrift/compiler/generate/cpp/name_resolver.h>
#include <thrift/compiler/generate/cpp/orderable_type_utils.h>
#include <thrift/compiler/generate/cpp/util.h>
#include <thrift/compiler/generate/t_whisker_generator.h>
#include <thrift/compiler/generate/templates.h>
#include <thrift/compiler/sema/ast_validator.h>
#include <thrift/compiler/sema/schematizer.h>
#include <thrift/compiler/sema/sema_context.h>
#include <thrift/compiler/sema/standard_validator.h>
namespace apache::thrift::compiler {
namespace {
using compiler_options_map = std::map<std::string, std::string, std::less<>>;
using apache::thrift::compiler::detail::schematizer;
// A compiler counterpart of cpp.EnumUnderlyingType that avoids dependency on
// the generated code and follows the compiler naming conventions.
enum class enum_underlying_type {
i8 = 0,
u8 = 1,
i16 = 2,
u16 = 3,
u32 = 4,
};
// A "rendered" type/value is a thin wrapper that carries the field context
// needed for field-aware C++ type resolution. When a field has a @cpp.Type
// annotation, the resolved C++ type differs from the underlying t_type's
// default — these wrappers allow templates to access both the field-aware
// type (via cpp_type / cpp_standard_type) and the underlying t_type's
// properties (via the "type" property) without mutating the shared AST node.
struct cpp2_rendered_type {
const t_type* type = nullptr;
const t_field* field = nullptr;
const t_structured* parent = nullptr;
};
struct cpp2_rendered_const_value {
const t_const_value* value = nullptr;
const t_type* expected_type = nullptr;
const t_field* field = nullptr;
const t_structured* parent = nullptr;
};
std::string_view get_field_cpp_type_property(
const t_field* field, const char* key) {
if (field == nullptr) {
return "";
}
if (const auto* annot =
field->find_structured_annotation_or_null(kCppTypeUri);
annot != nullptr) {
if (const auto* value =
annot->get_value_from_structured_annotation_or_null(key)) {
return value->get_string();
}
}
return "";
}
bool has_field_cpp_type_annotation(const t_field* field) {
return field != nullptr &&
field->find_structured_annotation_or_null(kCppTypeUri) != nullptr;
}
std::string_view get_cpp_type_name_with_field_override(
const t_type* type, const t_field* field = nullptr) {
if (auto value = get_field_cpp_type_property(field, "name"); !value.empty()) {
return value;
}
if (type != nullptr) {
if (const auto* value = cpp_name_resolver::find_type(*type)) {
return *value;
}
}
return "";
}
std::string_view get_cpp_template_with_field_override(
const t_type* type, const t_field* field = nullptr) {
if (auto value = get_field_cpp_type_property(field, "template");
!value.empty()) {
return value;
}
if (type != nullptr) {
if (const auto* value = cpp_name_resolver::find_template(*type)) {
return *value;
}
}
return "";
}
bool is_complex_return(const t_type* type) {
return type->is<t_container>() || type->is_string_or_binary() ||
type->is<t_structured>();
}
const t_type* get_effective_type(const cpp2_rendered_const_value& value) {
if (value.expected_type != nullptr) {
return value.expected_type;
}
if (!value.value->type().empty()) {
return &value.value->type().deref();
}
if (value.value->get_owner() != nullptr) {
return value.value->get_owner()->type();
}
return nullptr;
}
bool same_types_with_field_override(
const t_type* a, const t_type* b, const t_field* a_field = nullptr) {
if (!a || !b) {
return false;
}
if (get_cpp_template_with_field_override(a, a_field) !=
get_cpp_template_with_field_override(b) ||
get_cpp_type_name_with_field_override(a, a_field) !=
get_cpp_type_name_with_field_override(b) ||
cpp2::get_type(a) != cpp2::get_type(b)) {
return false;
}
const auto* resolved_a = a->get_true_type();
const auto* resolved_b = b->get_true_type();
// Check if both types are the same kind and for primitives, the same type
if (const t_primitive_type *prim_a = resolved_a->try_as<t_primitive_type>(),
*prim_b = resolved_b->try_as<t_primitive_type>();
prim_a != nullptr && prim_b != nullptr) {
// Both are primitives, check they are the same primitive type
if (prim_a->primitive_type() != prim_b->primitive_type()) {
return false;
}
} else if (typeid(*resolved_a) != typeid(*resolved_b)) {
// Use typeid for other types to check they are the same kind
return false;
}
if (const t_list* list_a = resolved_a->try_as<t_list>()) {
const auto* list_b = static_cast<const t_list*>(resolved_b);
return same_types_with_field_override(
&list_a->elem_type().deref(), &list_b->elem_type().deref());
} else if (const t_set* set_a = resolved_a->try_as<t_set>()) {
const auto* set_b = static_cast<const t_set*>(resolved_b);
return same_types_with_field_override(
&set_a->elem_type().deref(), &set_b->elem_type().deref());
} else if (const t_map* map_a = resolved_a->try_as<t_map>()) {
const auto* map_b = static_cast<const t_map*>(resolved_b);
return same_types_with_field_override(
&map_a->key_type().deref(), &map_b->key_type().deref()) &&
same_types_with_field_override(
&map_a->val_type().deref(), &map_b->val_type().deref());
}
return true;
}
std::string get_out_dir_base(const compiler_options_map& options) {
return options.contains("py3cpp") ? "gen-py3cpp" : "gen-cpp2";
}
std::string mangle_field_name(const std::string& name) {
return fmt::format("__fbthrift_field_{}", name);
}
bool should_mangle_field_storage_name_in_struct(const t_structured& s) {
// We don't mangle field name if cpp.methods exist
return !s.has_unstructured_annotation("cpp.methods");
}
bool resolves_to_container_or_struct(const t_type* type) {
return type->is<t_container>() || type->is<t_structured>();
}
bool generate_reduced_client(const t_interface& i) {
return i.is<t_interaction>();
}
template <class Comp>
const std::string& get_extremal_union_member(const t_union& u) {
Comp comp;
auto iter = std::min_element(
u.fields().cbegin(),
u.fields().cend(),
[&comp](const t_field& a, const t_field& b) {
return comp(a.id(), b.id());
});
if (iter == u.fields().cend()) {
throw std::runtime_error("empty union struct");
}
return cpp2::get_name(&*iter);
}
// Compute the set of types that appear anywhere in the service
// definition as input or output types. This presents maps, lists etc as seen
// in declarations, but unpacks the payloads of sinks and streams.
whisker::array::ptr build_user_type_footprint(
const t_service& service,
const whisker::prototype_database& prototype_database) {
std::vector<const t_type*> types;
std::unordered_set<const t_type*> seen;
// Helper to extract the necessary types from a single type identified in
// some component of a method declaration. Deals with maps, lists, streams
// that surround actual types.
auto extract_type = [&](const t_type* type) -> void {
// Maintain insertion order for stable output.
// Insert into types in order of detection (parsing), use "seen"
// to avoid duplicates.
if (seen.count(type) == 0) {
types.emplace_back(type);
seen.insert(type);
}
};
// Go through each method declaration and identfiy the places that could
// contain user defined types.
std::deque<const t_function*> pending;
for (const auto& function : service.functions()) {
pending.emplace_back(&function);
}
while (!pending.empty()) {
const auto& function = *pending.front();
pending.erase(pending.begin());
for (const auto& param : function.params().fields()) {
extract_type(¶m.type().deref());
}
if (const auto& excs = function.exceptions();
!t_throws::is_null_or_empty(excs)) {
for (auto& ex : excs->fields()) {
extract_type(&ex.type().deref());
}
}
extract_type(&function.return_type().deref());
if (!function.interaction().empty()) {
const auto& interaction =
function.interaction()->get_true_type()->as<t_interaction>();
for (const auto& intfunc : interaction.functions()) {
pending.emplace_back(&intfunc);
}
continue;
}
if (function.sink()) {
extract_type(&function.sink()->elem_type().deref());
if (!function.sink()->final_response_type().empty()) {
extract_type(&function.sink()->final_response_type().deref());
}
}
if (function.stream()) {
extract_type(&function.stream()->elem_type().deref());
}
}
whisker::array::raw ret;
for (const t_type* typeptr : types) {
// This line below should be this:
// auto obj = resolve_derived_t_type(prototype_database, *typeptr);
//
// resolve_derived_t_type() does not produce the correct result for
// right now - the right result being a match of the type names
// used in service stub definitions, due to problems with inconsistent
// behavior of the cpp_type property across different implementations/types.
auto obj = prototype_database.create<t_type>(*typeptr);
ret.emplace_back(std::move(obj));
}
return whisker::array::of(std::move(ret));
}
// Program's transitive_schema_includes depends on consistent order.
struct program_less {
bool operator()(const t_program* a, const t_program* b) const {
return a->path() < b->path();
}
};
/**
* Collect all transitive includes of a program into a sorted set, excluding
* programs with the `DisableSchemaConst` annotation.
*/
void collect_transitive_includes(
const t_program& program,
std::set<const t_program*, program_less>& result) {
for (const t_program* include : program.get_includes_for_codegen()) {
if (include->has_structured_annotation(kDisableSchemaConstUri)) {
continue;
}
if (result.insert(include).second) {
collect_transitive_includes(*include, result);
}
}
}
/**
* To reduce build time, the generated constants code only includes the
* headers for direct thrift includes in the .cpp file and not in the .h file,
* which means constants from transitive includes are not visible. To allow
* constructing a flattened array of schemas for transitive dependencies
* without undoing this optimization we indirect through the flattened array
* of one of the direct includes to reach the schema of the transitive
* include.
*
* This builds the information for how we will access the schema for all of
* the transitive dependencies of a program. Each entry has:
* - program: the included program
* - schema_provider_program: the program whose _includes array provides access
* (equals the root program for direct includes)
* - schema_index: 0-based position within the provider's sorted transitive
* include set (template accounts for each program's own schema being
* inserted at 0)
*/
whisker::object program_transitive_schema_includes(
const t_program& program, const whisker::prototype_database& proto) {
// Accumulate the full set of transitive schema includes in a stable order
std::map<const t_program*, whisker::object, program_less> items;
for (const t_program* include : program.get_includes_for_codegen()) {
if (include->has_structured_annotation(kDisableSchemaConstUri)) {
continue;
}
// Direct include: schema_provider_program is the root program itself.
items.emplace(
include,
whisker::map::of({
{"program",
whisker::make::native_handle(proto.create<t_program>(*include))},
{"schema_provider_program",
whisker::make::native_handle(proto.create<t_program>(program))},
{"schema_index", whisker::make::null},
}));
// Get all transitive includes of this direct include (sorted by path).
// The index within this sorted set determines the position in the
// corresponding _includes array
std::set<const t_program*, program_less> transitive_includes;
collect_transitive_includes(*include, transitive_includes);
int64_t i = 0;
for (const t_program* transitive : transitive_includes) {
if (!items.contains(transitive)) {
items.emplace(
transitive,
whisker::map::of({
{"program",
whisker::make::native_handle(
proto.create<t_program>(*transitive))},
{"schema_provider_program",
whisker::make::native_handle(
proto.create<t_program>(*include))},
{"schema_index", whisker::make::i64(i)},
}));
}
++i;
}
}
whisker::array::raw result;
result.reserve(items.size());
for (auto& [_, item] : items) {
result.emplace_back(std::move(item));
}
return whisker::make::array(std::move(result));
}
struct cpp2_field_generator_context {
const t_field* serialization_prev = nullptr;
const t_field* serialization_next = nullptr;
int isset_index = -1;
};
std::vector<const t_field*> get_structured_fields_in_layout_order(
const t_structured& strct);
/**
* Check fields for the meeting any of the following criteria:
* All enums
* All primitives except empty strings
* All non-empty structs and containers
* All non-optional references with basetypes, enums, non-empty structs, and
* containers
*/
bool is_field_explicitly_constructed(
const t_field& field, const t_structured& parent_struct) {
const t_type* type = field.type()->get_true_type();
if (cpp2::is_explicit_ref(&field) &&
field.qualifier() == t_field_qualifier::optional) {
return false;
}
if (type->is<t_enum>()) {
return true;
}
if (type->is<t_primitive_type>()) {
return !type->is_string_or_binary() || field.default_value() != nullptr ||
cpp2::is_explicit_ref(&field);
}
if (type->is<t_struct>() || type->is<t_union>()) {
return type != &parent_struct &&
(cpp2::is_explicit_ref(&field) ||
(field.default_value() != nullptr &&
!field.default_value()->is_empty()));
}
if (type->is<t_container>()) {
return cpp2::is_explicit_ref(&field) ||
(field.default_value() != nullptr &&
!field.default_value()->is_empty());
}
return false;
}
class cpp2_generator_context {
public:
explicit cpp2_generator_context(
source_manager& sm, const t_program* root, int program_split_count)
: root_program_{root} {
root_program_has_schema_const_ =
root_program_->find(
{schematizer::schema_const_name(sm, *root_program_),
source_range{}}) != nullptr;
if (program_split_count > 0) {
program_structured_definition_splits_ = cpp2::lpt_split(
root->structured_definitions(), program_split_count, [](auto t) {
return t->fields().size();
});
}
// Compute topologically sorted structured definitions and typedefs for the
// root program. We combine these because the adapter trait used in typedefs
// requires the typedefed struct to be complete, and the typedefs themselves
// cannot be forward declared. Topo sort the combined set to fulfill these
// requirements.
{
std::vector<const t_type*> nodes;
nodes.reserve(
root->structured_definitions().size() + root->typedefs().size());
nodes.insert(
nodes.end(), root->typedefs().begin(), root->typedefs().end());
nodes.insert(
nodes.end(),
root->structured_definitions().begin(),
root->structured_definitions().end());
type_definitions_topological_order_ =
cpp2::topological_sort<const t_type*>(
nodes.begin(),
nodes.end(),
/*edges=*/cpp2::gen_dependency_graph(root, nodes),
/*throwOnCycle=*/true);
}
}
bool is_orderable(const t_structured& structured_type) {
return cpp2::OrderableTypeUtils::is_orderable(
is_orderable_memo_, structured_type);
}
cpp_name_resolver& resolver() { return resolver_; }
const cpp2_field_generator_context* get_field_context(
const t_field* field) const {
auto it = field_context_map_.find(field);
return it == field_context_map_.end() ? nullptr : &it->second;
}
/**
* The set of included programs whose constants are referenced for field
* default values in the root program. These programs' `module_constants.h`
* needs to be included in the root program's `module_types.h` for const
* referencing.
*/
const std::unordered_set<const t_program*>& field_default_const_ref_programs()
const {
return field_default_const_ref_programs_;
}
bool has_schema_const(const t_program& program) const {
check_root_program(program);
return root_program_has_schema_const_;
}
bool has_sink_functions(const t_program& program) const {
check_root_program(program);
return root_program_has_sink_functions_;
}
bool has_stream_functions(const t_program& program) const {
check_root_program(program);
return root_program_has_stream_functions_;
}
bool has_interaction_functions(const t_program& program) const {
check_root_program(program);
return root_program_has_interaction_functions_;
}
bool has_method_decorators(const t_program& program) const {
check_root_program(program);
return root_program_has_method_decorators_;
}
const std::vector<const t_field*>& fields_in_layout_order(
const t_structured& strct) const {
check_root_program(*strct.program());
auto it = fields_in_layout_order_.find(&strct);
assert(it != fields_in_layout_order_.end());
return it->second;
}
/**
* Structured definitions and typedefs defined by the program, in topological
* order.
*/
const std::vector<const t_type*>& type_definitions_topological_order(
const t_program& program) const {
check_root_program(program);
return type_definitions_topological_order_;
}
// --- Program split state ---
void set_program_split(int32_t split_id) {
assert(!program_structured_definition_splits_.empty());
program_split_id_ = split_id;
}
void clear_program_split() { program_split_id_ = std::nullopt; }
std::optional<int32_t> program_split_id() const { return program_split_id_; }
const std::vector<t_structured*>&
program_current_split_structured_definitions() const {
assert(program_split_id_.has_value());
return program_structured_definition_splits_.at(*program_split_id_);
}
std::vector<const t_enum*> program_current_split_enums() const {
assert(program_split_id_.has_value());
std::vector<const t_enum*> split;
size_t split_count = program_structured_definition_splits_.size();
for (size_t i = *program_split_id_; i < root_program_->enums().size();
i += split_count) {
split.emplace_back(root_program_->enums()[i]);
}
return split;
}
// --- Service split state ---
void set_service_split(int32_t split_id, int32_t split_count) {
current_service_split_id_ = split_id;
current_service_split_count_ = split_count;
}
void clear_service_split() {
current_service_split_id_ = 0;
current_service_split_count_ = 1;
}
int32_t current_service_split_id() const { return current_service_split_id_; }
int32_t current_service_split_count() const {
return current_service_split_count_;
}
void register_visitors(t_whisker_generator::context_visitor& visitor) {
using context = t_whisker_generator::whisker_generator_visitor_context;
// Compute field isset indexes and serialization order, which requires a
// back-reference to the parent structured definition. Not using field
// visitor here, since it requires forward/backward context.
visitor.add_structured_definition_visitor(
[this](const context& ctx, const t_structured& node) {
if (&ctx.program() == root_program_) {
fields_in_layout_order_[&node] =
get_structured_fields_in_layout_order(node);
}
cpp2_field_generator_context field_ctx;
for (const t_field& field : node.fields()) {
if (cpp2::field_has_isset(&field)) {
field_ctx.isset_index++;
}
field_context_map_[&field] = field_ctx;
}
if (node.has_structured_annotation(kSerializeInFieldIdOrderUri)) {
const t_field* prev = nullptr;
for (const t_field* curr : node.fields_id_order()) {
if (prev != nullptr) {
field_context_map_[prev].serialization_next = curr;
field_context_map_[curr].serialization_prev = prev;
}
prev = curr;
}
} else {
const t_field* prev = nullptr;
for (const t_field& curr : node.fields()) {
if (prev != nullptr) {
field_context_map_[prev].serialization_next = &curr;
field_context_map_[&curr].serialization_prev = prev;
}
prev = &curr;
}
}
});
visitor.add_field_visitor([this](const context& ctx, const t_field& node) {
if (node.default_value() == nullptr || &ctx.program() != root_program_) {
return;
}
// If this field is in our root program and its default value is a
// constant from an included program, track it so we can include the
// corresponding `module_constants.h` in `module_types.h`
const t_program* const_program =
node.default_value()->get_owner() == nullptr
? nullptr
: node.default_value()->get_owner()->program();
if (const_program != nullptr && const_program != root_program_) {
field_default_const_ref_programs_.emplace(const_program);
}
});
visitor.add_service_visitor(
[this](const context& ctx, const t_service& service) {
if (&ctx.program() == root_program_) {
root_program_has_method_decorators_ |=
service.has_structured_annotation(
kCppGenerateServiceMethodDecorator);
}
});
visitor.add_function_visitor(
[this](const context& ctx, const t_function& func) {
if (&ctx.program() != root_program_ ||
dynamic_cast<const t_interaction*>(ctx.parent()) != nullptr) {
// Only take service functions from the root program
return;
}
root_program_has_sink_functions_ |= func.sink() != nullptr;
root_program_has_stream_functions_ |= func.stream() != nullptr;
root_program_has_interaction_functions_ |=
func.is_interaction_constructor() || !func.interaction().empty();
});
}
private:
const t_program* root_program_;
std::unordered_map<const t_type*, bool> is_orderable_memo_;
cpp_name_resolver resolver_;
bool root_program_has_schema_const_;
bool root_program_has_sink_functions_{false};
bool root_program_has_stream_functions_{false};
bool root_program_has_interaction_functions_{false};
bool root_program_has_method_decorators_{false};
// Although generator fields can be in a different order than the IDL
// order, field_generator_context should be always computed in the IDL order,
// as the context does not change by reordering. Without the map, each
// different reordering recomputes field_generator_context, and each
// field takes O(N) to loop through node_list_view<t_field> or
// std::vector<t_field*> to find the exact t_field to compute
// field_generator_context.
std::unordered_map<const t_field*, cpp2_field_generator_context>
field_context_map_;
std::unordered_set<const t_program*> field_default_const_ref_programs_;
std::unordered_map<const t_structured*, std::vector<const t_field*>>
fields_in_layout_order_;
std::vector<const t_type*> type_definitions_topological_order_;
// Program split: LPT-partitioned structured definitions
std::vector<std::vector<t_structured*>> program_structured_definition_splits_;
// Current program split ID, set per loop iteration in generate_structs.
std::optional<int32_t> program_split_id_;
// Current service split state, set per loop iteration in
// generate_out_of_line_service
int32_t current_service_split_id_ = 0;
int32_t current_service_split_count_ = 1;
void check_root_program(const t_program& program) const {
if (&program != root_program_) {
throw whisker::eval_error(
"This property is only implemented for the root program");
}
}
};
int checked_stoi(const std::string& s, const std::string& msg) {
std::size_t pos = 0;
int ret = std::stoi(s, &pos);
if (pos != s.size()) {
throw std::runtime_error(msg);
}
return ret;
}
int get_split_count(const compiler_options_map& options) {
auto iter = options.find("types_cpp_splits");
if (iter == options.end()) {
return 0;
}
return checked_stoi(
iter->second, "Invalid types_cpp_splits value: `" + iter->second + "`");
}
bool needs_op_encode(const t_type& type);
bool field_needs_op_encode(const t_field& field, const t_structured& strct);
bool is_zero_copy_arg(const t_type& type) {
const auto& true_type = *type.get_true_type();
if (true_type.is_binary() || true_type.is<t_structured>()) {
return true;
} else if (const t_list* list = true_type.try_as<t_list>()) {
return is_zero_copy_arg(*list->elem_type());
} else if (const t_set* set = true_type.try_as<t_set>()) {
return is_zero_copy_arg(*set->elem_type());
} else if (const t_map* map = true_type.try_as<t_map>()) {
return is_zero_copy_arg(map->key_type().deref()) ||
is_zero_copy_arg(map->val_type().deref());
}
return false;
}
bool is_field_private(
const t_field& field, bool deprecated_public_required_fields) {
// Lazy and cpp.ref fields are always private.
if (cpp2::is_lazy(&field) || cpp2::is_ref(&field)) {
return true;
}
if (field.qualifier() == t_field_qualifier::required) {
return !deprecated_public_required_fields;
}
return true;
}
bool is_field_eligible_for_storage_name_mangling(
const t_structured& strct,
const t_field& field,
bool deprecated_public_required_fields) {
if (strct.is<t_union>()) {
// For unions, we should set this to false since we don't want to mangle
// the field name inside MyUnion::Type.
return false;
}
if (!should_mangle_field_storage_name_in_struct(strct)) {
return false;
}
return is_field_private(field, deprecated_public_required_fields);
}
bool type_transitively_refers_to_struct(const t_type& type) {
const t_type* resolved = type.get_true_type();
// fast path is unnecessary but may avoid allocations
if (resolved->is<t_struct>() || resolved->is<t_union>()) {
return true;
}
if (!resolved->is<t_container>()) {
return false;
}
// type is a container: traverse (breadthwise, but could be depthwise)
std::queue<const t_type*> queue;
queue.push(resolved);
while (!queue.empty()) {
auto next = queue.front();
queue.pop();
if (next->is<t_struct>() || next->is<t_union>()) {
return true;
}
if (!next->is<t_container>()) {
continue;
}
if (const t_list* list = next->try_as<t_list>()) {
queue.push(&list->elem_type().deref());
} else if (const t_set* set = next->try_as<t_set>()) {
queue.push(&set->elem_type().deref());
} else if (const t_map* map = next->try_as<t_map>()) {
queue.push(&map->key_type().deref());
queue.push(&map->val_type().deref());
} else {
assert(false);
}
}
return false;
}
class t_mstch_cpp2_generator : public t_whisker_generator {
public:
using t_whisker_generator::t_whisker_generator;
void process_options(
const std::map<std::string, std::string>& options) override {
t_whisker_generator::process_options(options);
client_name_to_split_count_ = get_client_name_to_split_count();
out_dir_base_ = get_out_dir_base(compiler_options());
}
void generate_program() override;
void fill_validator_visitors(ast_validator&) const override;
static std::string include_prefix(
const t_program* program, const compiler_options_map& options);
private:
/** Render a template with only the current program as context. */
void render_whisker_file(
std::string_view template_name, const std::filesystem::path& output) {
whisker::object context = whisker::make::map({
{"program",
whisker::make::native_handle(
render_state().prototypes->create<t_program>(*program_))},
});
t_whisker_generator::render_to_file(output, template_name, context);
}
/** Render a template for a single service. */
void render_whisker_service_file(
const t_service& service,
std::string_view template_name,
const std::filesystem::path& output) {
whisker::object context = whisker::make::map({
{"service",
whisker::make::native_handle(
render_state().prototypes->create<t_service>(service))},
});
t_whisker_generator::render_to_file(output, template_name, context);
}
whisker::object make_rendered_type(
const prototype_database& proto,
const t_type* type,
const t_field* field = nullptr) const {
if (type == nullptr) {
return whisker::make::null;
}
const t_structured* parent =
field == nullptr ? nullptr : context().get_field_parent(field);
return whisker::object(proto.create<cpp2_rendered_type>(
whisker::manage_owned<cpp2_rendered_type>(cpp2_rendered_type{
.type = type, .field = field, .parent = parent})));
}
whisker::object make_rendered_const_value(
const prototype_database& proto,
const t_const_value* value,
const t_type* expected_type = nullptr,
const t_field* field = nullptr) const {
if (value == nullptr) {
return whisker::make::null;
}
const t_structured* parent =
field == nullptr ? nullptr : context().get_field_parent(field);
return whisker::object(proto.create<cpp2_rendered_const_value>(
whisker::manage_owned<cpp2_rendered_const_value>(
cpp2_rendered_const_value{
.value = value,
.expected_type = expected_type,
.field = field,
.parent = parent,
})));
}
void define_additional_prototypes(prototype_database& db) const override {
db.define(make_prototype_for_rendered_type(db));
db.define(make_prototype_for_rendered_const_value(db));
}
prototype<cpp2_rendered_type>::ptr make_prototype_for_rendered_type(
const prototype_database& proto) const {
whisker::dsl::prototype_builder<whisker::native_handle<cpp2_rendered_type>>
def;
// Expose the underlying t_type handle for access to non-field-aware
// properties (e.g. list?, set?, map?, cpp_adapter, cpp_name, etc.).
def.property("type", [&proto](const cpp2_rendered_type& self) {
return resolve_derived_t_type(proto, *self.type);
});
// Field-aware properties — these are the reason this wrapper exists.
def.property("cpp_standard_type", [this](const cpp2_rendered_type& self) {
if (has_field_cpp_type_annotation(self.field)) {
return cpp_context_->resolver().get_standard_type(*self.field);
}
return cpp_context_->resolver().get_standard_type(*self.type);
});
def.property("cpp_type", [this](const cpp2_rendered_type& self) {
if (has_field_cpp_type_annotation(self.field) && self.parent != nullptr) {
return cpp_context_->resolver().get_native_type(
*self.field, *self.parent);
}
return cpp_context_->resolver().get_native_type(*self.type);
});
return std::move(def).make();
}
prototype<cpp2_rendered_const_value>::ptr
make_prototype_for_rendered_const_value(
const prototype_database& proto) const {
using cv = t_const_value::t_const_value_kind;
whisker::dsl::prototype_builder<
whisker::native_handle<cpp2_rendered_const_value>>
def;
// Expose the underlying t_const_value handle for access to non-field-aware
// properties (e.g. bool?, string?, integer_value, owner, etc.).
def.property("value", [&proto](const cpp2_rendered_const_value& self) {
return whisker::object(proto.create<t_const_value>(*self.value));
});
// Field-aware type — returns a rendered type with field context.
def.property("type", [this, &proto](const cpp2_rendered_const_value& self) {
const t_type* type = get_effective_type(self);
if (type == nullptr) {
throw whisker::eval_error("Const value has indeterminate type");
}
return make_rendered_type(proto, type, self.field);
});
// Context-aware structured? — uses expected_type rather than the value's
// own type, which may not be set for nested const values.
def.property("structured?", [](const cpp2_rendered_const_value& self) {
const t_type* type = get_effective_type(self);
return self.value->kind() == cv::CV_MAP && type != nullptr &&
type->get_true_type()->is<t_structured>();
});
// Context-aware container elements — creates nested rendered const values
// with field-aware type context from the parent container's element types.
def.property(
"structured_elements",
[this, &proto](const cpp2_rendered_const_value& self) {
const t_type* type = get_effective_type(self);
const t_structured* strct = type == nullptr
? nullptr
: type->get_true_type()->try_as<t_structured>();
if (strct == nullptr) {
return whisker::make::null;
}
whisker::array::raw result;
for (const auto& [key_const_val, val_const_val] :
self.value->get_map()) {
const t_field* field =
strct->get_field_by_name(key_const_val->get_string());
assert(field != nullptr);
result.emplace_back(
whisker::make::map({
{"field",
whisker::make::native_handle(
proto.create<t_field>(*field))},
{"value",
make_rendered_const_value(
proto, val_const_val, &field->type().deref(), field)},
}));
}
return whisker::make::array(std::move(result));
});
def.property(
"list_elements", [this, &proto](const cpp2_rendered_const_value& self) {
if (self.value->kind() != cv::CV_LIST) {
return whisker::make::null;
}
const t_type* type = get_effective_type(self);
const t_type* elem_type = nullptr;
if (type != nullptr) {
if (const auto* list = type->get_true_type()->try_as<t_list>()) {
elem_type = &list->elem_type().deref();
} else if (
const auto* set = type->get_true_type()->try_as<t_set>()) {
elem_type = &set->elem_type().deref();
}
}
whisker::array::raw result;
for (const auto* elem : self.value->get_list()) {
result.emplace_back(
make_rendered_const_value(proto, elem, elem_type));
}
return whisker::make::array(std::move(result));