1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 * Contains some contributions under the Thrift Software License.
20 * Please see doc/old-thrift-license.txt in the Thrift distribution for
21 * details.
22 */
23
24 #include <cassert>
25
26 #include <fstream>
27 #include <iomanip>
28 #include <iostream>
29 #include <limits>
30 #include <sstream>
31 #include <string>
32 #include <vector>
33
34 #include <sys/stat.h>
35
36 #include "thrift/platform.h"
37 #include "thrift/generate/t_oop_generator.h"
38
39 using std::map;
40 using std::ofstream;
41 using std::ostream;
42 using std::string;
43 using std::vector;
44
45 static const string endl = "\n"; // avoid ostream << std::endl flushes
46
47 /**
48 * C++ code generator. This is legitimacy incarnate.
49 *
50 */
51 class t_cpp_generator : public t_oop_generator {
52 public:
t_cpp_generator(t_program * program,const std::map<std::string,std::string> & parsed_options,const std::string & option_string)53 t_cpp_generator(t_program* program,
54 const std::map<std::string, std::string>& parsed_options,
55 const std::string& option_string)
56 : t_oop_generator(program) {
57 (void)option_string;
58 std::map<std::string, std::string>::const_iterator iter;
59
60
61 gen_pure_enums_ = false;
62 use_include_prefix_ = false;
63 gen_cob_style_ = false;
64 gen_no_client_completion_ = false;
65 gen_no_default_operators_ = false;
66 gen_templates_ = false;
67 gen_templates_only_ = false;
68 gen_moveable_ = false;
69 gen_no_ostream_operators_ = false;
70 gen_no_skeleton_ = false;
71 has_members_ = false;
72
73 for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) {
74 if( iter->first.compare("pure_enums") == 0) {
75 gen_pure_enums_ = true;
76 } else if( iter->first.compare("include_prefix") == 0) {
77 use_include_prefix_ = true;
78 } else if( iter->first.compare("cob_style") == 0) {
79 gen_cob_style_ = true;
80 } else if( iter->first.compare("no_client_completion") == 0) {
81 gen_no_client_completion_ = true;
82 } else if( iter->first.compare("no_default_operators") == 0) {
83 gen_no_default_operators_ = true;
84 } else if( iter->first.compare("templates") == 0) {
85 gen_templates_ = true;
86 gen_templates_only_ = (iter->second == "only");
87 } else if( iter->first.compare("moveable_types") == 0) {
88 gen_moveable_ = true;
89 } else if ( iter->first.compare("no_ostream_operators") == 0) {
90 gen_no_ostream_operators_ = true;
91 } else if ( iter->first.compare("no_skeleton") == 0) {
92 gen_no_skeleton_ = true;
93 } else {
94 throw "unknown option cpp:" + iter->first;
95 }
96 }
97
98 out_dir_base_ = "gen-cpp";
99 }
100
101 /**
102 * Init and close methods
103 */
104
105 void init_generator() override;
106 void close_generator() override;
107
108 void generate_consts(std::vector<t_const*> consts) override;
109
110 /**
111 * Program-level generation functions
112 */
113
114 void generate_typedef(t_typedef* ttypedef) override;
115 void generate_enum(t_enum* tenum) override;
116 void generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum);
117 void generate_enum_ostream_operator(std::ostream& out, t_enum* tenum);
118 void generate_enum_to_string_helper_function_decl(std::ostream& out, t_enum* tenum);
119 void generate_enum_to_string_helper_function(std::ostream& out, t_enum* tenum);
120 void generate_forward_declaration(t_struct* tstruct) override;
generate_struct(t_struct * tstruct)121 void generate_struct(t_struct* tstruct) override { generate_cpp_struct(tstruct, false); }
generate_xception(t_struct * txception)122 void generate_xception(t_struct* txception) override { generate_cpp_struct(txception, true); }
123 void generate_cpp_struct(t_struct* tstruct, bool is_exception);
124
125 void generate_service(t_service* tservice) override;
126
127 void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value);
128 std::string render_const_value(std::ostream& out,
129 std::string name,
130 t_type* type,
131 t_const_value* value);
132
133 void generate_struct_declaration(std::ostream& out,
134 t_struct* tstruct,
135 bool is_exception = false,
136 bool pointers = false,
137 bool read = true,
138 bool write = true,
139 bool swap = false,
140 bool is_user_struct = false);
141 void generate_struct_definition(std::ostream& out,
142 std::ostream& force_cpp_out,
143 t_struct* tstruct,
144 bool setters = true,
145 bool is_user_struct = false);
146 void generate_copy_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
147 void generate_move_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
148 void generate_constructor_helper(std::ostream& out,
149 t_struct* tstruct,
150 bool is_excpetion,
151 bool is_move);
152 void generate_assignment_operator(std::ostream& out, t_struct* tstruct);
153 void generate_move_assignment_operator(std::ostream& out, t_struct* tstruct);
154 void generate_assignment_helper(std::ostream& out, t_struct* tstruct, bool is_move);
155 void generate_struct_reader(std::ostream& out, t_struct* tstruct, bool pointers = false);
156 void generate_struct_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
157 void generate_struct_result_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
158 void generate_struct_swap(std::ostream& out, t_struct* tstruct);
159 void generate_struct_print_method(std::ostream& out, t_struct* tstruct);
160 void generate_exception_what_method(std::ostream& out, t_struct* tstruct);
161
162 /**
163 * Service-level generation functions
164 */
165
166 void generate_service_interface(t_service* tservice, string style);
167 void generate_service_interface_factory(t_service* tservice, string style);
168 void generate_service_null(t_service* tservice, string style);
169 void generate_service_multiface(t_service* tservice);
170 void generate_service_helpers(t_service* tservice);
171 void generate_service_client(t_service* tservice, string style);
172 void generate_service_processor(t_service* tservice, string style);
173 void generate_service_skeleton(t_service* tservice);
174 void generate_process_function(t_service* tservice,
175 t_function* tfunction,
176 string style,
177 bool specialized = false);
178 void generate_function_helpers(t_service* tservice, t_function* tfunction);
179 void generate_service_async_skeleton(t_service* tservice);
180
181 /**
182 * Serialization constructs
183 */
184
185 void generate_deserialize_field(std::ostream& out,
186 t_field* tfield,
187 std::string prefix = "",
188 std::string suffix = "");
189
190 void generate_deserialize_struct(std::ostream& out,
191 t_struct* tstruct,
192 std::string prefix = "",
193 bool pointer = false);
194
195 void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");
196
197 void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "");
198
199 void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "");
200
201 void generate_deserialize_list_element(std::ostream& out,
202 t_list* tlist,
203 std::string prefix,
204 bool push_back,
205 std::string index);
206
207 void generate_serialize_field(std::ostream& out,
208 t_field* tfield,
209 std::string prefix = "",
210 std::string suffix = "");
211
212 void generate_serialize_struct(std::ostream& out,
213 t_struct* tstruct,
214 std::string prefix = "",
215 bool pointer = false);
216
217 void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");
218
219 void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter);
220
221 void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter);
222
223 void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter);
224
225 void generate_function_call(ostream& out,
226 t_function* tfunction,
227 string target,
228 string iface,
229 string arg_prefix);
230 /*
231 * Helper rendering functions
232 */
233
234 std::string namespace_prefix(std::string ns);
235 std::string namespace_open(std::string ns);
236 std::string namespace_close(std::string ns);
237 std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false);
238 std::string base_type_name(t_base_type::t_base tbase);
239 std::string declare_field(t_field* tfield,
240 bool init = false,
241 bool pointer = false,
242 bool constant = false,
243 bool reference = false);
244 std::string function_signature(t_function* tfunction,
245 std::string style,
246 std::string prefix = "",
247 bool name_params = true);
248 std::string cob_function_signature(t_function* tfunction,
249 std::string prefix = "",
250 bool name_params = true);
251 std::string argument_list(t_struct* tstruct, bool name_params = true, bool start_comma = false);
252 std::string type_to_enum(t_type* ttype);
253
254 void generate_enum_constant_list(std::ostream& f,
255 const vector<t_enum_value*>& constants,
256 const char* prefix,
257 const char* suffix,
258 bool include_values);
259
260 void generate_struct_ostream_operator_decl(std::ostream& f, t_struct* tstruct);
261 void generate_struct_ostream_operator(std::ostream& f, t_struct* tstruct);
262 void generate_struct_print_method_decl(std::ostream& f, t_struct* tstruct);
263 void generate_exception_what_method_decl(std::ostream& f,
264 t_struct* tstruct,
265 bool external = false);
266
is_reference(t_field * tfield)267 bool is_reference(t_field* tfield) { return tfield->get_reference(); }
268
is_complex_type(t_type * ttype)269 bool is_complex_type(t_type* ttype) {
270 ttype = get_true_type(ttype);
271
272 return ttype->is_container() || ttype->is_struct() || ttype->is_xception()
273 || (ttype->is_base_type()
274 && (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING));
275 }
276
set_use_include_prefix(bool use_include_prefix)277 void set_use_include_prefix(bool use_include_prefix) { use_include_prefix_ = use_include_prefix; }
278
279 /**
280 * The compiler option "no_thrift_ostream_impl" can be used to prevent
281 * the compiler from emitting implementations for operator <<. In this
282 * case the consuming application must provide any needed to build.
283 *
284 * To disable this on a per structure bases, one can alternatively set
285 * the annotation "cpp.customostream" to prevent thrift from emitting an
286 * operator << (std::ostream&).
287 *
288 * See AnnotationTest for validation of this annotation feature.
289 */
has_custom_ostream(t_type * ttype) const290 bool has_custom_ostream(t_type* ttype) const {
291 return (gen_no_ostream_operators_) ||
292 (ttype->annotations_.find("cpp.customostream") != ttype->annotations_.end());
293 }
294
295 private:
296 /**
297 * Returns the include prefix to use for a file generated by program, or the
298 * empty string if no include prefix should be used.
299 */
300 std::string get_include_prefix(const t_program& program) const;
301
302 /**
303 * Returns the legal program name to use for a file generated by program, if the
304 * program name contains dots then replace it with underscores, otherwise return the
305 * original program name.
306 */
307 std::string get_legal_program_name(std::string program_name);
308
309 /**
310 * True if we should generate pure enums for Thrift enums, instead of wrapper classes.
311 */
312 bool gen_pure_enums_;
313
314 /**
315 * True if we should generate templatized reader/writer methods.
316 */
317 bool gen_templates_;
318
319 /**
320 * True iff we should generate process function pointers for only templatized
321 * reader/writer methods.
322 */
323 bool gen_templates_only_;
324
325 /**
326 * True if we should generate move constructors & assignment operators.
327 */
328 bool gen_moveable_;
329
330 /**
331 * True if we should generate ostream definitions
332 */
333 bool gen_no_ostream_operators_;
334
335 /**
336 * True iff we should use a path prefix in our #include statements for other
337 * thrift-generated header files.
338 */
339 bool use_include_prefix_;
340
341 /**
342 * True if we should generate "Continuation OBject"-style classes as well.
343 */
344 bool gen_cob_style_;
345
346 /**
347 * True if we should omit calls to completion__() in CobClient class.
348 */
349 bool gen_no_client_completion_;
350
351 /**
352 * True if we should omit generating the default opeartors ==, != and <.
353 */
354 bool gen_no_default_operators_;
355
356 /**
357 * True if we should generate skeleton.
358 */
359 bool gen_no_skeleton_;
360
361 /**
362 * True if thrift has member(s)
363 */
364 bool has_members_;
365
366 /**
367 * Strings for namespace, computed once up front then used directly
368 */
369
370 std::string ns_open_;
371 std::string ns_close_;
372
373 /**
374 * File streams, stored here to avoid passing them as parameters to every
375 * function.
376 */
377
378 ofstream_with_content_based_conditional_update f_types_;
379 ofstream_with_content_based_conditional_update f_types_impl_;
380 ofstream_with_content_based_conditional_update f_types_tcc_;
381 ofstream_with_content_based_conditional_update f_header_;
382 ofstream_with_content_based_conditional_update f_service_;
383 ofstream_with_content_based_conditional_update f_service_tcc_;
384
385 // The ProcessorGenerator is used to generate parts of the code,
386 // so it needs access to many of our protected members and methods.
387 //
388 // TODO: The code really should be cleaned up so that helper methods for
389 // writing to the output files are separate from the generator classes
390 // themselves.
391 friend class ProcessorGenerator;
392 };
393
394 /**
395 * Prepares for file generation by opening up the necessary file output
396 * streams.
397 */
init_generator()398 void t_cpp_generator::init_generator() {
399 // Make output directory
400 MKDIR(get_out_dir().c_str());
401
402 program_name_ = get_legal_program_name(program_name_);
403
404 // Make output file
405 string f_types_name = get_out_dir() + program_name_ + "_types.h";
406 f_types_.open(f_types_name);
407
408 string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp";
409 f_types_impl_.open(f_types_impl_name.c_str());
410
411 if (gen_templates_) {
412 // If we don't open the stream, it appears to just discard data,
413 // which is fine.
414 string f_types_tcc_name = get_out_dir() + program_name_ + "_types.tcc";
415 f_types_tcc_.open(f_types_tcc_name.c_str());
416 }
417
418 // Print header
419 f_types_ << autogen_comment();
420 f_types_impl_ << autogen_comment();
421 f_types_tcc_ << autogen_comment();
422
423 // Start ifndef
424 f_types_ << "#ifndef " << program_name_ << "_TYPES_H" << endl << "#define " << program_name_
425 << "_TYPES_H" << endl << endl;
426 f_types_tcc_ << "#ifndef " << program_name_ << "_TYPES_TCC" << endl << "#define " << program_name_
427 << "_TYPES_TCC" << endl << endl;
428
429 // Include base types
430 f_types_ << "#include <iosfwd>" << endl
431 << endl
432 << "#include <thrift/Thrift.h>" << endl
433 << "#include <thrift/TApplicationException.h>" << endl
434 << "#include <thrift/TBase.h>" << endl
435 << "#include <thrift/protocol/TProtocol.h>" << endl
436 << "#include <thrift/transport/TTransport.h>" << endl
437 << endl;
438 // Include C++xx compatibility header
439 f_types_ << "#include <functional>" << endl;
440 f_types_ << "#include <memory>" << endl;
441
442 // Include other Thrift includes
443 const vector<t_program*>& includes = program_->get_includes();
444 for (auto include : includes) {
445 f_types_ << "#include \"" << get_include_prefix(*include) << include->get_name()
446 << "_types.h\"" << endl;
447
448 // XXX(simpkins): If gen_templates_ is enabled, we currently assume all
449 // included files were also generated with templates enabled.
450 f_types_tcc_ << "#include \"" << get_include_prefix(*include) << include->get_name()
451 << "_types.tcc\"" << endl;
452 }
453 f_types_ << endl;
454
455 // Include custom headers
456 const vector<string>& cpp_includes = program_->get_cpp_includes();
457 for (const auto & cpp_include : cpp_includes) {
458 if (cpp_include[0] == '<') {
459 f_types_ << "#include " << cpp_include << endl;
460 } else {
461 f_types_ << "#include \"" << cpp_include << "\"" << endl;
462 }
463 }
464 f_types_ << endl;
465
466 // Include the types file
467 f_types_impl_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
468 << "_types.h\"" << endl << endl;
469 f_types_tcc_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
470 << "_types.h\"" << endl << endl;
471
472 // The swap() code needs <algorithm> for std::swap()
473 f_types_impl_ << "#include <algorithm>" << endl;
474 // for operator<<
475 f_types_impl_ << "#include <ostream>" << endl << endl;
476 f_types_impl_ << "#include <thrift/TToString.h>" << endl << endl;
477
478 // Open namespace
479 ns_open_ = namespace_open(program_->get_namespace("cpp"));
480 ns_close_ = namespace_close(program_->get_namespace("cpp"));
481
482 f_types_ << ns_open_ << endl << endl;
483
484 f_types_impl_ << ns_open_ << endl << endl;
485
486 f_types_tcc_ << ns_open_ << endl << endl;
487 }
488
489 /**
490 * Closes the output files.
491 */
close_generator()492 void t_cpp_generator::close_generator() {
493 // Close namespace
494 f_types_ << ns_close_ << endl << endl;
495 f_types_impl_ << ns_close_ << endl;
496 f_types_tcc_ << ns_close_ << endl << endl;
497
498 // Include the types.tcc file from the types header file,
499 // so clients don't have to explicitly include the tcc file.
500 // TODO(simpkins): Make this a separate option.
501 if (gen_templates_) {
502 f_types_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
503 << "_types.tcc\"" << endl << endl;
504 }
505
506 // Close ifndef
507 f_types_ << "#endif" << endl;
508 f_types_tcc_ << "#endif" << endl;
509
510 // Close output file
511 f_types_.close();
512 f_types_impl_.close();
513 f_types_tcc_.close();
514
515 string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp";
516
517 if (!has_members_) {
518 remove(f_types_impl_name.c_str());
519 }
520 }
521
522 /**
523 * Generates a typedef. This is just a simple 1-liner in C++
524 *
525 * @param ttypedef The type definition
526 */
generate_typedef(t_typedef * ttypedef)527 void t_cpp_generator::generate_typedef(t_typedef* ttypedef) {
528 generate_java_doc(f_types_, ttypedef);
529 f_types_ << indent() << "typedef " << type_name(ttypedef->get_type(), true) << " "
530 << ttypedef->get_symbolic() << ";" << endl << endl;
531 }
532
generate_enum_constant_list(std::ostream & f,const vector<t_enum_value * > & constants,const char * prefix,const char * suffix,bool include_values)533 void t_cpp_generator::generate_enum_constant_list(std::ostream& f,
534 const vector<t_enum_value*>& constants,
535 const char* prefix,
536 const char* suffix,
537 bool include_values) {
538 f << " {" << endl;
539 indent_up();
540
541 vector<t_enum_value*>::const_iterator c_iter;
542 bool first = true;
543 for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
544 if (first) {
545 first = false;
546 } else {
547 f << "," << endl;
548 }
549 generate_java_doc(f, *c_iter);
550 indent(f) << prefix << (*c_iter)->get_name() << suffix;
551 if (include_values) {
552 f << " = " << (*c_iter)->get_value();
553 }
554 }
555
556 f << endl;
557 indent_down();
558 indent(f) << "};" << endl;
559 }
560
561 /**
562 * Generates code for an enumerated type. In C++, this is essentially the same
563 * as the thrift definition itself, using the enum keyword in C++.
564 *
565 * @param tenum The enumeration
566 */
generate_enum(t_enum * tenum)567 void t_cpp_generator::generate_enum(t_enum* tenum) {
568 vector<t_enum_value*> constants = tenum->get_constants();
569
570 std::string enum_name = tenum->get_name();
571 if (!gen_pure_enums_) {
572 enum_name = "type";
573 generate_java_doc(f_types_, tenum);
574 f_types_ << indent() << "struct " << tenum->get_name() << " {" << endl;
575 indent_up();
576 }
577 f_types_ << indent() << "enum " << enum_name;
578
579 generate_enum_constant_list(f_types_, constants, "", "", true);
580
581 if (!gen_pure_enums_) {
582 indent_down();
583 f_types_ << "};" << endl;
584 }
585
586 f_types_ << endl;
587
588 /**
589 Generate a character array of enum names for debugging purposes.
590 */
591 std::string prefix = "";
592 if (!gen_pure_enums_) {
593 prefix = tenum->get_name() + "::";
594 }
595
596 f_types_impl_ << indent() << "int _k" << tenum->get_name() << "Values[] =";
597 generate_enum_constant_list(f_types_impl_, constants, prefix.c_str(), "", false);
598
599 f_types_impl_ << indent() << "const char* _k" << tenum->get_name() << "Names[] =";
600 generate_enum_constant_list(f_types_impl_, constants, "\"", "\"", false);
601
602 f_types_ << indent() << "extern const std::map<int, const char*> _" << tenum->get_name()
603 << "_VALUES_TO_NAMES;" << endl << endl;
604
605 f_types_impl_ << indent() << "const std::map<int, const char*> _" << tenum->get_name()
606 << "_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(" << constants.size() << ", _k"
607 << tenum->get_name() << "Values"
608 << ", _k" << tenum->get_name() << "Names), "
609 << "::apache::thrift::TEnumIterator(-1, nullptr, nullptr));" << endl << endl;
610
611 generate_enum_ostream_operator_decl(f_types_, tenum);
612 generate_enum_ostream_operator(f_types_impl_, tenum);
613
614 generate_enum_to_string_helper_function_decl(f_types_, tenum);
615 generate_enum_to_string_helper_function(f_types_impl_, tenum);
616 }
617
generate_enum_ostream_operator_decl(std::ostream & out,t_enum * tenum)618 void t_cpp_generator::generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum) {
619
620 out << "std::ostream& operator<<(std::ostream& out, const ";
621 if (gen_pure_enums_) {
622 out << tenum->get_name();
623 } else {
624 out << tenum->get_name() << "::type&";
625 }
626 out << " val);" << endl;
627 out << endl;
628 }
629
generate_enum_ostream_operator(std::ostream & out,t_enum * tenum)630 void t_cpp_generator::generate_enum_ostream_operator(std::ostream& out, t_enum* tenum) {
631
632 // If we've been told the consuming application will provide an ostream
633 // operator definition then we only make a declaration:
634
635 if (!has_custom_ostream(tenum)) {
636 out << "std::ostream& operator<<(std::ostream& out, const ";
637 if (gen_pure_enums_) {
638 out << tenum->get_name();
639 } else {
640 out << tenum->get_name() << "::type&";
641 }
642 out << " val) ";
643 scope_up(out);
644
645 out << indent() << "std::map<int, const char*>::const_iterator it = _"
646 << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl;
647 out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl;
648 indent_up();
649 out << indent() << "out << it->second;" << endl;
650 indent_down();
651 out << indent() << "} else {" << endl;
652 indent_up();
653 out << indent() << "out << static_cast<int>(val);" << endl;
654 indent_down();
655 out << indent() << "}" << endl;
656
657 out << indent() << "return out;" << endl;
658 scope_down(out);
659 out << endl;
660 }
661 }
662
generate_enum_to_string_helper_function_decl(std::ostream & out,t_enum * tenum)663 void t_cpp_generator::generate_enum_to_string_helper_function_decl(std::ostream& out, t_enum* tenum) {
664 out << "std::string to_string(const ";
665 if (gen_pure_enums_) {
666 out << tenum->get_name();
667 } else {
668 out << tenum->get_name() << "::type&";
669 }
670 out << " val);" << endl;
671 out << endl;
672 }
673
generate_enum_to_string_helper_function(std::ostream & out,t_enum * tenum)674 void t_cpp_generator::generate_enum_to_string_helper_function(std::ostream& out, t_enum* tenum) {
675 if (!has_custom_ostream(tenum)) {
676 out << "std::string to_string(const ";
677 if (gen_pure_enums_) {
678 out << tenum->get_name();
679 } else {
680 out << tenum->get_name() << "::type&";
681 }
682 out << " val) " ;
683 scope_up(out);
684
685 out << indent() << "std::map<int, const char*>::const_iterator it = _"
686 << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl;
687 out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl;
688 indent_up();
689 out << indent() << "return std::string(it->second);" << endl;
690 indent_down();
691 out << indent() << "} else {" << endl;
692 indent_up();
693 out << indent() << "return std::to_string(static_cast<int>(val));" << endl;
694 indent_down();
695 out << indent() << "}" << endl;
696
697 scope_down(out);
698 out << endl;
699 }
700 }
701
702 /**
703 * Generates a class that holds all the constants.
704 */
generate_consts(std::vector<t_const * > consts)705 void t_cpp_generator::generate_consts(std::vector<t_const*> consts) {
706 string f_consts_name = get_out_dir() + program_name_ + "_constants.h";
707 ofstream_with_content_based_conditional_update f_consts;
708 if (consts.size() > 0) {
709 f_consts.open(f_consts_name);
710
711 string f_consts_impl_name = get_out_dir() + program_name_ + "_constants.cpp";
712 ofstream_with_content_based_conditional_update f_consts_impl;
713 f_consts_impl.open(f_consts_impl_name);
714
715 // Print header
716 f_consts << autogen_comment();
717 f_consts_impl << autogen_comment();
718
719 // Start ifndef
720 f_consts << "#ifndef " << program_name_ << "_CONSTANTS_H" << endl << "#define " << program_name_
721 << "_CONSTANTS_H" << endl << endl << "#include \"" << get_include_prefix(*get_program())
722 << program_name_ << "_types.h\"" << endl << endl << ns_open_ << endl << endl;
723
724 f_consts_impl << "#include \"" << get_include_prefix(*get_program()) << program_name_
725 << "_constants.h\"" << endl << endl << ns_open_ << endl << endl;
726
727 f_consts << "class " << program_name_ << "Constants {" << endl << " public:" << endl << " "
728 << program_name_ << "Constants();" << endl << endl;
729 indent_up();
730 vector<t_const*>::iterator c_iter;
731 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
732 string name = (*c_iter)->get_name();
733 t_type* type = (*c_iter)->get_type();
734 f_consts << indent() << type_name(type) << " " << name << ";" << endl;
735 }
736 indent_down();
737 f_consts << "};" << endl;
738
739 f_consts_impl << "const " << program_name_ << "Constants g_" << program_name_ << "_constants;"
740 << endl << endl << program_name_ << "Constants::" << program_name_
741 << "Constants() {" << endl;
742 indent_up();
743 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
744 print_const_value(f_consts_impl,
745 (*c_iter)->get_name(),
746 (*c_iter)->get_type(),
747 (*c_iter)->get_value());
748 }
749 indent_down();
750 indent(f_consts_impl) << "}" << endl;
751
752 f_consts << endl << "extern const " << program_name_ << "Constants g_" << program_name_
753 << "_constants;" << endl << endl << ns_close_ << endl << endl << "#endif" << endl;
754 f_consts.close();
755
756 f_consts_impl << endl << ns_close_ << endl << endl;
757 f_consts_impl.close();
758 }
759 }
760
761 /**
762 * Prints the value of a constant with the given type. Note that type checking
763 * is NOT performed in this function as it is always run beforehand using the
764 * validate_types method in main.cc
765 */
print_const_value(ostream & out,string name,t_type * type,t_const_value * value)766 void t_cpp_generator::print_const_value(ostream& out,
767 string name,
768 t_type* type,
769 t_const_value* value) {
770 type = get_true_type(type);
771 if (type->is_base_type()) {
772 string v2 = render_const_value(out, name, type, value);
773 indent(out) << name << " = " << v2 << ";" << endl << endl;
774 } else if (type->is_enum()) {
775 indent(out) << name << " = (" << type_name(type) << ")" << value->get_integer() << ";" << endl
776 << endl;
777 } else if (type->is_struct() || type->is_xception()) {
778 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
779 vector<t_field*>::const_iterator f_iter;
780 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
781 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
782 bool is_nonrequired_field = false;
783 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
784 t_type* field_type = nullptr;
785 is_nonrequired_field = false;
786 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
787 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
788 field_type = (*f_iter)->get_type();
789 is_nonrequired_field = (*f_iter)->get_req() != t_field::T_REQUIRED;
790 }
791 }
792 if (field_type == nullptr) {
793 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
794 }
795 string val = render_const_value(out, name, field_type, v_iter->second);
796 indent(out) << name << "." << v_iter->first->get_string() << " = " << val << ";" << endl;
797 if (is_nonrequired_field) {
798 indent(out) << name << ".__isset." << v_iter->first->get_string() << " = true;" << endl;
799 }
800 }
801 out << endl;
802 } else if (type->is_map()) {
803 t_type* ktype = ((t_map*)type)->get_key_type();
804 t_type* vtype = ((t_map*)type)->get_val_type();
805 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
806 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
807 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
808 string key = render_const_value(out, name, ktype, v_iter->first);
809 string val = render_const_value(out, name, vtype, v_iter->second);
810 indent(out) << name << ".insert(std::make_pair(" << key << ", " << val << "));" << endl;
811 }
812 out << endl;
813 } else if (type->is_list()) {
814 t_type* etype = ((t_list*)type)->get_elem_type();
815 const vector<t_const_value*>& val = value->get_list();
816 vector<t_const_value*>::const_iterator v_iter;
817 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
818 string val = render_const_value(out, name, etype, *v_iter);
819 indent(out) << name << ".push_back(" << val << ");" << endl;
820 }
821 out << endl;
822 } else if (type->is_set()) {
823 t_type* etype = ((t_set*)type)->get_elem_type();
824 const vector<t_const_value*>& val = value->get_list();
825 vector<t_const_value*>::const_iterator v_iter;
826 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
827 string val = render_const_value(out, name, etype, *v_iter);
828 indent(out) << name << ".insert(" << val << ");" << endl;
829 }
830 out << endl;
831 } else {
832 throw "INVALID TYPE IN print_const_value: " + type->get_name();
833 }
834 }
835
836 /**
837 *
838 */
render_const_value(ostream & out,string name,t_type * type,t_const_value * value)839 string t_cpp_generator::render_const_value(ostream& out,
840 string name,
841 t_type* type,
842 t_const_value* value) {
843 (void)name;
844 std::ostringstream render;
845
846 if (type->is_base_type()) {
847 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
848 switch (tbase) {
849 case t_base_type::TYPE_STRING:
850 render << '"' << get_escaped_string(value) << '"';
851 break;
852 case t_base_type::TYPE_BOOL:
853 render << ((value->get_integer() > 0) ? "true" : "false");
854 break;
855 case t_base_type::TYPE_I8:
856 case t_base_type::TYPE_I16:
857 case t_base_type::TYPE_I32:
858 render << value->get_integer();
859 break;
860 case t_base_type::TYPE_I64:
861 render << value->get_integer() << "LL";
862 break;
863 case t_base_type::TYPE_DOUBLE:
864 if (value->get_type() == t_const_value::CV_INTEGER) {
865 render << "static_cast<double>(" << value->get_integer() << ")";
866 } else {
867 render << emit_double_as_string(value->get_double());
868 }
869 break;
870 default:
871 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
872 }
873 } else if (type->is_enum()) {
874 render << "(" << type_name(type) << ")" << value->get_integer();
875 } else {
876 string t = tmp("tmp");
877 indent(out) << type_name(type) << " " << t << ";" << endl;
878 print_const_value(out, t, type, value);
879 render << t;
880 }
881
882 return render.str();
883 }
884
generate_forward_declaration(t_struct * tstruct)885 void t_cpp_generator::generate_forward_declaration(t_struct* tstruct) {
886 // Forward declare struct def
887 f_types_ << indent() << "class " << tstruct->get_name() << ";" << endl << endl;
888 }
889
890 /**
891 * Generates a struct definition for a thrift data type. This is a class
892 * with data members and a read/write() function, plus a mirroring isset
893 * inner class.
894 *
895 * @param tstruct The struct definition
896 */
generate_cpp_struct(t_struct * tstruct,bool is_exception)897 void t_cpp_generator::generate_cpp_struct(t_struct* tstruct, bool is_exception) {
898 generate_struct_declaration(f_types_, tstruct, is_exception, false, true, true, true, true);
899 generate_struct_definition(f_types_impl_, f_types_impl_, tstruct, true, true);
900
901 std::ostream& out = (gen_templates_ ? f_types_tcc_ : f_types_impl_);
902 generate_struct_reader(out, tstruct);
903 generate_struct_writer(out, tstruct);
904 generate_struct_swap(f_types_impl_, tstruct);
905 generate_copy_constructor(f_types_impl_, tstruct, is_exception);
906 if (gen_moveable_) {
907 generate_move_constructor(f_types_impl_, tstruct, is_exception);
908 }
909 generate_assignment_operator(f_types_impl_, tstruct);
910 if (gen_moveable_) {
911 generate_move_assignment_operator(f_types_impl_, tstruct);
912 }
913
914 if (!has_custom_ostream(tstruct)) {
915 generate_struct_print_method(f_types_impl_, tstruct);
916 }
917
918 if (is_exception) {
919 generate_exception_what_method(f_types_impl_, tstruct);
920 }
921
922 has_members_ = true;
923 }
924
generate_copy_constructor(ostream & out,t_struct * tstruct,bool is_exception)925 void t_cpp_generator::generate_copy_constructor(ostream& out,
926 t_struct* tstruct,
927 bool is_exception) {
928 generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/false);
929 }
930
generate_move_constructor(ostream & out,t_struct * tstruct,bool is_exception)931 void t_cpp_generator::generate_move_constructor(ostream& out,
932 t_struct* tstruct,
933 bool is_exception) {
934 generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/true);
935 }
936
937 namespace {
938 // Helper to convert a variable to rvalue, if move is enabled
maybeMove(std::string const & other,bool move)939 std::string maybeMove(std::string const& other, bool move) {
940 if (move) {
941 return "std::move(" + other + ")";
942 }
943 return other;
944 }
945 }
946
generate_constructor_helper(ostream & out,t_struct * tstruct,bool is_exception,bool is_move)947 void t_cpp_generator::generate_constructor_helper(ostream& out,
948 t_struct* tstruct,
949 bool is_exception,
950 bool is_move) {
951
952 std::string tmp_name = tmp("other");
953
954 indent(out) << tstruct->get_name() << "::" << tstruct->get_name();
955
956 if (is_move) {
957 out << "( " << tstruct->get_name() << "&& ";
958 } else {
959 out << "(const " << tstruct->get_name() << "& ";
960 }
961 out << tmp_name << ") ";
962 if (is_exception)
963 out << ": TException() ";
964 out << "{" << endl;
965 indent_up();
966
967 const vector<t_field*>& members = tstruct->get_members();
968
969 // eliminate compiler unused warning
970 if (members.empty())
971 indent(out) << "(void) " << tmp_name << ";" << endl;
972
973 vector<t_field*>::const_iterator f_iter;
974 bool has_nonrequired_fields = false;
975 for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
976 if ((*f_iter)->get_req() != t_field::T_REQUIRED)
977 has_nonrequired_fields = true;
978 indent(out) << (*f_iter)->get_name() << " = "
979 << maybeMove(tmp_name + "." + (*f_iter)->get_name(), is_move) << ";" << endl;
980 }
981
982 if (has_nonrequired_fields) {
983 indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", is_move) << ";" << endl;
984 }
985
986 indent_down();
987 indent(out) << "}" << endl;
988 }
989
generate_assignment_operator(ostream & out,t_struct * tstruct)990 void t_cpp_generator::generate_assignment_operator(ostream& out, t_struct* tstruct) {
991 generate_assignment_helper(out, tstruct, /*is_move=*/false);
992 }
993
generate_move_assignment_operator(ostream & out,t_struct * tstruct)994 void t_cpp_generator::generate_move_assignment_operator(ostream& out, t_struct* tstruct) {
995 generate_assignment_helper(out, tstruct, /*is_move=*/true);
996 }
997
generate_assignment_helper(ostream & out,t_struct * tstruct,bool is_move)998 void t_cpp_generator::generate_assignment_helper(ostream& out, t_struct* tstruct, bool is_move) {
999 std::string tmp_name = tmp("other");
1000
1001 indent(out) << tstruct->get_name() << "& " << tstruct->get_name() << "::operator=(";
1002
1003 if (is_move) {
1004 out << tstruct->get_name() << "&& ";
1005 } else {
1006 out << "const " << tstruct->get_name() << "& ";
1007 }
1008 out << tmp_name << ") {" << endl;
1009
1010 indent_up();
1011
1012 const vector<t_field*>& members = tstruct->get_members();
1013
1014 // eliminate compiler unused warning
1015 if (members.empty())
1016 indent(out) << "(void) " << tmp_name << ";" << endl;
1017
1018 vector<t_field*>::const_iterator f_iter;
1019 bool has_nonrequired_fields = false;
1020 for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
1021 if ((*f_iter)->get_req() != t_field::T_REQUIRED)
1022 has_nonrequired_fields = true;
1023 indent(out) << (*f_iter)->get_name() << " = "
1024 << maybeMove(tmp_name + "." + (*f_iter)->get_name(), is_move) << ";" << endl;
1025 }
1026 if (has_nonrequired_fields) {
1027 indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", is_move) << ";" << endl;
1028 }
1029
1030 indent(out) << "return *this;" << endl;
1031 indent_down();
1032 indent(out) << "}" << endl;
1033 }
1034
1035 /**
1036 * Writes the struct declaration into the header file
1037 *
1038 * @param out Output stream
1039 * @param tstruct The struct
1040 */
generate_struct_declaration(ostream & out,t_struct * tstruct,bool is_exception,bool pointers,bool read,bool write,bool swap,bool is_user_struct)1041 void t_cpp_generator::generate_struct_declaration(ostream& out,
1042 t_struct* tstruct,
1043 bool is_exception,
1044 bool pointers,
1045 bool read,
1046 bool write,
1047 bool swap,
1048 bool is_user_struct) {
1049 string extends = "";
1050 if (is_exception) {
1051 extends = " : public ::apache::thrift::TException";
1052 } else {
1053 if (is_user_struct && !gen_templates_) {
1054 extends = " : public virtual ::apache::thrift::TBase";
1055 }
1056 }
1057
1058 // Get members
1059 vector<t_field*>::const_iterator m_iter;
1060 const vector<t_field*>& members = tstruct->get_members();
1061
1062 // Write the isset structure declaration outside the class. This makes
1063 // the generated code amenable to processing by SWIG.
1064 // We only declare the struct if it gets used in the class.
1065
1066 // Isset struct has boolean fields, but only for non-required fields.
1067 bool has_nonrequired_fields = false;
1068 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1069 if ((*m_iter)->get_req() != t_field::T_REQUIRED)
1070 has_nonrequired_fields = true;
1071 }
1072
1073 if (has_nonrequired_fields && (!pointers || read)) {
1074
1075 out << indent() << "typedef struct _" << tstruct->get_name() << "__isset {" << endl;
1076 indent_up();
1077
1078 indent(out) << "_" << tstruct->get_name() << "__isset() ";
1079 bool first = true;
1080 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1081 if ((*m_iter)->get_req() == t_field::T_REQUIRED) {
1082 continue;
1083 }
1084 string isSet = ((*m_iter)->get_value() != nullptr) ? "true" : "false";
1085 if (first) {
1086 first = false;
1087 out << ": " << (*m_iter)->get_name() << "(" << isSet << ")";
1088 } else {
1089 out << ", " << (*m_iter)->get_name() << "(" << isSet << ")";
1090 }
1091 }
1092 out << " {}" << endl;
1093
1094 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1095 if ((*m_iter)->get_req() != t_field::T_REQUIRED) {
1096 indent(out) << "bool " << (*m_iter)->get_name() << " :1;" << endl;
1097 }
1098 }
1099
1100 indent_down();
1101 indent(out) << "} _" << tstruct->get_name() << "__isset;" << endl;
1102 }
1103
1104 out << endl;
1105
1106 generate_java_doc(out, tstruct);
1107
1108 // Open struct def
1109 out << indent() << "class " << tstruct->get_name() << extends << " {" << endl << indent()
1110 << " public:" << endl << endl;
1111 indent_up();
1112
1113 if (!pointers) {
1114 // Copy constructor
1115 indent(out) << tstruct->get_name() << "(const " << tstruct->get_name() << "&);" << endl;
1116
1117 // Move constructor
1118 if (gen_moveable_) {
1119 indent(out) << tstruct->get_name() << "(" << tstruct->get_name() << "&&);" << endl;
1120 }
1121
1122 // Assignment Operator
1123 indent(out) << tstruct->get_name() << "& operator=(const " << tstruct->get_name() << "&);"
1124 << endl;
1125
1126 // Move assignment operator
1127 if (gen_moveable_) {
1128 indent(out) << tstruct->get_name() << "& operator=(" << tstruct->get_name() << "&&);" << endl;
1129 }
1130
1131 // Default constructor
1132 indent(out) << tstruct->get_name() << "()";
1133
1134 bool init_ctor = false;
1135
1136 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1137 t_type* t = get_true_type((*m_iter)->get_type());
1138 if (t->is_base_type() || t->is_enum() || is_reference(*m_iter)) {
1139 string dval;
1140 if (t->is_enum()) {
1141 dval += "(" + type_name(t) + ")";
1142 }
1143 dval += (t->is_string() || is_reference(*m_iter)) ? "" : "0";
1144 t_const_value* cv = (*m_iter)->get_value();
1145 if (cv != nullptr) {
1146 dval = render_const_value(out, (*m_iter)->get_name(), t, cv);
1147 }
1148 if (!init_ctor) {
1149 init_ctor = true;
1150 out << " : ";
1151 out << (*m_iter)->get_name() << "(" << dval << ")";
1152 } else {
1153 out << ", " << (*m_iter)->get_name() << "(" << dval << ")";
1154 }
1155 }
1156 }
1157 out << " {" << endl;
1158 indent_up();
1159 // TODO(dreiss): When everything else in Thrift is perfect,
1160 // do more of these in the initializer list.
1161 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1162 t_type* t = get_true_type((*m_iter)->get_type());
1163
1164 if (!t->is_base_type()) {
1165 t_const_value* cv = (*m_iter)->get_value();
1166 if (cv != nullptr) {
1167 print_const_value(out, (*m_iter)->get_name(), t, cv);
1168 }
1169 }
1170 }
1171 scope_down(out);
1172 }
1173
1174 if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
1175 out << endl << indent() << "virtual ~" << tstruct->get_name() << "() noexcept;" << endl;
1176 }
1177
1178 // Declare all fields
1179 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1180 generate_java_doc(out, *m_iter);
1181 indent(out) << declare_field(*m_iter,
1182 false,
1183 (pointers && !(*m_iter)->get_type()->is_xception()),
1184 !read) << endl;
1185 }
1186
1187 // Add the __isset data member if we need it, using the definition from above
1188 if (has_nonrequired_fields && (!pointers || read)) {
1189 out << endl << indent() << "_" << tstruct->get_name() << "__isset __isset;" << endl;
1190 }
1191
1192 // Create a setter function for each field
1193 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1194 if (pointers) {
1195 continue;
1196 }
1197 if (is_reference((*m_iter))) {
1198 out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "(::std::shared_ptr<"
1199 << type_name((*m_iter)->get_type(), false, false) << ">";
1200 out << " val);" << endl;
1201 } else {
1202 out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "("
1203 << type_name((*m_iter)->get_type(), false, true);
1204 out << " val);" << endl;
1205 }
1206 }
1207 out << endl;
1208
1209 if (!pointers) {
1210 // Should we generate default operators?
1211 if (!gen_no_default_operators_) {
1212 // Generate an equality testing operator. Make it inline since the compiler
1213 // will do a better job than we would when deciding whether to inline it.
1214 out << indent() << "bool operator == (const " << tstruct->get_name() << " & "
1215 << (members.size() > 0 ? "rhs" : "/* rhs */") << ") const" << endl;
1216 scope_up(out);
1217 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1218 // Most existing Thrift code does not use isset or optional/required,
1219 // so we treat "default" fields as required.
1220 if ((*m_iter)->get_req() != t_field::T_OPTIONAL) {
1221 out << indent() << "if (!(" << (*m_iter)->get_name() << " == rhs."
1222 << (*m_iter)->get_name() << "))" << endl << indent() << " return false;" << endl;
1223 } else {
1224 out << indent() << "if (__isset." << (*m_iter)->get_name() << " != rhs.__isset."
1225 << (*m_iter)->get_name() << ")" << endl << indent() << " return false;" << endl
1226 << indent() << "else if (__isset." << (*m_iter)->get_name() << " && !("
1227 << (*m_iter)->get_name() << " == rhs." << (*m_iter)->get_name() << "))" << endl
1228 << indent() << " return false;" << endl;
1229 }
1230 }
1231 indent(out) << "return true;" << endl;
1232 scope_down(out);
1233 out << indent() << "bool operator != (const " << tstruct->get_name() << " &rhs) const {"
1234 << endl << indent() << " return !(*this == rhs);" << endl << indent() << "}" << endl
1235 << endl;
1236
1237 // Generate the declaration of a less-than operator. This must be
1238 // implemented by the application developer if they wish to use it. (They
1239 // will get a link error if they try to use it without an implementation.)
1240 out << indent() << "bool operator < (const " << tstruct->get_name() << " & ) const;" << endl
1241 << endl;
1242 }
1243 }
1244
1245 if (read) {
1246 if (gen_templates_) {
1247 out << indent() << "template <class Protocol_>" << endl << indent()
1248 << "uint32_t read(Protocol_* iprot);" << endl;
1249 } else {
1250 out << indent() << "uint32_t read("
1251 << "::apache::thrift::protocol::TProtocol* iprot);" << endl;
1252 }
1253 }
1254 if (write) {
1255 if (gen_templates_) {
1256 out << indent() << "template <class Protocol_>" << endl << indent()
1257 << "uint32_t write(Protocol_* oprot) const;" << endl;
1258 } else {
1259 out << indent() << "uint32_t write("
1260 << "::apache::thrift::protocol::TProtocol* oprot) const;" << endl;
1261 }
1262 }
1263 out << endl;
1264
1265 if (is_user_struct && !has_custom_ostream(tstruct)) {
1266 out << indent() << "virtual ";
1267 generate_struct_print_method_decl(out, nullptr);
1268 out << ";" << endl;
1269 }
1270
1271 // std::exception::what()
1272 if (is_exception) {
1273 out << indent() << "mutable std::string thriftTExceptionMessageHolder_;" << endl;
1274 out << indent();
1275 generate_exception_what_method_decl(out, tstruct, false);
1276 out << ";" << endl;
1277 }
1278
1279 indent_down();
1280 indent(out) << "};" << endl << endl;
1281
1282 if (swap) {
1283 // Generate a namespace-scope swap() function
1284 if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
1285 out << indent() << "void swap(" << tstruct->get_name() << " &a1, " << tstruct->get_name()
1286 << " &a2);" << endl << endl;
1287 } else {
1288 out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
1289 << " &b);" << endl << endl;
1290 }
1291 }
1292
1293 if (is_user_struct) {
1294 generate_struct_ostream_operator_decl(out, tstruct);
1295 }
1296 }
1297
generate_struct_definition(ostream & out,ostream & force_cpp_out,t_struct * tstruct,bool setters,bool is_user_struct)1298 void t_cpp_generator::generate_struct_definition(ostream& out,
1299 ostream& force_cpp_out,
1300 t_struct* tstruct,
1301 bool setters,
1302 bool is_user_struct) {
1303 // Get members
1304 vector<t_field*>::const_iterator m_iter;
1305 const vector<t_field*>& members = tstruct->get_members();
1306
1307 // Destructor
1308 if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
1309 force_cpp_out << endl << indent() << tstruct->get_name() << "::~" << tstruct->get_name()
1310 << "() noexcept {" << endl;
1311 indent_up();
1312
1313 indent_down();
1314 force_cpp_out << indent() << "}" << endl << endl;
1315 }
1316
1317 // Create a setter function for each field
1318 if (setters) {
1319 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1320 if (is_reference((*m_iter))) {
1321 out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
1322 << (*m_iter)->get_name() << "(::std::shared_ptr<"
1323 << type_name((*m_iter)->get_type(), false, false) << ">";
1324 out << " val) {" << endl;
1325 } else {
1326 out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
1327 << (*m_iter)->get_name() << "(" << type_name((*m_iter)->get_type(), false, true);
1328 out << " val) {" << endl;
1329 }
1330 indent_up();
1331 out << indent() << "this->" << (*m_iter)->get_name() << " = val;" << endl;
1332 indent_down();
1333
1334 // assume all fields are required except optional fields.
1335 // for optional fields change __isset.name to true
1336 bool is_optional = (*m_iter)->get_req() == t_field::T_OPTIONAL;
1337 if (is_optional) {
1338 out << indent() << indent() << "__isset." << (*m_iter)->get_name() << " = true;" << endl;
1339 }
1340 out << indent() << "}" << endl;
1341 }
1342 }
1343 if (is_user_struct) {
1344 generate_struct_ostream_operator(out, tstruct);
1345 }
1346 out << endl;
1347 }
1348
1349 /**
1350 * Makes a helper function to gen a struct reader.
1351 *
1352 * @param out Stream to write to
1353 * @param tstruct The struct
1354 */
generate_struct_reader(ostream & out,t_struct * tstruct,bool pointers)1355 void t_cpp_generator::generate_struct_reader(ostream& out, t_struct* tstruct, bool pointers) {
1356 if (gen_templates_) {
1357 out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
1358 << tstruct->get_name() << "::read(Protocol_* iprot) {" << endl;
1359 } else {
1360 indent(out) << "uint32_t " << tstruct->get_name()
1361 << "::read(::apache::thrift::protocol::TProtocol* iprot) {" << endl;
1362 }
1363 indent_up();
1364
1365 const vector<t_field*>& fields = tstruct->get_members();
1366 vector<t_field*>::const_iterator f_iter;
1367
1368 // Declare stack tmp variables
1369 out << endl
1370 << indent() << "::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);" << endl
1371 << indent() << "uint32_t xfer = 0;" << endl
1372 << indent() << "std::string fname;" << endl
1373 << indent() << "::apache::thrift::protocol::TType ftype;" << endl
1374 << indent() << "int16_t fid;" << endl
1375 << endl
1376 << indent() << "xfer += iprot->readStructBegin(fname);" << endl
1377 << endl
1378 << indent() << "using ::apache::thrift::protocol::TProtocolException;" << endl
1379 << endl;
1380
1381 // Required variables aren't in __isset, so we need tmp vars to check them.
1382 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1383 if ((*f_iter)->get_req() == t_field::T_REQUIRED)
1384 indent(out) << "bool isset_" << (*f_iter)->get_name() << " = false;" << endl;
1385 }
1386 out << endl;
1387
1388 // Loop over reading in fields
1389 indent(out) << "while (true)" << endl;
1390 scope_up(out);
1391
1392 // Read beginning field marker
1393 indent(out) << "xfer += iprot->readFieldBegin(fname, ftype, fid);" << endl;
1394
1395 // Check for field STOP marker
1396 out << indent() << "if (ftype == ::apache::thrift::protocol::T_STOP) {" << endl << indent()
1397 << " break;" << endl << indent() << "}" << endl;
1398
1399 if (fields.empty()) {
1400 out << indent() << "xfer += iprot->skip(ftype);" << endl;
1401 } else {
1402 // Switch statement on the field we are reading
1403 indent(out) << "switch (fid)" << endl;
1404
1405 scope_up(out);
1406
1407 // Generate deserialization code for known cases
1408 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1409 indent(out) << "case " << (*f_iter)->get_key() << ":" << endl;
1410 indent_up();
1411 indent(out) << "if (ftype == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl;
1412 indent_up();
1413
1414 const char* isset_prefix = ((*f_iter)->get_req() != t_field::T_REQUIRED) ? "this->__isset."
1415 : "isset_";
1416
1417 #if 0
1418 // This code throws an exception if the same field is encountered twice.
1419 // We've decided to leave it out for performance reasons.
1420 // TODO(dreiss): Generate this code and "if" it out to make it easier
1421 // for people recompiling thrift to include it.
1422 out <<
1423 indent() << "if (" << isset_prefix << (*f_iter)->get_name() << ")" << endl <<
1424 indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
1425 #endif
1426
1427 if (pointers && !(*f_iter)->get_type()->is_xception()) {
1428 generate_deserialize_field(out, *f_iter, "(*(this->", "))");
1429 } else {
1430 generate_deserialize_field(out, *f_iter, "this->");
1431 }
1432 out << indent() << isset_prefix << (*f_iter)->get_name() << " = true;" << endl;
1433 indent_down();
1434 out << indent() << "} else {" << endl << indent() << " xfer += iprot->skip(ftype);" << endl
1435 <<
1436 // TODO(dreiss): Make this an option when thrift structs
1437 // have a common base class.
1438 // indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl <<
1439 indent() << "}" << endl << indent() << "break;" << endl;
1440 indent_down();
1441 }
1442
1443 // In the default case we skip the field
1444 out << indent() << "default:" << endl << indent() << " xfer += iprot->skip(ftype);" << endl
1445 << indent() << " break;" << endl;
1446
1447 scope_down(out);
1448 } //!fields.empty()
1449 // Read field end marker
1450 indent(out) << "xfer += iprot->readFieldEnd();" << endl;
1451
1452 scope_down(out);
1453
1454 out << endl << indent() << "xfer += iprot->readStructEnd();" << endl;
1455
1456 // Throw if any required fields are missing.
1457 // We do this after reading the struct end so that
1458 // there might possibly be a chance of continuing.
1459 out << endl;
1460 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1461 if ((*f_iter)->get_req() == t_field::T_REQUIRED)
1462 out << indent() << "if (!isset_" << (*f_iter)->get_name() << ')' << endl << indent()
1463 << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
1464 }
1465
1466 indent(out) << "return xfer;" << endl;
1467
1468 indent_down();
1469 indent(out) << "}" << endl << endl;
1470 }
1471
1472 /**
1473 * Generates the write function.
1474 *
1475 * @param out Stream to write to
1476 * @param tstruct The struct
1477 */
generate_struct_writer(ostream & out,t_struct * tstruct,bool pointers)1478 void t_cpp_generator::generate_struct_writer(ostream& out, t_struct* tstruct, bool pointers) {
1479 string name = tstruct->get_name();
1480 const vector<t_field*>& fields = tstruct->get_sorted_members();
1481 vector<t_field*>::const_iterator f_iter;
1482
1483 if (gen_templates_) {
1484 out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
1485 << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
1486 } else {
1487 indent(out) << "uint32_t " << tstruct->get_name()
1488 << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
1489 }
1490 indent_up();
1491
1492 out << indent() << "uint32_t xfer = 0;" << endl;
1493
1494 indent(out) << "::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);" << endl;
1495 indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;
1496
1497 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1498 bool check_if_set = (*f_iter)->get_req() == t_field::T_OPTIONAL
1499 || (*f_iter)->get_type()->is_xception();
1500 if (check_if_set) {
1501 out << endl << indent() << "if (this->__isset." << (*f_iter)->get_name() << ") {" << endl;
1502 indent_up();
1503 } else {
1504 out << endl;
1505 }
1506
1507 // Write field header
1508 out << indent() << "xfer += oprot->writeFieldBegin("
1509 << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
1510 << (*f_iter)->get_key() << ");" << endl;
1511 // Write field contents
1512 if (pointers && !(*f_iter)->get_type()->is_xception()) {
1513 generate_serialize_field(out, *f_iter, "(*(this->", "))");
1514 } else {
1515 generate_serialize_field(out, *f_iter, "this->");
1516 }
1517 // Write field closer
1518 indent(out) << "xfer += oprot->writeFieldEnd();" << endl;
1519 if (check_if_set) {
1520 indent_down();
1521 indent(out) << '}';
1522 }
1523 }
1524
1525 out << endl;
1526
1527 // Write the struct map
1528 out << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
1529 << "xfer += oprot->writeStructEnd();" << endl << indent()
1530 << "return xfer;" << endl;
1531
1532 indent_down();
1533 indent(out) << "}" << endl << endl;
1534 }
1535
1536 /**
1537 * Struct writer for result of a function, which can have only one of its
1538 * fields set and does a conditional if else look up into the __isset field
1539 * of the struct.
1540 *
1541 * @param out Output stream
1542 * @param tstruct The result struct
1543 */
generate_struct_result_writer(ostream & out,t_struct * tstruct,bool pointers)1544 void t_cpp_generator::generate_struct_result_writer(ostream& out,
1545 t_struct* tstruct,
1546 bool pointers) {
1547 string name = tstruct->get_name();
1548 const vector<t_field*>& fields = tstruct->get_sorted_members();
1549 vector<t_field*>::const_iterator f_iter;
1550
1551 if (gen_templates_) {
1552 out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
1553 << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
1554 } else {
1555 indent(out) << "uint32_t " << tstruct->get_name()
1556 << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
1557 }
1558 indent_up();
1559
1560 out << endl << indent() << "uint32_t xfer = 0;" << endl << endl;
1561
1562 indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;
1563
1564 bool first = true;
1565 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1566 if (first) {
1567 first = false;
1568 out << endl << indent() << "if ";
1569 } else {
1570 out << " else if ";
1571 }
1572
1573 out << "(this->__isset." << (*f_iter)->get_name() << ") {" << endl;
1574
1575 indent_up();
1576
1577 // Write field header
1578 out << indent() << "xfer += oprot->writeFieldBegin("
1579 << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
1580 << (*f_iter)->get_key() << ");" << endl;
1581 // Write field contents
1582 if (pointers) {
1583 generate_serialize_field(out, *f_iter, "(*(this->", "))");
1584 } else {
1585 generate_serialize_field(out, *f_iter, "this->");
1586 }
1587 // Write field closer
1588 indent(out) << "xfer += oprot->writeFieldEnd();" << endl;
1589
1590 indent_down();
1591 indent(out) << "}";
1592 }
1593
1594 // Write the struct map
1595 out << endl << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
1596 << "xfer += oprot->writeStructEnd();" << endl << indent() << "return xfer;" << endl;
1597
1598 indent_down();
1599 indent(out) << "}" << endl << endl;
1600 }
1601
1602 /**
1603 * Generates the swap function.
1604 *
1605 * @param out Stream to write to
1606 * @param tstruct The struct
1607 */
generate_struct_swap(ostream & out,t_struct * tstruct)1608 void t_cpp_generator::generate_struct_swap(ostream& out, t_struct* tstruct) {
1609 if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
1610 out << indent() << "void swap(" << tstruct->get_name() << " &a1, " << tstruct->get_name()
1611 << " &a2) {" << endl;
1612 } else {
1613 out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
1614 << " &b) {" << endl;
1615 }
1616
1617 indent_up();
1618
1619 // Let argument-dependent name lookup find the correct swap() function to
1620 // use based on the argument types. If none is found in the arguments'
1621 // namespaces, fall back to ::std::swap().
1622 out << indent() << "using ::std::swap;" << endl;
1623
1624 bool has_nonrequired_fields = false;
1625 const vector<t_field*>& fields = tstruct->get_members();
1626 for (auto tfield : fields) {
1627 if (tfield->get_req() != t_field::T_REQUIRED) {
1628 has_nonrequired_fields = true;
1629 }
1630
1631 if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
1632 out << indent() << "swap(a1." << tfield->get_name() << ", a2." << tfield->get_name() << ");"
1633 << endl;
1634 } else {
1635 out << indent() << "swap(a." << tfield->get_name() << ", b." << tfield->get_name() << ");"
1636 << endl;
1637 }
1638 }
1639
1640 if (has_nonrequired_fields) {
1641 if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
1642 out << indent() << "swap(a1.__isset, a2.__isset);" << endl;
1643 } else {
1644 out << indent() << "swap(a.__isset, b.__isset);" << endl;
1645 }
1646 }
1647
1648 // handle empty structs
1649 if (fields.size() == 0) {
1650 if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
1651 out << indent() << "(void) a1;" << endl;
1652 out << indent() << "(void) a2;" << endl;
1653 } else {
1654 out << indent() << "(void) a;" << endl;
1655 out << indent() << "(void) b;" << endl;
1656 }
1657 }
1658
1659 scope_down(out);
1660 out << endl;
1661 }
1662
generate_struct_ostream_operator_decl(std::ostream & out,t_struct * tstruct)1663 void t_cpp_generator::generate_struct_ostream_operator_decl(std::ostream& out, t_struct* tstruct) {
1664 out << "std::ostream& operator<<(std::ostream& out, const "
1665 << tstruct->get_name()
1666 << "& obj);" << endl;
1667 out << endl;
1668 }
1669
generate_struct_ostream_operator(std::ostream & out,t_struct * tstruct)1670 void t_cpp_generator::generate_struct_ostream_operator(std::ostream& out, t_struct* tstruct) {
1671 if (!has_custom_ostream(tstruct)) {
1672 // thrift defines this behavior
1673 out << "std::ostream& operator<<(std::ostream& out, const "
1674 << tstruct->get_name()
1675 << "& obj)" << endl;
1676 scope_up(out);
1677 out << indent() << "obj.printTo(out);" << endl
1678 << indent() << "return out;" << endl;
1679 scope_down(out);
1680 out << endl;
1681 }
1682 }
1683
generate_struct_print_method_decl(std::ostream & out,t_struct * tstruct)1684 void t_cpp_generator::generate_struct_print_method_decl(std::ostream& out, t_struct* tstruct) {
1685 out << "void ";
1686 if (tstruct) {
1687 out << tstruct->get_name() << "::";
1688 }
1689 out << "printTo(std::ostream& out) const";
1690 }
1691
generate_exception_what_method_decl(std::ostream & out,t_struct * tstruct,bool external)1692 void t_cpp_generator::generate_exception_what_method_decl(std::ostream& out,
1693 t_struct* tstruct,
1694 bool external) {
1695 out << "const char* ";
1696 if (external) {
1697 out << tstruct->get_name() << "::";
1698 }
1699 out << "what() const noexcept";
1700 }
1701
1702 namespace struct_ostream_operator_generator {
generate_required_field_value(std::ostream & out,const t_field * field)1703 void generate_required_field_value(std::ostream& out, const t_field* field) {
1704 out << " << to_string(" << field->get_name() << ")";
1705 }
1706
generate_optional_field_value(std::ostream & out,const t_field * field)1707 void generate_optional_field_value(std::ostream& out, const t_field* field) {
1708 out << "; (__isset." << field->get_name() << " ? (out";
1709 generate_required_field_value(out, field);
1710 out << ") : (out << \"<null>\"))";
1711 }
1712
generate_field_value(std::ostream & out,const t_field * field)1713 void generate_field_value(std::ostream& out, const t_field* field) {
1714 if (field->get_req() == t_field::T_OPTIONAL)
1715 generate_optional_field_value(out, field);
1716 else
1717 generate_required_field_value(out, field);
1718 }
1719
generate_field_name(std::ostream & out,const t_field * field)1720 void generate_field_name(std::ostream& out, const t_field* field) {
1721 out << "\"" << field->get_name() << "=\"";
1722 }
1723
generate_field(std::ostream & out,const t_field * field)1724 void generate_field(std::ostream& out, const t_field* field) {
1725 generate_field_name(out, field);
1726 generate_field_value(out, field);
1727 }
1728
generate_fields(std::ostream & out,const vector<t_field * > & fields,const std::string & indent)1729 void generate_fields(std::ostream& out,
1730 const vector<t_field*>& fields,
1731 const std::string& indent) {
1732 const vector<t_field*>::const_iterator beg = fields.begin();
1733 const vector<t_field*>::const_iterator end = fields.end();
1734
1735 for (vector<t_field*>::const_iterator it = beg; it != end; ++it) {
1736 out << indent << "out << ";
1737
1738 if (it != beg) {
1739 out << "\", \" << ";
1740 }
1741
1742 generate_field(out, *it);
1743 out << ";" << endl;
1744 }
1745 }
1746 }
1747
1748 /**
1749 * Generates operator<<
1750 */
generate_struct_print_method(std::ostream & out,t_struct * tstruct)1751 void t_cpp_generator::generate_struct_print_method(std::ostream& out, t_struct* tstruct) {
1752 out << indent();
1753 generate_struct_print_method_decl(out, tstruct);
1754 out << " {" << endl;
1755
1756 indent_up();
1757
1758 out << indent() << "using ::apache::thrift::to_string;" << endl;
1759 out << indent() << "out << \"" << tstruct->get_name() << "(\";" << endl;
1760 struct_ostream_operator_generator::generate_fields(out, tstruct->get_members(), indent());
1761 out << indent() << "out << \")\";" << endl;
1762
1763 indent_down();
1764 out << "}" << endl << endl;
1765 }
1766
1767 /**
1768 * Generates what() method for exceptions
1769 */
generate_exception_what_method(std::ostream & out,t_struct * tstruct)1770 void t_cpp_generator::generate_exception_what_method(std::ostream& out, t_struct* tstruct) {
1771 out << indent();
1772 generate_exception_what_method_decl(out, tstruct, true);
1773 out << " {" << endl;
1774
1775 indent_up();
1776 out << indent() << "try {" << endl;
1777
1778 indent_up();
1779 out << indent() << "std::stringstream ss;" << endl;
1780 out << indent() << "ss << \"TException - service has thrown: \" << *this;" << endl;
1781 out << indent() << "this->thriftTExceptionMessageHolder_ = ss.str();" << endl;
1782 out << indent() << "return this->thriftTExceptionMessageHolder_.c_str();" << endl;
1783 indent_down();
1784
1785 out << indent() << "} catch (const std::exception&) {" << endl;
1786
1787 indent_up();
1788 out << indent() << "return \"TException - service has thrown: " << tstruct->get_name() << "\";"
1789 << endl;
1790 indent_down();
1791
1792 out << indent() << "}" << endl;
1793
1794 indent_down();
1795 out << "}" << endl << endl;
1796 }
1797
1798 /**
1799 * Generates a thrift service. In C++, this comprises an entirely separate
1800 * header and source file. The header file defines the methods and includes
1801 * the data types defined in the main header file, and the implementation
1802 * file contains implementations of the basic printer and default interfaces.
1803 *
1804 * @param tservice The service definition
1805 */
generate_service(t_service * tservice)1806 void t_cpp_generator::generate_service(t_service* tservice) {
1807 string svcname = tservice->get_name();
1808
1809 // Make output files
1810 string f_header_name = get_out_dir() + svcname + ".h";
1811 f_header_.open(f_header_name.c_str());
1812
1813 // Print header file includes
1814 f_header_ << autogen_comment();
1815 f_header_ << "#ifndef " << svcname << "_H" << endl << "#define " << svcname << "_H" << endl
1816 << endl;
1817 if (gen_cob_style_) {
1818 f_header_ << "#include <thrift/transport/TBufferTransports.h>" << endl // TMemoryBuffer
1819 << "#include <functional>" << endl
1820 << "namespace apache { namespace thrift { namespace async {" << endl
1821 << "class TAsyncChannel;" << endl << "}}}" << endl;
1822 }
1823 f_header_ << "#include <thrift/TDispatchProcessor.h>" << endl;
1824 if (gen_cob_style_) {
1825 f_header_ << "#include <thrift/async/TAsyncDispatchProcessor.h>" << endl;
1826 }
1827 f_header_ << "#include <thrift/async/TConcurrentClientSyncInfo.h>" << endl;
1828 f_header_ << "#include <memory>" << endl;
1829 f_header_ << "#include \"" << get_include_prefix(*get_program()) << program_name_ << "_types.h\""
1830 << endl;
1831
1832 t_service* extends_service = tservice->get_extends();
1833 if (extends_service != nullptr) {
1834 f_header_ << "#include \"" << get_include_prefix(*(extends_service->get_program()))
1835 << extends_service->get_name() << ".h\"" << endl;
1836 }
1837
1838 f_header_ << endl << ns_open_ << endl << endl;
1839
1840 f_header_ << "#ifdef _MSC_VER\n"
1841 " #pragma warning( push )\n"
1842 " #pragma warning (disable : 4250 ) //inheriting methods via dominance \n"
1843 "#endif\n\n";
1844
1845 // Service implementation file includes
1846 string f_service_name = get_out_dir() + svcname + ".cpp";
1847 f_service_.open(f_service_name.c_str());
1848 f_service_ << autogen_comment();
1849 f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl;
1850 if (gen_cob_style_) {
1851 f_service_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
1852 }
1853 if (gen_templates_) {
1854 f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\""
1855 << endl;
1856
1857 string f_service_tcc_name = get_out_dir() + svcname + ".tcc";
1858 f_service_tcc_.open(f_service_tcc_name.c_str());
1859 f_service_tcc_ << autogen_comment();
1860 f_service_tcc_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\""
1861 << endl;
1862
1863 f_service_tcc_ << "#ifndef " << svcname << "_TCC" << endl << "#define " << svcname << "_TCC"
1864 << endl << endl;
1865
1866 if (gen_cob_style_) {
1867 f_service_tcc_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
1868 }
1869 }
1870
1871 f_service_ << endl << ns_open_ << endl << endl;
1872 f_service_tcc_ << endl << ns_open_ << endl << endl;
1873
1874 // Generate all the components
1875 generate_service_interface(tservice, "");
1876 generate_service_interface_factory(tservice, "");
1877 generate_service_null(tservice, "");
1878 generate_service_helpers(tservice);
1879 generate_service_client(tservice, "");
1880 generate_service_processor(tservice, "");
1881 generate_service_multiface(tservice);
1882 generate_service_client(tservice, "Concurrent");
1883
1884 // Generate skeleton
1885 if (!gen_no_skeleton_) {
1886 generate_service_skeleton(tservice);
1887 }
1888
1889 // Generate all the cob components
1890 if (gen_cob_style_) {
1891 generate_service_interface(tservice, "CobCl");
1892 generate_service_interface(tservice, "CobSv");
1893 generate_service_interface_factory(tservice, "CobSv");
1894 generate_service_null(tservice, "CobSv");
1895 generate_service_client(tservice, "Cob");
1896 generate_service_processor(tservice, "Cob");
1897
1898 if (!gen_no_skeleton_) {
1899 generate_service_async_skeleton(tservice);
1900 }
1901
1902 }
1903
1904 f_header_ << "#ifdef _MSC_VER\n"
1905 " #pragma warning( pop )\n"
1906 "#endif\n\n";
1907
1908 // Close the namespace
1909 f_service_ << ns_close_ << endl << endl;
1910 f_service_tcc_ << ns_close_ << endl << endl;
1911 f_header_ << ns_close_ << endl << endl;
1912
1913 // TODO(simpkins): Make this a separate option
1914 if (gen_templates_) {
1915 f_header_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\"" << endl
1916 << "#include \"" << get_include_prefix(*get_program()) << program_name_
1917 << "_types.tcc\"" << endl << endl;
1918 }
1919
1920 f_header_ << "#endif" << endl;
1921 f_service_tcc_ << "#endif" << endl;
1922
1923 // Close the files
1924 f_service_tcc_.close();
1925 f_service_.close();
1926 f_header_.close();
1927 }
1928
1929 /**
1930 * Generates helper functions for a service. Basically, this generates types
1931 * for all the arguments and results to functions.
1932 *
1933 * @param tservice The service to generate a header definition for
1934 */
generate_service_helpers(t_service * tservice)1935 void t_cpp_generator::generate_service_helpers(t_service* tservice) {
1936 vector<t_function*> functions = tservice->get_functions();
1937 vector<t_function*>::iterator f_iter;
1938 std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
1939
1940 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
1941 t_struct* ts = (*f_iter)->get_arglist();
1942 string name_orig = ts->get_name();
1943
1944 // TODO(dreiss): Why is this stuff not in generate_function_helpers?
1945 ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_args");
1946 generate_struct_declaration(f_header_, ts, false);
1947 generate_struct_definition(out, f_service_, ts, false);
1948 generate_struct_reader(out, ts);
1949 generate_struct_writer(out, ts);
1950 ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs");
1951 generate_struct_declaration(f_header_, ts, false, true, false, true);
1952 generate_struct_definition(out, f_service_, ts, false);
1953 generate_struct_writer(out, ts, true);
1954 ts->set_name(name_orig);
1955
1956 generate_function_helpers(tservice, *f_iter);
1957 }
1958 }
1959
1960 /**
1961 * Generates a service interface definition.
1962 *
1963 * @param tservice The service to generate a header definition for
1964 */
generate_service_interface(t_service * tservice,string style)1965 void t_cpp_generator::generate_service_interface(t_service* tservice, string style) {
1966
1967 string service_if_name = service_name_ + style + "If";
1968 if (style == "CobCl") {
1969 // Forward declare the client.
1970 string client_name = service_name_ + "CobClient";
1971 if (gen_templates_) {
1972 client_name += "T";
1973 service_if_name += "T";
1974 indent(f_header_) << "template <class Protocol_>" << endl;
1975 }
1976 indent(f_header_) << "class " << client_name << ";" << endl << endl;
1977 }
1978
1979 string extends = "";
1980 if (tservice->get_extends() != nullptr) {
1981 extends = " : virtual public " + type_name(tservice->get_extends()) + style + "If";
1982 if (style == "CobCl" && gen_templates_) {
1983 // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
1984 // parent services were also generated with templates enabled.
1985 extends += "T<Protocol_>";
1986 }
1987 }
1988
1989 if (style == "CobCl" && gen_templates_) {
1990 f_header_ << "template <class Protocol_>" << endl;
1991 }
1992
1993 generate_java_doc(f_header_, tservice);
1994
1995 f_header_ << "class " << service_if_name << extends << " {" << endl << " public:" << endl;
1996 indent_up();
1997 f_header_ << indent() << "virtual ~" << service_if_name << "() {}" << endl;
1998
1999 vector<t_function*> functions = tservice->get_functions();
2000 vector<t_function*>::iterator f_iter;
2001 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2002 if ((*f_iter)->has_doc())
2003 f_header_ << endl;
2004 generate_java_doc(f_header_, *f_iter);
2005 f_header_ << indent() << "virtual " << function_signature(*f_iter, style) << " = 0;" << endl;
2006 }
2007 indent_down();
2008 f_header_ << "};" << endl << endl;
2009
2010 if (style == "CobCl" && gen_templates_) {
2011 // generate a backwards-compatible typedef for clients that do not
2012 // know about the new template-style code
2013 f_header_ << "typedef " << service_if_name << "< ::apache::thrift::protocol::TProtocol> "
2014 << service_name_ << style << "If;" << endl << endl;
2015 }
2016 }
2017
2018 /**
2019 * Generates a service interface factory.
2020 *
2021 * @param tservice The service to generate an interface factory for.
2022 */
generate_service_interface_factory(t_service * tservice,string style)2023 void t_cpp_generator::generate_service_interface_factory(t_service* tservice, string style) {
2024 string service_if_name = service_name_ + style + "If";
2025
2026 // Figure out the name of the upper-most parent class.
2027 // Getting everything to work out properly with inheritance is annoying.
2028 // Here's what we're doing for now:
2029 //
2030 // - All handlers implement getHandler(), but subclasses use covariant return
2031 // types to return their specific service interface class type. We have to
2032 // use raw pointers because of this; shared_ptr<> can't be used for
2033 // covariant return types.
2034 //
2035 // - Since we're not using shared_ptr<>, we also provide a releaseHandler()
2036 // function that must be called to release a pointer to a handler obtained
2037 // via getHandler().
2038 //
2039 // releaseHandler() always accepts a pointer to the upper-most parent class
2040 // type. This is necessary since the parent versions of releaseHandler()
2041 // may accept any of the parent types, not just the most specific subclass
2042 // type. Implementations can use dynamic_cast to cast the pointer to the
2043 // subclass type if desired.
2044 t_service* base_service = tservice;
2045 while (base_service->get_extends() != nullptr) {
2046 base_service = base_service->get_extends();
2047 }
2048 string base_if_name = type_name(base_service) + style + "If";
2049
2050 // Generate the abstract factory class
2051 string factory_name = service_if_name + "Factory";
2052 string extends;
2053 if (tservice->get_extends() != nullptr) {
2054 extends = " : virtual public " + type_name(tservice->get_extends()) + style + "IfFactory";
2055 }
2056
2057 f_header_ << "class " << factory_name << extends << " {" << endl << " public:" << endl;
2058 indent_up();
2059 f_header_ << indent() << "typedef " << service_if_name << " Handler;" << endl << endl << indent()
2060 << "virtual ~" << factory_name << "() {}" << endl << endl << indent() << "virtual "
2061 << service_if_name << "* getHandler("
2062 << "const ::apache::thrift::TConnectionInfo& connInfo) = 0;" << endl << indent()
2063 << "virtual void releaseHandler(" << base_if_name << "* /* handler */) = 0;" << endl;
2064
2065 indent_down();
2066 f_header_ << "};" << endl << endl;
2067
2068 // Generate the singleton factory class
2069 string singleton_factory_name = service_if_name + "SingletonFactory";
2070 f_header_ << "class " << singleton_factory_name << " : virtual public " << factory_name << " {"
2071 << endl << " public:" << endl;
2072 indent_up();
2073 f_header_ << indent() << singleton_factory_name << "(const ::std::shared_ptr<" << service_if_name
2074 << ">& iface) : iface_(iface) {}" << endl << indent() << "virtual ~"
2075 << singleton_factory_name << "() {}" << endl << endl << indent() << "virtual "
2076 << service_if_name << "* getHandler("
2077 << "const ::apache::thrift::TConnectionInfo&) {" << endl << indent()
2078 << " return iface_.get();" << endl << indent() << "}" << endl << indent()
2079 << "virtual void releaseHandler(" << base_if_name << "* /* handler */) {}" << endl;
2080
2081 f_header_ << endl << " protected:" << endl << indent() << "::std::shared_ptr<" << service_if_name
2082 << "> iface_;" << endl;
2083
2084 indent_down();
2085 f_header_ << "};" << endl << endl;
2086 }
2087
2088 /**
2089 * Generates a null implementation of the service.
2090 *
2091 * @param tservice The service to generate a header definition for
2092 */
generate_service_null(t_service * tservice,string style)2093 void t_cpp_generator::generate_service_null(t_service* tservice, string style) {
2094 string extends = "";
2095 if (tservice->get_extends() != nullptr) {
2096 extends = " , virtual public " + type_name(tservice->get_extends()) + style + "Null";
2097 }
2098 f_header_ << "class " << service_name_ << style << "Null : virtual public " << service_name_
2099 << style << "If" << extends << " {" << endl << " public:" << endl;
2100 indent_up();
2101 f_header_ << indent() << "virtual ~" << service_name_ << style << "Null() {}" << endl;
2102 vector<t_function*> functions = tservice->get_functions();
2103 vector<t_function*>::iterator f_iter;
2104 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2105 f_header_ << indent() << function_signature(*f_iter, style, "", false) << " {" << endl;
2106 indent_up();
2107
2108 t_type* returntype = (*f_iter)->get_returntype();
2109 t_field returnfield(returntype, "_return");
2110
2111 if (style == "") {
2112 if (returntype->is_void() || is_complex_type(returntype)) {
2113 f_header_ << indent() << "return;" << endl;
2114 } else {
2115 f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
2116 << "return _return;" << endl;
2117 }
2118 } else if (style == "CobSv") {
2119 if (returntype->is_void()) {
2120 f_header_ << indent() << "return cob();" << endl;
2121 } else {
2122 t_field returnfield(returntype, "_return");
2123 f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
2124 << "return cob(_return);" << endl;
2125 }
2126
2127 } else {
2128 throw "UNKNOWN STYLE";
2129 }
2130
2131 indent_down();
2132 f_header_ << indent() << "}" << endl;
2133 }
2134 indent_down();
2135 f_header_ << "};" << endl << endl;
2136 }
2137
generate_function_call(ostream & out,t_function * tfunction,string target,string iface,string arg_prefix)2138 void t_cpp_generator::generate_function_call(ostream& out,
2139 t_function* tfunction,
2140 string target,
2141 string iface,
2142 string arg_prefix) {
2143 bool first = true;
2144 t_type* ret_type = get_true_type(tfunction->get_returntype());
2145 out << indent();
2146 if (!tfunction->is_oneway() && !ret_type->is_void()) {
2147 if (is_complex_type(ret_type)) {
2148 first = false;
2149 out << iface << "->" << tfunction->get_name() << "(" << target;
2150 } else {
2151 out << target << " = " << iface << "->" << tfunction->get_name() << "(";
2152 }
2153 } else {
2154 out << iface << "->" << tfunction->get_name() << "(";
2155 }
2156 const std::vector<t_field*>& fields = tfunction->get_arglist()->get_members();
2157 vector<t_field*>::const_iterator f_iter;
2158 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2159 if (first) {
2160 first = false;
2161 } else {
2162 out << ", ";
2163 }
2164 out << arg_prefix << (*f_iter)->get_name();
2165 }
2166 out << ");" << endl;
2167 }
2168
generate_service_async_skeleton(t_service * tservice)2169 void t_cpp_generator::generate_service_async_skeleton(t_service* tservice) {
2170 string svcname = tservice->get_name();
2171
2172 // Service implementation file includes
2173 string f_skeleton_name = get_out_dir() + svcname + "_async_server.skeleton.cpp";
2174
2175 string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));
2176
2177 ofstream_with_content_based_conditional_update f_skeleton;
2178 f_skeleton.open(f_skeleton_name.c_str());
2179 f_skeleton << "// This autogenerated skeleton file illustrates one way to adapt a synchronous"
2180 << endl << "// interface into an asynchronous interface. You should copy it to another"
2181 << endl
2182 << "// filename to avoid overwriting it and rewrite as asynchronous any functions"
2183 << endl << "// that would otherwise introduce unwanted latency." << endl << endl
2184 << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
2185 << "#include <thrift/protocol/TBinaryProtocol.h>" << endl
2186 << "#include <thrift/async/TAsyncProtocolProcessor.h>" << endl
2187 << "#include <thrift/async/TEvhttpServer.h>" << endl
2188 << "#include <event.h>" << endl
2189 << "#include <evhttp.h>" << endl << endl
2190 << "using namespace ::apache::thrift;" << endl
2191 << "using namespace ::apache::thrift::protocol;" << endl
2192 << "using namespace ::apache::thrift::transport;" << endl
2193 << "using namespace ::apache::thrift::async;" << endl << endl;
2194
2195 // the following code would not compile:
2196 // using namespace ;
2197 // using namespace ::;
2198 if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
2199 f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
2200 }
2201
2202 f_skeleton << "class " << svcname << "Handler : virtual public " << svcname << "If {" << endl
2203 << " public:" << endl;
2204 indent_up();
2205 f_skeleton << indent() << svcname << "Handler() {" << endl << indent()
2206 << " // Your initialization goes here" << endl << indent() << "}" << endl << endl;
2207
2208 vector<t_function*> functions = tservice->get_functions();
2209 vector<t_function*>::iterator f_iter;
2210 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2211 generate_java_doc(f_skeleton, *f_iter);
2212 f_skeleton << indent() << function_signature(*f_iter, "") << " {" << endl << indent()
2213 << " // Your implementation goes here" << endl << indent() << " printf(\""
2214 << (*f_iter)->get_name() << "\\n\");" << endl << indent() << "}" << endl << endl;
2215 }
2216
2217 indent_down();
2218 f_skeleton << "};" << endl << endl;
2219
2220 f_skeleton << "class " << svcname << "AsyncHandler : "
2221 << "public " << svcname << "CobSvIf {" << endl << " public:" << endl;
2222 indent_up();
2223 f_skeleton << indent() << svcname << "AsyncHandler() {" << endl << indent()
2224 << " syncHandler_ = std::unique_ptr<" << svcname << "Handler>(new " << svcname
2225 << "Handler);" << endl << indent() << " // Your initialization goes here" << endl
2226 << indent() << "}" << endl;
2227 f_skeleton << indent() << "virtual ~" << service_name_ << "AsyncHandler();" << endl;
2228
2229 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2230 f_skeleton << endl << indent() << function_signature(*f_iter, "CobSv", "", true) << " {"
2231 << endl;
2232 indent_up();
2233
2234 t_type* returntype = (*f_iter)->get_returntype();
2235 t_field returnfield(returntype, "_return");
2236
2237 string target = returntype->is_void() ? "" : "_return";
2238 if (!returntype->is_void()) {
2239 f_skeleton << indent() << declare_field(&returnfield, true) << endl;
2240 }
2241 generate_function_call(f_skeleton, *f_iter, target, "syncHandler_", "");
2242 f_skeleton << indent() << "return cob(" << target << ");" << endl;
2243
2244 scope_down(f_skeleton);
2245 }
2246 f_skeleton << endl << " protected:" << endl << indent() << "std::unique_ptr<" << svcname
2247 << "Handler> syncHandler_;" << endl;
2248 indent_down();
2249 f_skeleton << "};" << endl << endl;
2250
2251 f_skeleton << indent() << "int main(int argc, char **argv) {" << endl;
2252 indent_up();
2253 f_skeleton
2254 << indent() << "int port = 9090;" << endl << indent() << "::std::shared_ptr<" << svcname
2255 << "AsyncHandler> handler(new " << svcname << "AsyncHandler());" << endl << indent()
2256 << "::std::shared_ptr<" << svcname << "AsyncProcessor> processor(new " << svcname << "AsyncProcessor(handler));" << endl
2257 << indent() << "::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());"
2258 << endl
2259 << indent() << "::std::shared_ptr<TAsyncProtocolProcessor> protocolProcessor(new TAsyncProtocolProcessor(processor, protocolFactory));"
2260 << endl << endl << indent()
2261 << "TEvhttpServer server(protocolProcessor, port);"
2262 << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl;
2263 indent_down();
2264 f_skeleton << "}" << endl << endl;
2265 }
2266
2267 /**
2268 * Generates a multiface, which is a single server that just takes a set
2269 * of objects implementing the interface and calls them all, returning the
2270 * value of the last one to be called.
2271 *
2272 * @param tservice The service to generate a multiserver for.
2273 */
generate_service_multiface(t_service * tservice)2274 void t_cpp_generator::generate_service_multiface(t_service* tservice) {
2275 // Generate the dispatch methods
2276 vector<t_function*> functions = tservice->get_functions();
2277 vector<t_function*>::iterator f_iter;
2278
2279 string extends = "";
2280 string extends_multiface = "";
2281 if (tservice->get_extends() != nullptr) {
2282 extends = type_name(tservice->get_extends());
2283 extends_multiface = ", public " + extends + "Multiface";
2284 }
2285
2286 string list_type = string("std::vector<std::shared_ptr<") + service_name_ + "If> >";
2287
2288 // Generate the header portion
2289 f_header_ << "class " << service_name_ << "Multiface : "
2290 << "virtual public " << service_name_ << "If" << extends_multiface << " {" << endl
2291 << " public:" << endl;
2292 indent_up();
2293 f_header_ << indent() << service_name_ << "Multiface(" << list_type
2294 << "& ifaces) : ifaces_(ifaces) {" << endl;
2295 if (!extends.empty()) {
2296 f_header_ << indent()
2297 << " std::vector<std::shared_ptr<" + service_name_ + "If> >::iterator iter;"
2298 << endl << indent() << " for (iter = ifaces.begin(); iter != ifaces.end(); ++iter) {"
2299 << endl << indent() << " " << extends << "Multiface::add(*iter);" << endl
2300 << indent() << " }" << endl;
2301 }
2302 f_header_ << indent() << "}" << endl << indent() << "virtual ~" << service_name_
2303 << "Multiface() {}" << endl;
2304 indent_down();
2305
2306 // Protected data members
2307 f_header_ << " protected:" << endl;
2308 indent_up();
2309 f_header_ << indent() << list_type << " ifaces_;" << endl << indent() << service_name_
2310 << "Multiface() {}" << endl << indent() << "void add(::std::shared_ptr<"
2311 << service_name_ << "If> iface) {" << endl;
2312 if (!extends.empty()) {
2313 f_header_ << indent() << " " << extends << "Multiface::add(iface);" << endl;
2314 }
2315 f_header_ << indent() << " ifaces_.push_back(iface);" << endl << indent() << "}" << endl;
2316 indent_down();
2317
2318 f_header_ << indent() << " public:" << endl;
2319 indent_up();
2320
2321 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2322 generate_java_doc(f_header_, *f_iter);
2323 t_struct* arglist = (*f_iter)->get_arglist();
2324 const vector<t_field*>& args = arglist->get_members();
2325 vector<t_field*>::const_iterator a_iter;
2326
2327 string call = string("ifaces_[i]->") + (*f_iter)->get_name() + "(";
2328 bool first = true;
2329 if (is_complex_type((*f_iter)->get_returntype())) {
2330 call += "_return";
2331 first = false;
2332 }
2333 for (a_iter = args.begin(); a_iter != args.end(); ++a_iter) {
2334 if (first) {
2335 first = false;
2336 } else {
2337 call += ", ";
2338 }
2339 call += (*a_iter)->get_name();
2340 }
2341 call += ")";
2342
2343 f_header_ << indent() << function_signature(*f_iter, "") << " {" << endl;
2344 indent_up();
2345 f_header_ << indent() << "size_t sz = ifaces_.size();" << endl << indent() << "size_t i = 0;"
2346 << endl << indent() << "for (; i < (sz - 1); ++i) {" << endl;
2347 indent_up();
2348 f_header_ << indent() << call << ";" << endl;
2349 indent_down();
2350 f_header_ << indent() << "}" << endl;
2351
2352 if (!(*f_iter)->get_returntype()->is_void()) {
2353 if (is_complex_type((*f_iter)->get_returntype())) {
2354 f_header_ << indent() << call << ";" << endl << indent() << "return;" << endl;
2355 } else {
2356 f_header_ << indent() << "return " << call << ";" << endl;
2357 }
2358 } else {
2359 f_header_ << indent() << call << ";" << endl;
2360 }
2361
2362 indent_down();
2363 f_header_ << indent() << "}" << endl << endl;
2364 }
2365
2366 indent_down();
2367 f_header_ << indent() << "};" << endl << endl;
2368 }
2369
2370 /**
2371 * Generates a service client definition.
2372 *
2373 * @param tservice The service to generate a server for.
2374 */
generate_service_client(t_service * tservice,string style)2375 void t_cpp_generator::generate_service_client(t_service* tservice, string style) {
2376 string ifstyle;
2377 if (style == "Cob") {
2378 ifstyle = "CobCl";
2379 }
2380
2381 std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
2382 string template_header, template_suffix, short_suffix, protocol_type, _this;
2383 string const prot_factory_type = "::apache::thrift::protocol::TProtocolFactory";
2384 if (gen_templates_) {
2385 template_header = "template <class Protocol_>\n";
2386 short_suffix = "T";
2387 template_suffix = "T<Protocol_>";
2388 protocol_type = "Protocol_";
2389 _this = "this->";
2390 } else {
2391 protocol_type = "::apache::thrift::protocol::TProtocol";
2392 }
2393 string prot_ptr = "std::shared_ptr< " + protocol_type + ">";
2394 string client_suffix = "Client" + template_suffix;
2395 string if_suffix = "If";
2396 if (style == "Cob") {
2397 if_suffix += template_suffix;
2398 }
2399
2400 string extends = "";
2401 string extends_client = "";
2402 if (tservice->get_extends() != nullptr) {
2403 // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
2404 // parent services were also generated with templates enabled.
2405 extends = type_name(tservice->get_extends());
2406 extends_client = ", public " + extends + style + client_suffix;
2407 }
2408
2409 // Generate the header portion
2410 if (style == "Concurrent") {
2411 f_header_ << "// The \'concurrent\' client is a thread safe client that correctly handles\n"
2412 "// out of order responses. It is slower than the regular client, so should\n"
2413 "// only be used when you need to share a connection among multiple threads\n";
2414 }
2415 f_header_ << template_header << "class " << service_name_ << style << "Client" << short_suffix
2416 << " : "
2417 << "virtual public " << service_name_ << ifstyle << if_suffix << extends_client << " {"
2418 << endl << " public:" << endl;
2419
2420 indent_up();
2421 if (style != "Cob") {
2422 f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
2423 << " prot";
2424 if (style == "Concurrent") {
2425 f_header_ << ", std::shared_ptr<::apache::thrift::async::TConcurrentClientSyncInfo> sync";
2426 }
2427 f_header_ << ") ";
2428
2429 if (extends.empty()) {
2430 if (style == "Concurrent") {
2431 f_header_ << ": sync_(sync)" << endl;
2432 }
2433 f_header_ << "{" << endl;
2434 f_header_ << indent() << " setProtocol" << short_suffix << "(prot);" << endl << indent()
2435 << "}" << endl;
2436 } else {
2437 f_header_ << ":" << endl;
2438 f_header_ << indent() << " " << extends << style << client_suffix << "(prot, prot";
2439 if (style == "Concurrent") {
2440 f_header_ << ", sync";
2441 }
2442 f_header_ << ") {}" << endl;
2443 }
2444
2445 f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
2446 << " iprot, " << prot_ptr << " oprot";
2447 if (style == "Concurrent") {
2448 f_header_ << ", std::shared_ptr<::apache::thrift::async::TConcurrentClientSyncInfo> sync";
2449 }
2450 f_header_ << ") ";
2451
2452 if (extends.empty()) {
2453 if (style == "Concurrent") {
2454 f_header_ << ": sync_(sync)" << endl;
2455 }
2456 f_header_ << "{" << endl;
2457 f_header_ << indent() << " setProtocol" << short_suffix << "(iprot,oprot);" << endl
2458 << indent() << "}" << endl;
2459 } else {
2460 f_header_ << ":" << indent() << " " << extends << style << client_suffix
2461 << "(iprot, oprot";
2462 if (style == "Concurrent") {
2463 f_header_ << ", sync";
2464 }
2465 f_header_ << ") {}" << endl;
2466 }
2467
2468 // create the setProtocol methods
2469 if (extends.empty()) {
2470 f_header_ << " private:" << endl;
2471 // 1: one parameter
2472 f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " prot) {"
2473 << endl;
2474 f_header_ << indent() << "setProtocol" << short_suffix << "(prot,prot);" << endl;
2475 f_header_ << indent() << "}" << endl;
2476 // 2: two parameter
2477 f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " iprot, "
2478 << prot_ptr << " oprot) {" << endl;
2479
2480 f_header_ << indent() << " piprot_=iprot;" << endl << indent() << " poprot_=oprot;" << endl
2481 << indent() << " iprot_ = iprot.get();" << endl << indent()
2482 << " oprot_ = oprot.get();" << endl;
2483
2484 f_header_ << indent() << "}" << endl;
2485 f_header_ << " public:" << endl;
2486 }
2487
2488 // Generate getters for the protocols.
2489 // Note that these are not currently templated for simplicity.
2490 // TODO(simpkins): should they be templated?
2491 f_header_ << indent()
2492 << "std::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {"
2493 << endl << indent() << " return " << _this << "piprot_;" << endl << indent() << "}"
2494 << endl;
2495
2496 f_header_ << indent()
2497 << "std::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {"
2498 << endl << indent() << " return " << _this << "poprot_;" << endl << indent() << "}"
2499 << endl;
2500
2501 } else /* if (style == "Cob") */ {
2502 f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "("
2503 << "std::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, "
2504 << "::apache::thrift::protocol::TProtocolFactory* protocolFactory) :" << endl;
2505 if (extends.empty()) {
2506 f_header_ << indent() << " channel_(channel)," << endl << indent()
2507 << " itrans_(new ::apache::thrift::transport::TMemoryBuffer())," << endl
2508 << indent() << " otrans_(new ::apache::thrift::transport::TMemoryBuffer()),"
2509 << endl;
2510 if (gen_templates_) {
2511 // TProtocolFactory classes return generic TProtocol pointers.
2512 // We have to dynamic cast to the Protocol_ type we are expecting.
2513 f_header_ << indent() << " piprot_(::std::dynamic_pointer_cast<Protocol_>("
2514 << "protocolFactory->getProtocol(itrans_)))," << endl << indent()
2515 << " poprot_(::std::dynamic_pointer_cast<Protocol_>("
2516 << "protocolFactory->getProtocol(otrans_))) {" << endl;
2517 // Throw a TException if either dynamic cast failed.
2518 f_header_ << indent() << " if (!piprot_ || !poprot_) {" << endl << indent()
2519 << " throw ::apache::thrift::TException(\""
2520 << "TProtocolFactory returned unexpected protocol type in " << service_name_
2521 << style << "Client" << short_suffix << " constructor\");" << endl << indent()
2522 << " }" << endl;
2523 } else {
2524 f_header_ << indent() << " piprot_(protocolFactory->getProtocol(itrans_))," << endl
2525 << indent() << " poprot_(protocolFactory->getProtocol(otrans_)) {" << endl;
2526 }
2527 f_header_ << indent() << " iprot_ = piprot_.get();" << endl << indent()
2528 << " oprot_ = poprot_.get();" << endl << indent() << "}" << endl;
2529 } else {
2530 f_header_ << indent() << " " << extends << style << client_suffix
2531 << "(channel, protocolFactory) {}" << endl;
2532 }
2533 }
2534
2535 if (style == "Cob") {
2536 generate_java_doc(f_header_, tservice);
2537
2538 f_header_ << indent()
2539 << "::std::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() {" << endl
2540 << indent() << " return " << _this << "channel_;" << endl << indent() << "}" << endl;
2541 if (!gen_no_client_completion_) {
2542 f_header_ << indent() << "virtual void completed__(bool /* success */) {}" << endl;
2543 }
2544 }
2545
2546 vector<t_function*> functions = tservice->get_functions();
2547 vector<t_function*>::const_iterator f_iter;
2548 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2549 generate_java_doc(f_header_, *f_iter);
2550 indent(f_header_) << function_signature(*f_iter, ifstyle) << ";" << endl;
2551 // TODO(dreiss): Use private inheritance to avoid generating thise in cob-style.
2552 if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
2553 // concurrent clients need to move the seqid from the send function to the
2554 // recv function. Oneway methods don't have a recv function, so we don't need to
2555 // move the seqid for them. Attempting to do so would result in a seqid leak.
2556 t_function send_function(g_type_i32, /*returning seqid*/
2557 string("send_") + (*f_iter)->get_name(),
2558 (*f_iter)->get_arglist());
2559 indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
2560 } else {
2561 t_function send_function(g_type_void,
2562 string("send_") + (*f_iter)->get_name(),
2563 (*f_iter)->get_arglist());
2564 indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
2565 }
2566 if (!(*f_iter)->is_oneway()) {
2567 if (style == "Concurrent") {
2568 t_field seqIdArg(g_type_i32, "seqid");
2569 t_struct seqIdArgStruct(program_);
2570 seqIdArgStruct.append(&seqIdArg);
2571 t_function recv_function((*f_iter)->get_returntype(),
2572 string("recv_") + (*f_iter)->get_name(),
2573 &seqIdArgStruct);
2574 indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
2575 } else {
2576 t_struct noargs(program_);
2577 t_function recv_function((*f_iter)->get_returntype(),
2578 string("recv_") + (*f_iter)->get_name(),
2579 &noargs);
2580 indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
2581 }
2582 }
2583 }
2584 indent_down();
2585
2586 if (extends.empty()) {
2587 f_header_ << " protected:" << endl;
2588 indent_up();
2589
2590 if (style == "Cob") {
2591 f_header_ << indent()
2592 << "::std::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_;" << endl
2593 << indent()
2594 << "::std::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_;" << endl
2595 << indent()
2596 << "::std::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_;"
2597 << endl;
2598 }
2599 f_header_ <<
2600 indent() << prot_ptr << " piprot_;" << endl <<
2601 indent() << prot_ptr << " poprot_;" << endl <<
2602 indent() << protocol_type << "* iprot_;" << endl <<
2603 indent() << protocol_type << "* oprot_;" << endl;
2604
2605 if (style == "Concurrent") {
2606 f_header_ <<
2607 indent() << "std::shared_ptr<::apache::thrift::async::TConcurrentClientSyncInfo> sync_;"<<endl;
2608 }
2609 indent_down();
2610 }
2611
2612 f_header_ << "};" << endl << endl;
2613
2614 if (gen_templates_) {
2615 // Output a backwards compatibility typedef using
2616 // TProtocol as the template parameter.
2617 f_header_ << "typedef " << service_name_ << style
2618 << "ClientT< ::apache::thrift::protocol::TProtocol> " << service_name_ << style
2619 << "Client;" << endl << endl;
2620 }
2621
2622 string scope = service_name_ + style + client_suffix + "::";
2623
2624 // Generate client method implementations
2625 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2626 string seqIdCapture;
2627 string seqIdUse;
2628 string seqIdCommaUse;
2629 if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
2630 seqIdCapture = "int32_t seqid = ";
2631 seqIdUse = "seqid";
2632 seqIdCommaUse = ", seqid";
2633 }
2634
2635 string funname = (*f_iter)->get_name();
2636
2637 // Open function
2638 if (gen_templates_) {
2639 indent(out) << template_header;
2640 }
2641 indent(out) << function_signature(*f_iter, ifstyle, scope) << endl;
2642 scope_up(out);
2643 indent(out) << seqIdCapture << "send_" << funname << "(";
2644
2645 // Get the struct of function call params
2646 t_struct* arg_struct = (*f_iter)->get_arglist();
2647
2648 // Declare the function arguments
2649 const vector<t_field*>& fields = arg_struct->get_members();
2650 vector<t_field*>::const_iterator fld_iter;
2651 bool first = true;
2652 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2653 if (first) {
2654 first = false;
2655 } else {
2656 out << ", ";
2657 }
2658 out << (*fld_iter)->get_name();
2659 }
2660 out << ");" << endl;
2661
2662 if (style != "Cob") {
2663 if (!(*f_iter)->is_oneway()) {
2664 out << indent();
2665 if (!(*f_iter)->get_returntype()->is_void()) {
2666 if (is_complex_type((*f_iter)->get_returntype())) {
2667 out << "recv_" << funname << "(_return" << seqIdCommaUse << ");" << endl;
2668 } else {
2669 out << "return recv_" << funname << "(" << seqIdUse << ");" << endl;
2670 }
2671 } else {
2672 out << "recv_" << funname << "(" << seqIdUse << ");" << endl;
2673 }
2674 }
2675 } else {
2676 if (!(*f_iter)->is_oneway()) {
2677 out << indent() << _this << "channel_->sendAndRecvMessage("
2678 << "::std::bind(cob, this), " << _this << "otrans_.get(), " << _this << "itrans_.get());"
2679 << endl;
2680 } else {
2681 out << indent() << _this << "channel_->sendMessage("
2682 << "::std::bind(cob, this), " << _this << "otrans_.get());" << endl;
2683 }
2684 }
2685 scope_down(out);
2686 out << endl;
2687
2688 // if (style != "Cob") // TODO(dreiss): Libify the client and don't generate this for cob-style
2689 if (true) {
2690 t_type* send_func_return_type = g_type_void;
2691 if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
2692 send_func_return_type = g_type_i32;
2693 }
2694 // Function for sending
2695 t_function send_function(send_func_return_type,
2696 string("send_") + (*f_iter)->get_name(),
2697 (*f_iter)->get_arglist());
2698
2699 // Open the send function
2700 if (gen_templates_) {
2701 indent(out) << template_header;
2702 }
2703 indent(out) << function_signature(&send_function, "", scope) << endl;
2704 scope_up(out);
2705
2706 // Function arguments and results
2707 string argsname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs";
2708 string resultname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_presult";
2709
2710 string cseqidVal = "0";
2711 if (style == "Concurrent") {
2712 if (!(*f_iter)->is_oneway()) {
2713 cseqidVal = "this->sync_->generateSeqId()";
2714 }
2715 }
2716 // Serialize the request
2717 out <<
2718 indent() << "int32_t cseqid = " << cseqidVal << ";" << endl;
2719 if(style == "Concurrent") {
2720 out <<
2721 indent() << "::apache::thrift::async::TConcurrentSendSentry sentry(this->sync_.get());" << endl;
2722 }
2723 if (style == "Cob") {
2724 out <<
2725 indent() << _this << "otrans_->resetBuffer();" << endl;
2726 }
2727 out <<
2728 indent() << _this << "oprot_->writeMessageBegin(\"" <<
2729 (*f_iter)->get_name() <<
2730 "\", ::apache::thrift::protocol::" << ((*f_iter)->is_oneway() ? "T_ONEWAY" : "T_CALL") <<
2731 ", cseqid);" << endl << endl <<
2732 indent() << argsname << " args;" << endl;
2733
2734 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2735 out << indent() << "args." << (*fld_iter)->get_name() << " = &" << (*fld_iter)->get_name()
2736 << ";" << endl;
2737 }
2738
2739 out << indent() << "args.write(" << _this << "oprot_);" << endl << endl << indent() << _this
2740 << "oprot_->writeMessageEnd();" << endl << indent() << _this
2741 << "oprot_->getTransport()->writeEnd();" << endl << indent() << _this
2742 << "oprot_->getTransport()->flush();" << endl;
2743
2744 if (style == "Concurrent") {
2745 out << endl << indent() << "sentry.commit();" << endl;
2746
2747 if (!(*f_iter)->is_oneway()) {
2748 out << indent() << "return cseqid;" << endl;
2749 }
2750 }
2751 scope_down(out);
2752 out << endl;
2753
2754 // Generate recv function only if not an oneway function
2755 if (!(*f_iter)->is_oneway()) {
2756 t_struct noargs(program_);
2757
2758 t_field seqIdArg(g_type_i32, "seqid");
2759 t_struct seqIdArgStruct(program_);
2760 seqIdArgStruct.append(&seqIdArg);
2761
2762 t_struct* recv_function_args = &noargs;
2763 if (style == "Concurrent") {
2764 recv_function_args = &seqIdArgStruct;
2765 }
2766
2767 t_function recv_function((*f_iter)->get_returntype(),
2768 string("recv_") + (*f_iter)->get_name(),
2769 recv_function_args);
2770 // Open the recv function
2771 if (gen_templates_) {
2772 indent(out) << template_header;
2773 }
2774 indent(out) << function_signature(&recv_function, "", scope) << endl;
2775 scope_up(out);
2776
2777 out << endl <<
2778 indent() << "int32_t rseqid = 0;" << endl <<
2779 indent() << "std::string fname;" << endl <<
2780 indent() << "::apache::thrift::protocol::TMessageType mtype;" << endl;
2781 if(style == "Concurrent") {
2782 out <<
2783 endl <<
2784 indent() << "// the read mutex gets dropped and reacquired as part of waitForWork()" << endl <<
2785 indent() << "// The destructor of this sentry wakes up other clients" << endl <<
2786 indent() << "::apache::thrift::async::TConcurrentRecvSentry sentry(this->sync_.get(), seqid);" << endl;
2787 }
2788 if (style == "Cob" && !gen_no_client_completion_) {
2789 out << indent() << "bool completed = false;" << endl << endl << indent() << "try {";
2790 indent_up();
2791 }
2792 out << endl;
2793 if (style == "Concurrent") {
2794 out <<
2795 indent() << "while(true) {" << endl <<
2796 indent() << " if(!this->sync_->getPending(fname, mtype, rseqid)) {" << endl;
2797 indent_up();
2798 indent_up();
2799 }
2800 out <<
2801 indent() << _this << "iprot_->readMessageBegin(fname, mtype, rseqid);" << endl;
2802 if (style == "Concurrent") {
2803 scope_down(out);
2804 out << indent() << "if(seqid == rseqid) {" << endl;
2805 indent_up();
2806 }
2807 out <<
2808 indent() << "if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {" << endl <<
2809 indent() << " ::apache::thrift::TApplicationException x;" << endl <<
2810 indent() << " x.read(" << _this << "iprot_);" << endl <<
2811 indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
2812 indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
2813 if (style == "Cob" && !gen_no_client_completion_) {
2814 out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
2815 << endl;
2816 }
2817 if (style == "Concurrent") {
2818 out << indent() << " sentry.commit();" << endl;
2819 }
2820 out <<
2821 indent() << " throw x;" << endl <<
2822 indent() << "}" << endl <<
2823 indent() << "if (mtype != ::apache::thrift::protocol::T_REPLY) {" << endl <<
2824 indent() << " " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
2825 indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
2826 indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
2827 if (style == "Cob" && !gen_no_client_completion_) {
2828 out << indent() << " completed = true;" << endl << indent() << " completed__(false);"
2829 << endl;
2830 }
2831 out <<
2832 indent() << "}" << endl <<
2833 indent() << "if (fname.compare(\"" << (*f_iter)->get_name() << "\") != 0) {" << endl <<
2834 indent() << " " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
2835 indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
2836 indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
2837 if (style == "Cob" && !gen_no_client_completion_) {
2838 out << indent() << " completed = true;" << endl << indent() << " completed__(false);"
2839 << endl;
2840 }
2841 if (style == "Concurrent") {
2842 out << endl <<
2843 indent() << " // in a bad state, don't commit" << endl <<
2844 indent() << " using ::apache::thrift::protocol::TProtocolException;" << endl <<
2845 indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
2846 }
2847 out << indent() << "}" << endl;
2848
2849 if (!(*f_iter)->get_returntype()->is_void()
2850 && !is_complex_type((*f_iter)->get_returntype())) {
2851 t_field returnfield((*f_iter)->get_returntype(), "_return");
2852 out << indent() << declare_field(&returnfield) << endl;
2853 }
2854
2855 out << indent() << resultname << " result;" << endl;
2856
2857 if (!(*f_iter)->get_returntype()->is_void()) {
2858 out << indent() << "result.success = &_return;" << endl;
2859 }
2860
2861 out << indent() << "result.read(" << _this << "iprot_);" << endl << indent() << _this
2862 << "iprot_->readMessageEnd();" << endl << indent() << _this
2863 << "iprot_->getTransport()->readEnd();" << endl << endl;
2864
2865 // Careful, only look for _result if not a void function
2866 if (!(*f_iter)->get_returntype()->is_void()) {
2867 if (is_complex_type((*f_iter)->get_returntype())) {
2868 out <<
2869 indent() << "if (result.__isset.success) {" << endl;
2870 out <<
2871 indent() << " // _return pointer has now been filled" << endl;
2872 if (style == "Cob" && !gen_no_client_completion_) {
2873 out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
2874 << endl;
2875 }
2876 if (style == "Concurrent") {
2877 out << indent() << " sentry.commit();" << endl;
2878 }
2879 out <<
2880 indent() << " return;" << endl <<
2881 indent() << "}" << endl;
2882 } else {
2883 out << indent() << "if (result.__isset.success) {" << endl;
2884 if (style == "Cob" && !gen_no_client_completion_) {
2885 out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
2886 << endl;
2887 }
2888 if (style == "Concurrent") {
2889 out << indent() << " sentry.commit();" << endl;
2890 }
2891 out << indent() << " return _return;" << endl << indent() << "}" << endl;
2892 }
2893 }
2894
2895 t_struct* xs = (*f_iter)->get_xceptions();
2896 const std::vector<t_field*>& xceptions = xs->get_members();
2897 vector<t_field*>::const_iterator x_iter;
2898 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
2899 out << indent() << "if (result.__isset." << (*x_iter)->get_name() << ") {" << endl;
2900 if (style == "Cob" && !gen_no_client_completion_) {
2901 out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
2902 << endl;
2903 }
2904 if (style == "Concurrent") {
2905 out << indent() << " sentry.commit();" << endl;
2906 }
2907 out << indent() << " throw result." << (*x_iter)->get_name() << ";" << endl << indent()
2908 << "}" << endl;
2909 }
2910
2911 // We only get here if we are a void function
2912 if ((*f_iter)->get_returntype()->is_void()) {
2913 if (style == "Cob" && !gen_no_client_completion_) {
2914 out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
2915 << endl;
2916 }
2917 if (style == "Concurrent") {
2918 out << indent() << "sentry.commit();" << endl;
2919 }
2920 indent(out) << "return;" << endl;
2921 } else {
2922 if (style == "Cob" && !gen_no_client_completion_) {
2923 out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
2924 << endl;
2925 }
2926 if (style == "Concurrent") {
2927 out << indent() << "// in a bad state, don't commit" << endl;
2928 }
2929 out << indent() << "throw "
2930 "::apache::thrift::TApplicationException(::apache::thrift::"
2931 "TApplicationException::MISSING_RESULT, \"" << (*f_iter)->get_name()
2932 << " failed: unknown result\");" << endl;
2933 }
2934 if (style == "Concurrent") {
2935 indent_down();
2936 indent_down();
2937 out <<
2938 indent() << " }" << endl <<
2939 indent() << " // seqid != rseqid" << endl <<
2940 indent() << " this->sync_->updatePending(fname, mtype, rseqid);" << endl <<
2941 endl <<
2942 indent() << " // this will temporarily unlock the readMutex, and let other clients get work done" << endl <<
2943 indent() << " this->sync_->waitForWork(seqid);" << endl <<
2944 indent() << "} // end while(true)" << endl;
2945 }
2946 if (style == "Cob" && !gen_no_client_completion_) {
2947 indent_down();
2948 out << indent() << "} catch (...) {" << endl << indent() << " if (!completed) {" << endl
2949 << indent() << " completed__(false);" << endl << indent() << " }" << endl
2950 << indent() << " throw;" << endl << indent() << "}" << endl;
2951 }
2952 // Close function
2953 scope_down(out);
2954 out << endl;
2955 }
2956 }
2957 }
2958 }
2959
2960 class ProcessorGenerator {
2961 public:
2962 ProcessorGenerator(t_cpp_generator* generator, t_service* service, const string& style);
2963
run()2964 void run() {
2965 generate_class_definition();
2966
2967 // Generate the dispatchCall() function
2968 generate_dispatch_call(false);
2969 if (generator_->gen_templates_) {
2970 generate_dispatch_call(true);
2971 }
2972
2973 // Generate all of the process subfunctions
2974 generate_process_functions();
2975
2976 generate_factory();
2977 }
2978
2979 void generate_class_definition();
2980 void generate_dispatch_call(bool template_protocol);
2981 void generate_process_functions();
2982 void generate_factory();
2983
2984 protected:
type_name(t_type * ttype,bool in_typedef=false,bool arg=false)2985 std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false) {
2986 return generator_->type_name(ttype, in_typedef, arg);
2987 }
2988
indent()2989 std::string indent() { return generator_->indent(); }
indent(std::ostream & os)2990 std::ostream& indent(std::ostream& os) { return generator_->indent(os); }
2991
indent_up()2992 void indent_up() { generator_->indent_up(); }
indent_down()2993 void indent_down() { generator_->indent_down(); }
2994
2995 t_cpp_generator* generator_;
2996 t_service* service_;
2997 std::ostream& f_header_;
2998 std::ostream& f_out_;
2999 string service_name_;
3000 string style_;
3001 string pstyle_;
3002 string class_name_;
3003 string if_name_;
3004 string factory_class_name_;
3005 string finish_cob_;
3006 string finish_cob_decl_;
3007 string ret_type_;
3008 string call_context_;
3009 string cob_arg_;
3010 string call_context_arg_;
3011 string call_context_decl_;
3012 string template_header_;
3013 string template_suffix_;
3014 string typename_str_;
3015 string class_suffix_;
3016 string extends_;
3017 };
3018
ProcessorGenerator(t_cpp_generator * generator,t_service * service,const string & style)3019 ProcessorGenerator::ProcessorGenerator(t_cpp_generator* generator,
3020 t_service* service,
3021 const string& style)
3022 : generator_(generator),
3023 service_(service),
3024 f_header_(generator->f_header_),
3025 f_out_(generator->gen_templates_ ? generator->f_service_tcc_ : generator->f_service_),
3026 service_name_(generator->service_name_),
3027 style_(style) {
3028 if (style_ == "Cob") {
3029 pstyle_ = "Async";
3030 class_name_ = service_name_ + pstyle_ + "Processor";
3031 if_name_ = service_name_ + "CobSvIf";
3032
3033 finish_cob_ = "::std::function<void(bool ok)> cob, ";
3034 finish_cob_decl_ = "::std::function<void(bool ok)>, ";
3035 cob_arg_ = "cob, ";
3036 ret_type_ = "void ";
3037 } else {
3038 class_name_ = service_name_ + "Processor";
3039 if_name_ = service_name_ + "If";
3040
3041 ret_type_ = "bool ";
3042 // TODO(edhall) callContext should eventually be added to TAsyncProcessor
3043 call_context_ = ", void* callContext";
3044 call_context_arg_ = ", callContext";
3045 call_context_decl_ = ", void*";
3046 }
3047
3048 factory_class_name_ = class_name_ + "Factory";
3049
3050 if (generator->gen_templates_) {
3051 template_header_ = "template <class Protocol_>\n";
3052 template_suffix_ = "<Protocol_>";
3053 typename_str_ = "typename ";
3054 class_name_ += "T";
3055 factory_class_name_ += "T";
3056 }
3057
3058 if (service_->get_extends() != nullptr) {
3059 extends_ = type_name(service_->get_extends()) + pstyle_ + "Processor";
3060 if (generator_->gen_templates_) {
3061 // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
3062 // parent services were also generated with templates enabled.
3063 extends_ += "T<Protocol_>";
3064 }
3065 }
3066 }
3067
generate_class_definition()3068 void ProcessorGenerator::generate_class_definition() {
3069 // Generate the dispatch methods
3070 vector<t_function*> functions = service_->get_functions();
3071 vector<t_function*>::iterator f_iter;
3072
3073 string parent_class;
3074 if (service_->get_extends() != nullptr) {
3075 parent_class = extends_;
3076 } else {
3077 if (style_ == "Cob") {
3078 parent_class = "::apache::thrift::async::TAsyncDispatchProcessor";
3079 } else {
3080 parent_class = "::apache::thrift::TDispatchProcessor";
3081 }
3082
3083 if (generator_->gen_templates_) {
3084 parent_class += "T<Protocol_>";
3085 }
3086 }
3087
3088 // Generate the header portion
3089 f_header_ << template_header_ << "class " << class_name_ << " : public " << parent_class << " {"
3090 << endl;
3091
3092 // Protected data members
3093 f_header_ << " protected:" << endl;
3094 indent_up();
3095 f_header_ << indent() << "::std::shared_ptr<" << if_name_ << "> iface_;" << endl;
3096 f_header_ << indent() << "virtual " << ret_type_ << "dispatchCall(" << finish_cob_
3097 << "::apache::thrift::protocol::TProtocol* iprot, "
3098 << "::apache::thrift::protocol::TProtocol* oprot, "
3099 << "const std::string& fname, int32_t seqid" << call_context_ << ");" << endl;
3100 if (generator_->gen_templates_) {
3101 f_header_ << indent() << "virtual " << ret_type_ << "dispatchCallTemplated(" << finish_cob_
3102 << "Protocol_* iprot, Protocol_* oprot, "
3103 << "const std::string& fname, int32_t seqid" << call_context_ << ");" << endl;
3104 }
3105 indent_down();
3106
3107 // Process function declarations
3108 f_header_ << " private:" << endl;
3109 indent_up();
3110
3111 // Declare processMap_
3112 f_header_ << indent() << "typedef void (" << class_name_ << "::*"
3113 << "ProcessFunction)(" << finish_cob_decl_ << "int32_t, "
3114 << "::apache::thrift::protocol::TProtocol*, "
3115 << "::apache::thrift::protocol::TProtocol*" << call_context_decl_ << ");" << endl;
3116 if (generator_->gen_templates_) {
3117 f_header_ << indent() << "typedef void (" << class_name_ << "::*"
3118 << "SpecializedProcessFunction)(" << finish_cob_decl_ << "int32_t, "
3119 << "Protocol_*, Protocol_*" << call_context_decl_ << ");" << endl << indent()
3120 << "struct ProcessFunctions {" << endl << indent() << " ProcessFunction generic;"
3121 << endl << indent() << " SpecializedProcessFunction specialized;" << endl << indent()
3122 << " ProcessFunctions(ProcessFunction g, "
3123 << "SpecializedProcessFunction s) :" << endl << indent() << " generic(g)," << endl
3124 << indent() << " specialized(s) {}" << endl << indent()
3125 << " ProcessFunctions() : generic(nullptr), specialized(nullptr) "
3126 << "{}" << endl << indent() << "};" << endl << indent()
3127 << "typedef std::map<std::string, ProcessFunctions> "
3128 << "ProcessMap;" << endl;
3129 } else {
3130 f_header_ << indent() << "typedef std::map<std::string, ProcessFunction> "
3131 << "ProcessMap;" << endl;
3132 }
3133 f_header_ << indent() << "ProcessMap processMap_;" << endl;
3134
3135 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3136 indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
3137 << "int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, "
3138 "::apache::thrift::protocol::TProtocol* oprot" << call_context_ << ");"
3139 << endl;
3140 if (generator_->gen_templates_) {
3141 indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
3142 << "int32_t seqid, Protocol_* iprot, Protocol_* oprot" << call_context_
3143 << ");" << endl;
3144 }
3145 if (style_ == "Cob") {
3146 // XXX Factor this out, even if it is a pain.
3147 string ret_arg = ((*f_iter)->get_returntype()->is_void()
3148 ? ""
3149 : ", const " + type_name((*f_iter)->get_returntype()) + "& _return");
3150 f_header_ << indent() << "void return_" << (*f_iter)->get_name()
3151 << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3152 << "::apache::thrift::protocol::TProtocol* oprot, "
3153 << "void* ctx" << ret_arg << ");" << endl;
3154 if (generator_->gen_templates_) {
3155 f_header_ << indent() << "void return_" << (*f_iter)->get_name()
3156 << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3157 << "Protocol_* oprot, void* ctx" << ret_arg << ");" << endl;
3158 }
3159 // XXX Don't declare throw if it doesn't exist
3160 f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
3161 << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3162 << "::apache::thrift::protocol::TProtocol* oprot, void* ctx, "
3163 << "::apache::thrift::TDelayedException* _throw);" << endl;
3164 if (generator_->gen_templates_) {
3165 f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
3166 << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3167 << "Protocol_* oprot, void* ctx, "
3168 << "::apache::thrift::TDelayedException* _throw);" << endl;
3169 }
3170 }
3171 }
3172
3173 f_header_ << " public:" << endl << indent() << class_name_ << "(::std::shared_ptr<" << if_name_
3174 << "> iface) :" << endl;
3175 if (!extends_.empty()) {
3176 f_header_ << indent() << " " << extends_ << "(iface)," << endl;
3177 }
3178 f_header_ << indent() << " iface_(iface) {" << endl;
3179 indent_up();
3180
3181 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3182 f_header_ << indent() << "processMap_[\"" << (*f_iter)->get_name() << "\"] = ";
3183 if (generator_->gen_templates_) {
3184 f_header_ << "ProcessFunctions(" << endl;
3185 if (generator_->gen_templates_only_) {
3186 indent(f_header_) << " nullptr," << endl;
3187 } else {
3188 indent(f_header_) << " &" << class_name_ << "::process_" << (*f_iter)->get_name() << ","
3189 << endl;
3190 }
3191 indent(f_header_) << " &" << class_name_ << "::process_" << (*f_iter)->get_name() << ")";
3192 } else {
3193 f_header_ << "&" << class_name_ << "::process_" << (*f_iter)->get_name();
3194 }
3195 f_header_ << ";" << endl;
3196 }
3197
3198 indent_down();
3199 f_header_ << indent() << "}" << endl << endl << indent() << "virtual ~" << class_name_ << "() {}"
3200 << endl;
3201 indent_down();
3202 f_header_ << "};" << endl << endl;
3203
3204 if (generator_->gen_templates_) {
3205 // Generate a backwards compatible typedef, for callers who don't know
3206 // about the new template-style code.
3207 //
3208 // We can't use TProtocol as the template parameter, since ProcessorT
3209 // provides overloaded versions of most methods, one of which accepts
3210 // TProtocol pointers, and one which accepts Protocol_ pointers. This
3211 // results in a compile error if instantiated with Protocol_ == TProtocol.
3212 // Therefore, we define TDummyProtocol solely so we can use it as the
3213 // template parameter here.
3214 f_header_ << "typedef " << class_name_ << "< ::apache::thrift::protocol::TDummyProtocol > "
3215 << service_name_ << pstyle_ << "Processor;" << endl << endl;
3216 }
3217 }
3218
generate_dispatch_call(bool template_protocol)3219 void ProcessorGenerator::generate_dispatch_call(bool template_protocol) {
3220 string protocol = "::apache::thrift::protocol::TProtocol";
3221 string function_suffix;
3222 if (template_protocol) {
3223 protocol = "Protocol_";
3224 // We call the generic version dispatchCall(), and the specialized
3225 // version dispatchCallTemplated(). We can't call them both
3226 // dispatchCall(), since this will cause the compiler to issue a warning if
3227 // a service that doesn't use templates inherits from a service that does
3228 // use templates: the compiler complains that the subclass only implements
3229 // the generic version of dispatchCall(), and hides the templated version.
3230 // Using different names for the two functions prevents this.
3231 function_suffix = "Templated";
3232 }
3233
3234 f_out_ << template_header_ << ret_type_ << class_name_ << template_suffix_ << "::dispatchCall"
3235 << function_suffix << "(" << finish_cob_ << protocol << "* iprot, " << protocol
3236 << "* oprot, "
3237 << "const std::string& fname, int32_t seqid" << call_context_ << ") {" << endl;
3238 indent_up();
3239
3240 // HOT: member function pointer map
3241 f_out_ << indent() << typename_str_ << "ProcessMap::iterator pfn;" << endl << indent()
3242 << "pfn = processMap_.find(fname);" << endl << indent()
3243 << "if (pfn == processMap_.end()) {" << endl;
3244 if (extends_.empty()) {
3245 f_out_ << indent() << " iprot->skip(::apache::thrift::protocol::T_STRUCT);" << endl << indent()
3246 << " iprot->readMessageEnd();" << endl << indent()
3247 << " iprot->getTransport()->readEnd();" << endl << indent()
3248 << " ::apache::thrift::TApplicationException "
3249 "x(::apache::thrift::TApplicationException::UNKNOWN_METHOD, \"Invalid method name: "
3250 "'\"+fname+\"'\");" << endl << indent()
3251 << " oprot->writeMessageBegin(fname, ::apache::thrift::protocol::T_EXCEPTION, seqid);"
3252 << endl << indent() << " x.write(oprot);" << endl << indent()
3253 << " oprot->writeMessageEnd();" << endl << indent()
3254 << " oprot->getTransport()->writeEnd();" << endl << indent()
3255 << " oprot->getTransport()->flush();" << endl << indent()
3256 << (style_ == "Cob" ? " return cob(true);" : " return true;") << endl;
3257 } else {
3258 f_out_ << indent() << " return " << extends_ << "::dispatchCall("
3259 << (style_ == "Cob" ? "cob, " : "") << "iprot, oprot, fname, seqid" << call_context_arg_
3260 << ");" << endl;
3261 }
3262 f_out_ << indent() << "}" << endl;
3263 if (template_protocol) {
3264 f_out_ << indent() << "(this->*(pfn->second.specialized))";
3265 } else {
3266 if (generator_->gen_templates_only_) {
3267 // TODO: This is a null pointer, so nothing good will come from calling
3268 // it. Throw an exception instead.
3269 f_out_ << indent() << "(this->*(pfn->second.generic))";
3270 } else if (generator_->gen_templates_) {
3271 f_out_ << indent() << "(this->*(pfn->second.generic))";
3272 } else {
3273 f_out_ << indent() << "(this->*(pfn->second))";
3274 }
3275 }
3276 f_out_ << "(" << cob_arg_ << "seqid, iprot, oprot" << call_context_arg_ << ");" << endl;
3277
3278 // TODO(dreiss): return pfn ret?
3279 if (style_ == "Cob") {
3280 f_out_ << indent() << "return;" << endl;
3281 } else {
3282 f_out_ << indent() << "return true;" << endl;
3283 }
3284
3285 indent_down();
3286 f_out_ << "}" << endl << endl;
3287 }
3288
generate_process_functions()3289 void ProcessorGenerator::generate_process_functions() {
3290 vector<t_function*> functions = service_->get_functions();
3291 vector<t_function*>::iterator f_iter;
3292 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3293 if (generator_->gen_templates_) {
3294 generator_->generate_process_function(service_, *f_iter, style_, false);
3295 generator_->generate_process_function(service_, *f_iter, style_, true);
3296 } else {
3297 generator_->generate_process_function(service_, *f_iter, style_, false);
3298 }
3299 }
3300 }
3301
generate_factory()3302 void ProcessorGenerator::generate_factory() {
3303 string if_factory_name = if_name_ + "Factory";
3304
3305 // Generate the factory class definition
3306 f_header_ << template_header_ << "class " << factory_class_name_ << " : public ::apache::thrift::"
3307 << (style_ == "Cob" ? "async::TAsyncProcessorFactory" : "TProcessorFactory") << " {"
3308 << endl << " public:" << endl;
3309 indent_up();
3310
3311 f_header_ << indent() << factory_class_name_ << "(const ::std::shared_ptr< " << if_factory_name
3312 << " >& handlerFactory) :" << endl << indent()
3313 << " handlerFactory_(handlerFactory) {}" << endl << endl << indent()
3314 << "::std::shared_ptr< ::apache::thrift::"
3315 << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
3316 << "getProcessor(const ::apache::thrift::TConnectionInfo& connInfo);" << endl;
3317
3318 f_header_ << endl << " protected:" << endl << indent() << "::std::shared_ptr< "
3319 << if_factory_name << " > handlerFactory_;" << endl;
3320
3321 indent_down();
3322 f_header_ << "};" << endl << endl;
3323
3324 // If we are generating templates, output a typedef for the plain
3325 // factory name.
3326 if (generator_->gen_templates_) {
3327 f_header_ << "typedef " << factory_class_name_
3328 << "< ::apache::thrift::protocol::TDummyProtocol > " << service_name_ << pstyle_
3329 << "ProcessorFactory;" << endl << endl;
3330 }
3331
3332 // Generate the getProcessor() method
3333 f_out_ << template_header_ << indent() << "::std::shared_ptr< ::apache::thrift::"
3334 << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
3335 << factory_class_name_ << template_suffix_ << "::getProcessor("
3336 << "const ::apache::thrift::TConnectionInfo& connInfo) {" << endl;
3337 indent_up();
3338
3339 f_out_ << indent() << "::apache::thrift::ReleaseHandler< " << if_factory_name
3340 << " > cleanup(handlerFactory_);" << endl << indent() << "::std::shared_ptr< "
3341 << if_name_ << " > handler("
3342 << "handlerFactory_->getHandler(connInfo), cleanup);" << endl << indent()
3343 << "::std::shared_ptr< ::apache::thrift::"
3344 << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
3345 << "processor(new " << class_name_ << template_suffix_ << "(handler));" << endl << indent()
3346 << "return processor;" << endl;
3347
3348 indent_down();
3349 f_out_ << indent() << "}" << endl << endl;
3350 }
3351
3352 /**
3353 * Generates a service processor definition.
3354 *
3355 * @param tservice The service to generate a processor for.
3356 */
generate_service_processor(t_service * tservice,string style)3357 void t_cpp_generator::generate_service_processor(t_service* tservice, string style) {
3358 ProcessorGenerator generator(this, tservice, style);
3359 generator.run();
3360 }
3361
3362 /**
3363 * Generates a struct and helpers for a function.
3364 *
3365 * @param tfunction The function
3366 */
generate_function_helpers(t_service * tservice,t_function * tfunction)3367 void t_cpp_generator::generate_function_helpers(t_service* tservice, t_function* tfunction) {
3368 if (tfunction->is_oneway()) {
3369 return;
3370 }
3371
3372 std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
3373
3374 t_struct result(program_, tservice->get_name() + "_" + tfunction->get_name() + "_result");
3375 t_field success(tfunction->get_returntype(), "success", 0);
3376 if (!tfunction->get_returntype()->is_void()) {
3377 result.append(&success);
3378 }
3379
3380 t_struct* xs = tfunction->get_xceptions();
3381 const vector<t_field*>& fields = xs->get_members();
3382 vector<t_field*>::const_iterator f_iter;
3383 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3384 result.append(*f_iter);
3385 }
3386
3387 generate_struct_declaration(f_header_, &result, false);
3388 generate_struct_definition(out, f_service_, &result, false);
3389 generate_struct_reader(out, &result);
3390 generate_struct_result_writer(out, &result);
3391
3392 result.set_name(tservice->get_name() + "_" + tfunction->get_name() + "_presult");
3393 generate_struct_declaration(f_header_, &result, false, true, true, gen_cob_style_);
3394 generate_struct_definition(out, f_service_, &result, false);
3395 generate_struct_reader(out, &result, true);
3396 if (gen_cob_style_) {
3397 generate_struct_writer(out, &result, true);
3398 }
3399 }
3400
3401 /**
3402 * Generates a process function definition.
3403 *
3404 * @param tfunction The function to write a dispatcher for
3405 */
generate_process_function(t_service * tservice,t_function * tfunction,string style,bool specialized)3406 void t_cpp_generator::generate_process_function(t_service* tservice,
3407 t_function* tfunction,
3408 string style,
3409 bool specialized) {
3410 t_struct* arg_struct = tfunction->get_arglist();
3411 const std::vector<t_field*>& fields = arg_struct->get_members();
3412 vector<t_field*>::const_iterator f_iter;
3413
3414 t_struct* xs = tfunction->get_xceptions();
3415 const std::vector<t_field*>& xceptions = xs->get_members();
3416 vector<t_field*>::const_iterator x_iter;
3417 string service_func_name = "\"" + tservice->get_name() + "." + tfunction->get_name() + "\"";
3418
3419 std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
3420
3421 string prot_type = (specialized ? "Protocol_" : "::apache::thrift::protocol::TProtocol");
3422 string class_suffix;
3423 if (gen_templates_) {
3424 class_suffix = "T<Protocol_>";
3425 }
3426
3427 // I tried to do this as one function. I really did. But it was too hard.
3428 if (style != "Cob") {
3429 // Open function
3430 if (gen_templates_) {
3431 out << indent() << "template <class Protocol_>" << endl;
3432 }
3433 const bool unnamed_oprot_seqid = tfunction->is_oneway() && !(gen_templates_ && !specialized);
3434 out << "void " << tservice->get_name() << "Processor" << class_suffix << "::"
3435 << "process_" << tfunction->get_name() << "("
3436 << "int32_t" << (unnamed_oprot_seqid ? ", " : " seqid, ") << prot_type << "* iprot, "
3437 << prot_type << "*" << (unnamed_oprot_seqid ? ", " : " oprot, ") << "void* callContext)"
3438 << endl;
3439 scope_up(out);
3440
3441 string argsname = tservice->get_name() + "_" + tfunction->get_name() + "_args";
3442 string resultname = tservice->get_name() + "_" + tfunction->get_name() + "_result";
3443
3444 if (tfunction->is_oneway() && !unnamed_oprot_seqid) {
3445 out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
3446 }
3447
3448 out << indent() << "void* ctx = nullptr;" << endl << indent()
3449 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3450 << " ctx = this->eventHandler_->getContext(" << service_func_name << ", callContext);"
3451 << endl << indent() << "}" << endl << indent()
3452 << "::apache::thrift::TProcessorContextFreer freer("
3453 << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
3454 << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3455 << " this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
3456 << "}" << endl << endl << indent() << argsname << " args;" << endl << indent()
3457 << "args.read(iprot);" << endl << indent() << "iprot->readMessageEnd();" << endl << indent()
3458 << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << endl << indent()
3459 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3460 << " this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
3461 << indent() << "}" << endl << endl;
3462
3463 // Declare result
3464 if (!tfunction->is_oneway()) {
3465 out << indent() << resultname << " result;" << endl;
3466 }
3467
3468 // Try block for functions with exceptions
3469 out << indent() << "try {" << endl;
3470 indent_up();
3471
3472 // Generate the function call
3473 bool first = true;
3474 out << indent();
3475 if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
3476 if (is_complex_type(tfunction->get_returntype())) {
3477 first = false;
3478 out << "iface_->" << tfunction->get_name() << "(result.success";
3479 } else {
3480 out << "result.success = iface_->" << tfunction->get_name() << "(";
3481 }
3482 } else {
3483 out << "iface_->" << tfunction->get_name() << "(";
3484 }
3485 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3486 if (first) {
3487 first = false;
3488 } else {
3489 out << ", ";
3490 }
3491 out << "args." << (*f_iter)->get_name();
3492 }
3493 out << ");" << endl;
3494
3495 // Set isset on success field
3496 if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
3497 out << indent() << "result.__isset.success = true;" << endl;
3498 }
3499
3500 indent_down();
3501 out << indent() << "}";
3502
3503 if (!tfunction->is_oneway()) {
3504 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3505 out << " catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
3506 << ") {" << endl;
3507 if (!tfunction->is_oneway()) {
3508 indent_up();
3509 out << indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name()
3510 << ";" << endl << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;"
3511 << endl;
3512 indent_down();
3513 out << indent() << "}";
3514 } else {
3515 out << "}";
3516 }
3517 }
3518 }
3519
3520 if (!tfunction->is_oneway()) {
3521 out << " catch (const std::exception& e) {" << endl;
3522 } else {
3523 out << " catch (const std::exception&) {" << endl;
3524 }
3525
3526 indent_up();
3527 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3528 << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
3529 << indent() << "}" << endl;
3530
3531 if (!tfunction->is_oneway()) {
3532 out << endl << indent() << "::apache::thrift::TApplicationException x(e.what());" << endl
3533 << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
3534 << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
3535 << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
3536 << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
3537 << "oprot->getTransport()->flush();" << endl;
3538 }
3539 out << indent() << "return;" << endl;
3540 indent_down();
3541 out << indent() << "}" << endl << endl;
3542
3543 // Shortcut out here for oneway functions
3544 if (tfunction->is_oneway()) {
3545 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3546 << " this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
3547 << indent() << "}" << endl << endl << indent() << "return;" << endl;
3548 indent_down();
3549 out << "}" << endl << endl;
3550 return;
3551 }
3552
3553 // Serialize the result into a struct
3554 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3555 << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl << indent()
3556 << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
3557 << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl << indent()
3558 << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
3559 << indent() << "bytes = oprot->getTransport()->writeEnd();" << endl << indent()
3560 << "oprot->getTransport()->flush();" << endl << endl << indent()
3561 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3562 << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
3563 << indent() << "}" << endl;
3564
3565 // Close function
3566 scope_down(out);
3567 out << endl;
3568 }
3569
3570 // Cob style.
3571 else {
3572 // Processor entry point.
3573 // TODO(edhall) update for callContext when TEventServer is ready
3574 if (gen_templates_) {
3575 out << indent() << "template <class Protocol_>" << endl;
3576 }
3577 out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::process_"
3578 << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3579 << prot_type << "* iprot, " << prot_type << "* oprot)" << endl;
3580 scope_up(out);
3581
3582 // TODO(simpkins): we could try to consoldate this
3583 // with the non-cob code above
3584 if (gen_templates_ && !specialized) {
3585 // If these are instances of Protocol_, instead of any old TProtocol,
3586 // use the specialized process function instead.
3587 out << indent() << "Protocol_* _iprot = dynamic_cast<Protocol_*>(iprot);" << endl << indent()
3588 << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl << indent()
3589 << "if (_iprot && _oprot) {" << endl << indent() << " return process_"
3590 << tfunction->get_name() << "(cob, seqid, _iprot, _oprot);" << endl << indent() << "}"
3591 << endl << indent() << "T_GENERIC_PROTOCOL(this, iprot, _iprot);" << endl << indent()
3592 << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl << endl;
3593 }
3594
3595 if (tfunction->is_oneway()) {
3596 out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
3597 }
3598
3599 out << indent() << tservice->get_name() + "_" + tfunction->get_name() << "_args args;" << endl
3600 << indent() << "void* ctx = nullptr;" << endl << indent()
3601 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3602 << " ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
3603 << indent() << "}" << endl << indent() << "::apache::thrift::TProcessorContextFreer freer("
3604 << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
3605 << indent() << "try {" << endl;
3606 indent_up();
3607 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3608 << " this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
3609 << "}" << endl << indent() << "args.read(iprot);" << endl << indent()
3610 << "iprot->readMessageEnd();" << endl << indent()
3611 << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << indent()
3612 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3613 << " this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
3614 << indent() << "}" << endl;
3615 scope_down(out);
3616
3617 // TODO(dreiss): Handle TExceptions? Expose to server?
3618 out << indent() << "catch (const std::exception&) {" << endl << indent()
3619 << " if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3620 << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
3621 << indent() << " }" << endl << indent() << " return cob(false);" << endl << indent()
3622 << "}" << endl;
3623
3624 if (tfunction->is_oneway()) {
3625 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3626 << " this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
3627 << indent() << "}" << endl;
3628 }
3629 // TODO(dreiss): Figure out a strategy for exceptions in async handlers.
3630 out << indent() << "freer.unregister();" << endl;
3631 if (tfunction->is_oneway()) {
3632 // No return. Just hand off our cob.
3633 // TODO(dreiss): Call the cob immediately?
3634 out << indent() << "iface_->" << tfunction->get_name() << "("
3635 << "::std::bind(cob, true)" << endl;
3636 indent_up();
3637 indent_up();
3638 } else {
3639 string ret_arg, ret_placeholder;
3640 if (!tfunction->get_returntype()->is_void()) {
3641 ret_arg = ", const " + type_name(tfunction->get_returntype()) + "& _return";
3642 ret_placeholder = ", ::std::placeholders::_1";
3643 }
3644
3645 // When gen_templates_ is true, the return_ and throw_ functions are
3646 // overloaded. We have to declare pointers to them so that the compiler
3647 // can resolve the correct overloaded version.
3648 out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
3649 << "::*return_fn)(::std::function<void(bool ok)> "
3650 << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx" << ret_arg
3651 << ") =" << endl;
3652 out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix
3653 << "::return_" << tfunction->get_name() << ";" << endl;
3654 if (!xceptions.empty()) {
3655 out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
3656 << "::*throw_fn)(::std::function<void(bool ok)> "
3657 << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx, "
3658 << "::apache::thrift::TDelayedException* _throw) =" << endl;
3659 out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix
3660 << "::throw_" << tfunction->get_name() << ";" << endl;
3661 }
3662
3663 out << indent() << "iface_->" << tfunction->get_name() << "(" << endl;
3664 indent_up();
3665 indent_up();
3666 out << indent() << "::std::bind(return_fn, this, cob, seqid, oprot, ctx" << ret_placeholder
3667 << ")";
3668 if (!xceptions.empty()) {
3669 out << ',' << endl << indent() << "::std::bind(throw_fn, this, cob, seqid, oprot, "
3670 << "ctx, ::std::placeholders::_1)";
3671 }
3672 }
3673
3674 // XXX Whitespace cleanup.
3675 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3676 out << ',' << endl << indent() << "args." << (*f_iter)->get_name();
3677 }
3678 out << ");" << endl;
3679 indent_down();
3680 indent_down();
3681 scope_down(out);
3682 out << endl;
3683
3684 // Normal return.
3685 if (!tfunction->is_oneway()) {
3686 string ret_arg_decl, ret_arg_name;
3687 if (!tfunction->get_returntype()->is_void()) {
3688 ret_arg_decl = ", const " + type_name(tfunction->get_returntype()) + "& _return";
3689 ret_arg_name = ", _return";
3690 }
3691 if (gen_templates_) {
3692 out << indent() << "template <class Protocol_>" << endl;
3693 }
3694 out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::return_"
3695 << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3696 << prot_type << "* oprot, void* ctx" << ret_arg_decl << ')' << endl;
3697 scope_up(out);
3698
3699 if (gen_templates_ && !specialized) {
3700 // If oprot is a Protocol_ instance,
3701 // use the specialized return function instead.
3702 out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
3703 << indent() << "if (_oprot) {" << endl << indent() << " return return_"
3704 << tfunction->get_name() << "(cob, seqid, _oprot, ctx" << ret_arg_name << ");" << endl
3705 << indent() << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);"
3706 << endl << endl;
3707 }
3708
3709 out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_presult result;"
3710 << endl;
3711 if (!tfunction->get_returntype()->is_void()) {
3712 // The const_cast here is unfortunate, but it would be a pain to avoid,
3713 // and we only do a write with this struct, which is const-safe.
3714 out << indent() << "result.success = const_cast<" << type_name(tfunction->get_returntype())
3715 << "*>(&_return);" << endl << indent() << "result.__isset.success = true;" << endl;
3716 }
3717 // Serialize the result into a struct
3718 out << endl << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3719 << " ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
3720 << indent() << "}" << endl << indent()
3721 << "::apache::thrift::TProcessorContextFreer freer("
3722 << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
3723 << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3724 << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
3725 << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
3726 << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
3727 << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
3728 << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
3729 << indent() << "oprot->getTransport()->flush();" << endl << indent()
3730 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3731 << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
3732 << indent() << "}" << endl << indent() << "return cob(true);" << endl;
3733 scope_down(out);
3734 out << endl;
3735 }
3736
3737 // Exception return.
3738 if (!tfunction->is_oneway() && !xceptions.empty()) {
3739 if (gen_templates_) {
3740 out << indent() << "template <class Protocol_>" << endl;
3741 }
3742 out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::throw_"
3743 << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
3744 << prot_type << "* oprot, void* ctx, "
3745 << "::apache::thrift::TDelayedException* _throw)" << endl;
3746 scope_up(out);
3747
3748 if (gen_templates_ && !specialized) {
3749 // If oprot is a Protocol_ instance,
3750 // use the specialized throw function instead.
3751 out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
3752 << indent() << "if (_oprot) {" << endl << indent() << " return throw_"
3753 << tfunction->get_name() << "(cob, seqid, _oprot, ctx, _throw);" << endl << indent()
3754 << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl
3755 << endl;
3756 }
3757
3758 // Get the event handler context
3759 out << endl << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3760 << " ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
3761 << indent() << "}" << endl << indent()
3762 << "::apache::thrift::TProcessorContextFreer freer("
3763 << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl;
3764
3765 // Throw the TDelayedException, and catch the result
3766 out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_result result;"
3767 << endl << endl << indent() << "try {" << endl;
3768 indent_up();
3769 out << indent() << "_throw->throw_it();" << endl << indent() << "return cob(false);"
3770 << endl; // Is this possible? TBD.
3771 indent_down();
3772 out << indent() << '}';
3773 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3774 out << " catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
3775 << ") {" << endl;
3776 indent_up();
3777 out << indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name()
3778 << ";" << endl << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;"
3779 << endl;
3780 scope_down(out);
3781 }
3782
3783 // Handle the case where an undeclared exception is thrown
3784 out << " catch (std::exception& e) {" << endl;
3785 indent_up();
3786 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3787 << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
3788 << indent() << "}" << endl << endl << indent()
3789 << "::apache::thrift::TApplicationException x(e.what());" << endl << indent()
3790 << "oprot->writeMessageBegin(\"" << tfunction->get_name()
3791 << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
3792 << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
3793 << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
3794 << "oprot->getTransport()->flush();" << endl <<
3795 // We pass true to the cob here, since we did successfully write a
3796 // response, even though it is an exception response.
3797 // It looks like the argument is currently ignored, anyway.
3798 indent() << "return cob(true);" << endl;
3799 scope_down(out);
3800
3801 // Serialize the result into a struct
3802 out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3803 << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
3804 << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
3805 << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
3806 << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
3807 << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
3808 << indent() << "oprot->getTransport()->flush();" << endl << indent()
3809 << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
3810 << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
3811 << indent() << "}" << endl << indent() << "return cob(true);" << endl;
3812 scope_down(out);
3813 out << endl;
3814 } // for each function
3815 } // cob style
3816 }
3817
3818 /**
3819 * Generates a skeleton file of a server
3820 *
3821 * @param tservice The service to generate a server for.
3822 */
generate_service_skeleton(t_service * tservice)3823 void t_cpp_generator::generate_service_skeleton(t_service* tservice) {
3824 string svcname = tservice->get_name();
3825
3826 // Service implementation file includes
3827 string f_skeleton_name = get_out_dir() + svcname + "_server.skeleton.cpp";
3828
3829 string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));
3830
3831 ofstream_with_content_based_conditional_update f_skeleton;
3832 f_skeleton.open(f_skeleton_name.c_str());
3833 f_skeleton << "// This autogenerated skeleton file illustrates how to build a server." << endl
3834 << "// You should copy it to another filename to avoid overwriting it." << endl << endl
3835 << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
3836 << "#include <thrift/protocol/TBinaryProtocol.h>" << endl
3837 << "#include <thrift/server/TSimpleServer.h>" << endl
3838 << "#include <thrift/transport/TServerSocket.h>" << endl
3839 << "#include <thrift/transport/TBufferTransports.h>" << endl << endl
3840 << "using namespace ::apache::thrift;" << endl
3841 << "using namespace ::apache::thrift::protocol;" << endl
3842 << "using namespace ::apache::thrift::transport;" << endl
3843 << "using namespace ::apache::thrift::server;" << endl << endl;
3844
3845 // the following code would not compile:
3846 // using namespace ;
3847 // using namespace ::;
3848 if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
3849 f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
3850 }
3851
3852 f_skeleton << "class " << svcname << "Handler : virtual public " << svcname << "If {" << endl
3853 << " public:" << endl;
3854 indent_up();
3855 f_skeleton << indent() << svcname << "Handler() {" << endl << indent()
3856 << " // Your initialization goes here" << endl << indent() << "}" << endl << endl;
3857
3858 vector<t_function*> functions = tservice->get_functions();
3859 vector<t_function*>::iterator f_iter;
3860 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3861 generate_java_doc(f_skeleton, *f_iter);
3862 f_skeleton << indent() << function_signature(*f_iter, "") << " {" << endl << indent()
3863 << " // Your implementation goes here" << endl << indent() << " printf(\""
3864 << (*f_iter)->get_name() << "\\n\");" << endl << indent() << "}" << endl << endl;
3865 }
3866
3867 indent_down();
3868 f_skeleton << "};" << endl << endl;
3869
3870 f_skeleton << indent() << "int main(int argc, char **argv) {" << endl;
3871 indent_up();
3872 f_skeleton
3873 << indent() << "int port = 9090;" << endl << indent() << "::std::shared_ptr<" << svcname
3874 << "Handler> handler(new " << svcname << "Handler());" << endl << indent()
3875 << "::std::shared_ptr<TProcessor> processor(new " << svcname << "Processor(handler));" << endl
3876 << indent() << "::std::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));"
3877 << endl << indent()
3878 << "::std::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());" << endl
3879 << indent() << "::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());"
3880 << endl << endl << indent()
3881 << "TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);"
3882 << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl;
3883 indent_down();
3884 f_skeleton << "}" << endl << endl;
3885
3886 // Close the files
3887 f_skeleton.close();
3888 }
3889
3890 /**
3891 * Deserializes a field of any type.
3892 */
generate_deserialize_field(ostream & out,t_field * tfield,string prefix,string suffix)3893 void t_cpp_generator::generate_deserialize_field(ostream& out,
3894 t_field* tfield,
3895 string prefix,
3896 string suffix) {
3897 t_type* type = get_true_type(tfield->get_type());
3898
3899 if (type->is_void()) {
3900 throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name();
3901 }
3902
3903 string name = prefix + tfield->get_name() + suffix;
3904
3905 if (type->is_struct() || type->is_xception()) {
3906 generate_deserialize_struct(out, (t_struct*)type, name, is_reference(tfield));
3907 } else if (type->is_container()) {
3908 generate_deserialize_container(out, type, name);
3909 } else if (type->is_base_type()) {
3910 indent(out) << "xfer += iprot->";
3911 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
3912 switch (tbase) {
3913 case t_base_type::TYPE_VOID:
3914 throw "compiler error: cannot serialize void field in a struct: " + name;
3915 break;
3916 case t_base_type::TYPE_STRING:
3917 if (type->is_binary()) {
3918 out << "readBinary(" << name << ");";
3919 } else {
3920 out << "readString(" << name << ");";
3921 }
3922 break;
3923 case t_base_type::TYPE_BOOL:
3924 out << "readBool(" << name << ");";
3925 break;
3926 case t_base_type::TYPE_I8:
3927 out << "readByte(" << name << ");";
3928 break;
3929 case t_base_type::TYPE_I16:
3930 out << "readI16(" << name << ");";
3931 break;
3932 case t_base_type::TYPE_I32:
3933 out << "readI32(" << name << ");";
3934 break;
3935 case t_base_type::TYPE_I64:
3936 out << "readI64(" << name << ");";
3937 break;
3938 case t_base_type::TYPE_DOUBLE:
3939 out << "readDouble(" << name << ");";
3940 break;
3941 default:
3942 throw "compiler error: no C++ reader for base type " + t_base_type::t_base_name(tbase) + name;
3943 }
3944 out << endl;
3945 } else if (type->is_enum()) {
3946 string t = tmp("ecast");
3947 out << indent() << "int32_t " << t << ";" << endl << indent() << "xfer += iprot->readI32(" << t
3948 << ");" << endl << indent() << name << " = (" << type_name(type) << ")" << t << ";" << endl;
3949 } else {
3950 printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
3951 tfield->get_name().c_str(),
3952 type_name(type).c_str());
3953 }
3954 }
3955
3956 /**
3957 * Generates an unserializer for a variable. This makes two key assumptions,
3958 * first that there is a const char* variable named data that points to the
3959 * buffer for deserialization, and that there is a variable protocol which
3960 * is a reference to a TProtocol serialization object.
3961 */
generate_deserialize_struct(ostream & out,t_struct * tstruct,string prefix,bool pointer)3962 void t_cpp_generator::generate_deserialize_struct(ostream& out,
3963 t_struct* tstruct,
3964 string prefix,
3965 bool pointer) {
3966 if (pointer) {
3967 indent(out) << "if (!" << prefix << ") { " << endl;
3968 indent(out) << " " << prefix << " = ::std::shared_ptr<" << type_name(tstruct) << ">(new "
3969 << type_name(tstruct) << ");" << endl;
3970 indent(out) << "}" << endl;
3971 indent(out) << "xfer += " << prefix << "->read(iprot);" << endl;
3972 indent(out) << "bool wasSet = false;" << endl;
3973 const vector<t_field*>& members = tstruct->get_members();
3974 vector<t_field*>::const_iterator f_iter;
3975 for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
3976
3977 indent(out) << "if (" << prefix << "->__isset." << (*f_iter)->get_name()
3978 << ") { wasSet = true; }" << endl;
3979 }
3980 indent(out) << "if (!wasSet) { " << prefix << ".reset(); }" << endl;
3981 } else {
3982 indent(out) << "xfer += " << prefix << ".read(iprot);" << endl;
3983 }
3984 }
3985
generate_deserialize_container(ostream & out,t_type * ttype,string prefix)3986 void t_cpp_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) {
3987 scope_up(out);
3988
3989 string size = tmp("_size");
3990 string ktype = tmp("_ktype");
3991 string vtype = tmp("_vtype");
3992 string etype = tmp("_etype");
3993
3994 t_container* tcontainer = (t_container*)ttype;
3995 bool use_push = tcontainer->has_cpp_name();
3996
3997 indent(out) << prefix << ".clear();" << endl << indent() << "uint32_t " << size << ";" << endl;
3998
3999 // Declare variables, read header
4000 if (ttype->is_map()) {
4001 out << indent() << "::apache::thrift::protocol::TType " << ktype << ";" << endl << indent()
4002 << "::apache::thrift::protocol::TType " << vtype << ";" << endl << indent()
4003 << "xfer += iprot->readMapBegin(" << ktype << ", " << vtype << ", " << size << ");" << endl;
4004 } else if (ttype->is_set()) {
4005 out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
4006 << "xfer += iprot->readSetBegin(" << etype << ", " << size << ");" << endl;
4007 } else if (ttype->is_list()) {
4008 out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
4009 << "xfer += iprot->readListBegin(" << etype << ", " << size << ");" << endl;
4010 if (!use_push) {
4011 indent(out) << prefix << ".resize(" << size << ");" << endl;
4012 }
4013 }
4014
4015 // For loop iterates over elements
4016 string i = tmp("_i");
4017 out << indent() << "uint32_t " << i << ";" << endl << indent() << "for (" << i << " = 0; " << i
4018 << " < " << size << "; ++" << i << ")" << endl;
4019
4020 scope_up(out);
4021
4022 if (ttype->is_map()) {
4023 generate_deserialize_map_element(out, (t_map*)ttype, prefix);
4024 } else if (ttype->is_set()) {
4025 generate_deserialize_set_element(out, (t_set*)ttype, prefix);
4026 } else if (ttype->is_list()) {
4027 generate_deserialize_list_element(out, (t_list*)ttype, prefix, use_push, i);
4028 }
4029
4030 scope_down(out);
4031
4032 // Read container end
4033 if (ttype->is_map()) {
4034 indent(out) << "xfer += iprot->readMapEnd();" << endl;
4035 } else if (ttype->is_set()) {
4036 indent(out) << "xfer += iprot->readSetEnd();" << endl;
4037 } else if (ttype->is_list()) {
4038 indent(out) << "xfer += iprot->readListEnd();" << endl;
4039 }
4040
4041 scope_down(out);
4042 }
4043
4044 /**
4045 * Generates code to deserialize a map
4046 */
generate_deserialize_map_element(ostream & out,t_map * tmap,string prefix)4047 void t_cpp_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) {
4048 string key = tmp("_key");
4049 string val = tmp("_val");
4050 t_field fkey(tmap->get_key_type(), key);
4051 t_field fval(tmap->get_val_type(), val);
4052
4053 out << indent() << declare_field(&fkey) << endl;
4054
4055 generate_deserialize_field(out, &fkey);
4056 indent(out) << declare_field(&fval, false, false, false, true) << " = " << prefix << "[" << key
4057 << "];" << endl;
4058
4059 generate_deserialize_field(out, &fval);
4060 }
4061
generate_deserialize_set_element(ostream & out,t_set * tset,string prefix)4062 void t_cpp_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) {
4063 string elem = tmp("_elem");
4064 t_field felem(tset->get_elem_type(), elem);
4065
4066 indent(out) << declare_field(&felem) << endl;
4067
4068 generate_deserialize_field(out, &felem);
4069
4070 indent(out) << prefix << ".insert(" << elem << ");" << endl;
4071 }
4072
generate_deserialize_list_element(ostream & out,t_list * tlist,string prefix,bool use_push,string index)4073 void t_cpp_generator::generate_deserialize_list_element(ostream& out,
4074 t_list* tlist,
4075 string prefix,
4076 bool use_push,
4077 string index) {
4078 if (use_push) {
4079 string elem = tmp("_elem");
4080 t_field felem(tlist->get_elem_type(), elem);
4081 indent(out) << declare_field(&felem) << endl;
4082 generate_deserialize_field(out, &felem);
4083 indent(out) << prefix << ".push_back(" << elem << ");" << endl;
4084 } else {
4085 t_field felem(tlist->get_elem_type(), prefix + "[" + index + "]");
4086 generate_deserialize_field(out, &felem);
4087 }
4088 }
4089
4090 /**
4091 * Serializes a field of any type.
4092 *
4093 * @param tfield The field to serialize
4094 * @param prefix Name to prepend to field name
4095 */
generate_serialize_field(ostream & out,t_field * tfield,string prefix,string suffix)4096 void t_cpp_generator::generate_serialize_field(ostream& out,
4097 t_field* tfield,
4098 string prefix,
4099 string suffix) {
4100 t_type* type = get_true_type(tfield->get_type());
4101
4102 string name = prefix + tfield->get_name() + suffix;
4103
4104 // Do nothing for void types
4105 if (type->is_void()) {
4106 throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + name;
4107 }
4108
4109 if (type->is_struct() || type->is_xception()) {
4110 generate_serialize_struct(out, (t_struct*)type, name, is_reference(tfield));
4111 } else if (type->is_container()) {
4112 generate_serialize_container(out, type, name);
4113 } else if (type->is_base_type() || type->is_enum()) {
4114
4115 indent(out) << "xfer += oprot->";
4116
4117 if (type->is_base_type()) {
4118 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
4119 switch (tbase) {
4120 case t_base_type::TYPE_VOID:
4121 throw "compiler error: cannot serialize void field in a struct: " + name;
4122 break;
4123 case t_base_type::TYPE_STRING:
4124 if (type->is_binary()) {
4125 out << "writeBinary(" << name << ");";
4126 } else {
4127 out << "writeString(" << name << ");";
4128 }
4129 break;
4130 case t_base_type::TYPE_BOOL:
4131 out << "writeBool(" << name << ");";
4132 break;
4133 case t_base_type::TYPE_I8:
4134 out << "writeByte(" << name << ");";
4135 break;
4136 case t_base_type::TYPE_I16:
4137 out << "writeI16(" << name << ");";
4138 break;
4139 case t_base_type::TYPE_I32:
4140 out << "writeI32(" << name << ");";
4141 break;
4142 case t_base_type::TYPE_I64:
4143 out << "writeI64(" << name << ");";
4144 break;
4145 case t_base_type::TYPE_DOUBLE:
4146 out << "writeDouble(" << name << ");";
4147 break;
4148 default:
4149 throw "compiler error: no C++ writer for base type " + t_base_type::t_base_name(tbase)
4150 + name;
4151 }
4152 } else if (type->is_enum()) {
4153 out << "writeI32((int32_t)" << name << ");";
4154 }
4155 out << endl;
4156 } else {
4157 printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
4158 name.c_str(),
4159 type_name(type).c_str());
4160 }
4161 }
4162
4163 /**
4164 * Serializes all the members of a struct.
4165 *
4166 * @param tstruct The struct to serialize
4167 * @param prefix String prefix to attach to all fields
4168 */
generate_serialize_struct(ostream & out,t_struct * tstruct,string prefix,bool pointer)4169 void t_cpp_generator::generate_serialize_struct(ostream& out,
4170 t_struct* tstruct,
4171 string prefix,
4172 bool pointer) {
4173 if (pointer) {
4174 indent(out) << "if (" << prefix << ") {" << endl;
4175 indent(out) << " xfer += " << prefix << "->write(oprot); " << endl;
4176 indent(out) << "} else {"
4177 << "oprot->writeStructBegin(\"" << tstruct->get_name() << "\"); " << endl;
4178 indent(out) << " oprot->writeStructEnd();" << endl;
4179 indent(out) << " oprot->writeFieldStop();" << endl;
4180 indent(out) << "}" << endl;
4181 } else {
4182 indent(out) << "xfer += " << prefix << ".write(oprot);" << endl;
4183 }
4184 }
4185
generate_serialize_container(ostream & out,t_type * ttype,string prefix)4186 void t_cpp_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) {
4187 scope_up(out);
4188
4189 if (ttype->is_map()) {
4190 indent(out) << "xfer += oprot->writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type())
4191 << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", "
4192 << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
4193 } else if (ttype->is_set()) {
4194 indent(out) << "xfer += oprot->writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type())
4195 << ", "
4196 << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
4197 } else if (ttype->is_list()) {
4198 indent(out) << "xfer += oprot->writeListBegin("
4199 << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", "
4200 << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
4201 }
4202
4203 string iter = tmp("_iter");
4204 out << indent() << type_name(ttype) << "::const_iterator " << iter << ";" << endl << indent()
4205 << "for (" << iter << " = " << prefix << ".begin(); " << iter << " != " << prefix
4206 << ".end(); ++" << iter << ")" << endl;
4207 scope_up(out);
4208 if (ttype->is_map()) {
4209 generate_serialize_map_element(out, (t_map*)ttype, iter);
4210 } else if (ttype->is_set()) {
4211 generate_serialize_set_element(out, (t_set*)ttype, iter);
4212 } else if (ttype->is_list()) {
4213 generate_serialize_list_element(out, (t_list*)ttype, iter);
4214 }
4215 scope_down(out);
4216
4217 if (ttype->is_map()) {
4218 indent(out) << "xfer += oprot->writeMapEnd();" << endl;
4219 } else if (ttype->is_set()) {
4220 indent(out) << "xfer += oprot->writeSetEnd();" << endl;
4221 } else if (ttype->is_list()) {
4222 indent(out) << "xfer += oprot->writeListEnd();" << endl;
4223 }
4224
4225 scope_down(out);
4226 }
4227
4228 /**
4229 * Serializes the members of a map.
4230 *
4231 */
generate_serialize_map_element(ostream & out,t_map * tmap,string iter)4232 void t_cpp_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter) {
4233 t_field kfield(tmap->get_key_type(), iter + "->first");
4234 generate_serialize_field(out, &kfield, "");
4235
4236 t_field vfield(tmap->get_val_type(), iter + "->second");
4237 generate_serialize_field(out, &vfield, "");
4238 }
4239
4240 /**
4241 * Serializes the members of a set.
4242 */
generate_serialize_set_element(ostream & out,t_set * tset,string iter)4243 void t_cpp_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) {
4244 t_field efield(tset->get_elem_type(), "(*" + iter + ")");
4245 generate_serialize_field(out, &efield, "");
4246 }
4247
4248 /**
4249 * Serializes the members of a list.
4250 */
generate_serialize_list_element(ostream & out,t_list * tlist,string iter)4251 void t_cpp_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) {
4252 t_field efield(tlist->get_elem_type(), "(*" + iter + ")");
4253 generate_serialize_field(out, &efield, "");
4254 }
4255
4256 /**
4257 * Makes a :: prefix for a namespace
4258 *
4259 * @param ns The namespace, w/ periods in it
4260 * @return Namespaces
4261 */
namespace_prefix(string ns)4262 string t_cpp_generator::namespace_prefix(string ns) {
4263 // Always start with "::", to avoid possible name collisions with
4264 // other names in one of the current namespaces.
4265 //
4266 // We also need a leading space, in case the name is used inside of a
4267 // template parameter. "MyTemplate<::foo::Bar>" is not valid C++,
4268 // since "<:" is an alternative token for "[".
4269 string result = " ::";
4270
4271 if (ns.size() == 0) {
4272 return result;
4273 }
4274 string::size_type loc;
4275 while ((loc = ns.find(".")) != string::npos) {
4276 result += ns.substr(0, loc);
4277 result += "::";
4278 ns = ns.substr(loc + 1);
4279 }
4280 if (ns.size() > 0) {
4281 result += ns + "::";
4282 }
4283 return result;
4284 }
4285
4286 /**
4287 * Opens namespace.
4288 *
4289 * @param ns The namespace, w/ periods in it
4290 * @return Namespaces
4291 */
namespace_open(string ns)4292 string t_cpp_generator::namespace_open(string ns) {
4293 if (ns.size() == 0) {
4294 return "";
4295 }
4296 string result = "";
4297 string separator = "";
4298 string::size_type loc;
4299 while ((loc = ns.find(".")) != string::npos) {
4300 result += separator;
4301 result += "namespace ";
4302 result += ns.substr(0, loc);
4303 result += " {";
4304 separator = " ";
4305 ns = ns.substr(loc + 1);
4306 }
4307 if (ns.size() > 0) {
4308 result += separator + "namespace " + ns + " {";
4309 }
4310 return result;
4311 }
4312
4313 /**
4314 * Closes namespace.
4315 *
4316 * @param ns The namespace, w/ periods in it
4317 * @return Namespaces
4318 */
namespace_close(string ns)4319 string t_cpp_generator::namespace_close(string ns) {
4320 if (ns.size() == 0) {
4321 return "";
4322 }
4323 string result = "}";
4324 string::size_type loc;
4325 while ((loc = ns.find(".")) != string::npos) {
4326 result += "}";
4327 ns = ns.substr(loc + 1);
4328 }
4329 result += " // namespace";
4330 return result;
4331 }
4332
4333 /**
4334 * Returns a C++ type name
4335 *
4336 * @param ttype The type
4337 * @return String of the type name, i.e. std::set<type>
4338 */
type_name(t_type * ttype,bool in_typedef,bool arg)4339 string t_cpp_generator::type_name(t_type* ttype, bool in_typedef, bool arg) {
4340 if (ttype->is_base_type()) {
4341 string bname = base_type_name(((t_base_type*)ttype)->get_base());
4342 std::map<string, string>::iterator it = ttype->annotations_.find("cpp.type");
4343 if (it != ttype->annotations_.end()) {
4344 bname = it->second;
4345 }
4346
4347 if (!arg) {
4348 return bname;
4349 }
4350
4351 if (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING) {
4352 return "const " + bname + "&";
4353 } else {
4354 return "const " + bname;
4355 }
4356 }
4357
4358 // Check for a custom overloaded C++ name
4359 if (ttype->is_container()) {
4360 string cname;
4361
4362 t_container* tcontainer = (t_container*)ttype;
4363 if (tcontainer->has_cpp_name()) {
4364 cname = tcontainer->get_cpp_name();
4365 } else if (ttype->is_map()) {
4366 t_map* tmap = (t_map*)ttype;
4367 cname = "std::map<" + type_name(tmap->get_key_type(), in_typedef) + ", "
4368 + type_name(tmap->get_val_type(), in_typedef) + "> ";
4369 } else if (ttype->is_set()) {
4370 t_set* tset = (t_set*)ttype;
4371 cname = "std::set<" + type_name(tset->get_elem_type(), in_typedef) + "> ";
4372 } else if (ttype->is_list()) {
4373 t_list* tlist = (t_list*)ttype;
4374 cname = "std::vector<" + type_name(tlist->get_elem_type(), in_typedef) + "> ";
4375 }
4376
4377 if (arg) {
4378 return "const " + cname + "&";
4379 } else {
4380 return cname;
4381 }
4382 }
4383
4384 string class_prefix;
4385 if (in_typedef && (ttype->is_struct() || ttype->is_xception())) {
4386 class_prefix = "class ";
4387 }
4388
4389 // Check if it needs to be namespaced
4390 string pname;
4391 t_program* program = ttype->get_program();
4392 if (program != nullptr && program != program_) {
4393 pname = class_prefix + namespace_prefix(program->get_namespace("cpp")) + ttype->get_name();
4394 } else {
4395 pname = class_prefix + ttype->get_name();
4396 }
4397
4398 if (ttype->is_enum() && !gen_pure_enums_) {
4399 pname += "::type";
4400 }
4401
4402 if (arg) {
4403 if (is_complex_type(ttype)) {
4404 return "const " + pname + "&";
4405 } else {
4406 return "const " + pname;
4407 }
4408 } else {
4409 return pname;
4410 }
4411 }
4412
4413 /**
4414 * Returns the C++ type that corresponds to the thrift type.
4415 *
4416 * @param tbase The base type
4417 * @return Explicit C++ type, i.e. "int32_t"
4418 */
base_type_name(t_base_type::t_base tbase)4419 string t_cpp_generator::base_type_name(t_base_type::t_base tbase) {
4420 switch (tbase) {
4421 case t_base_type::TYPE_VOID:
4422 return "void";
4423 case t_base_type::TYPE_STRING:
4424 return "std::string";
4425 case t_base_type::TYPE_BOOL:
4426 return "bool";
4427 case t_base_type::TYPE_I8:
4428 return "int8_t";
4429 case t_base_type::TYPE_I16:
4430 return "int16_t";
4431 case t_base_type::TYPE_I32:
4432 return "int32_t";
4433 case t_base_type::TYPE_I64:
4434 return "int64_t";
4435 case t_base_type::TYPE_DOUBLE:
4436 return "double";
4437 default:
4438 throw "compiler error: no C++ base type name for base type " + t_base_type::t_base_name(tbase);
4439 }
4440 }
4441
4442 /**
4443 * Declares a field, which may include initialization as necessary.
4444 *
4445 * @param ttype The type
4446 * @return Field declaration, i.e. int x = 0;
4447 */
declare_field(t_field * tfield,bool init,bool pointer,bool constant,bool reference)4448 string t_cpp_generator::declare_field(t_field* tfield,
4449 bool init,
4450 bool pointer,
4451 bool constant,
4452 bool reference) {
4453 // TODO(mcslee): do we ever need to initialize the field?
4454 string result = "";
4455 if (constant) {
4456 result += "const ";
4457 }
4458 result += type_name(tfield->get_type());
4459 if (is_reference(tfield)) {
4460 result = "::std::shared_ptr<" + result + ">";
4461 }
4462 if (pointer) {
4463 result += "*";
4464 }
4465 if (reference) {
4466 result += "&";
4467 }
4468 result += " " + tfield->get_name();
4469 if (init) {
4470 t_type* type = get_true_type(tfield->get_type());
4471
4472 if (type->is_base_type()) {
4473 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
4474 switch (tbase) {
4475 case t_base_type::TYPE_VOID:
4476 case t_base_type::TYPE_STRING:
4477 break;
4478 case t_base_type::TYPE_BOOL:
4479 result += " = false";
4480 break;
4481 case t_base_type::TYPE_I8:
4482 case t_base_type::TYPE_I16:
4483 case t_base_type::TYPE_I32:
4484 case t_base_type::TYPE_I64:
4485 result += " = 0";
4486 break;
4487 case t_base_type::TYPE_DOUBLE:
4488 result += " = (double)0";
4489 break;
4490 default:
4491 throw "compiler error: no C++ initializer for base type " + t_base_type::t_base_name(tbase);
4492 }
4493 } else if (type->is_enum()) {
4494 result += " = (" + type_name(type) + ")0";
4495 }
4496 }
4497 if (!reference) {
4498 result += ";";
4499 }
4500 return result;
4501 }
4502
4503 /**
4504 * Renders a function signature of the form 'type name(args)'
4505 *
4506 * @param tfunction Function definition
4507 * @return String of rendered function definition
4508 */
function_signature(t_function * tfunction,string style,string prefix,bool name_params)4509 string t_cpp_generator::function_signature(t_function* tfunction,
4510 string style,
4511 string prefix,
4512 bool name_params) {
4513 t_type* ttype = tfunction->get_returntype();
4514 t_struct* arglist = tfunction->get_arglist();
4515 bool has_xceptions = !tfunction->get_xceptions()->get_members().empty();
4516
4517 if (style == "") {
4518 if (is_complex_type(ttype)) {
4519 return "void " + prefix + tfunction->get_name() + "(" + type_name(ttype)
4520 + (name_params ? "& _return" : "& /* _return */")
4521 + argument_list(arglist, name_params, true) + ")";
4522 } else {
4523 return type_name(ttype) + " " + prefix + tfunction->get_name() + "("
4524 + argument_list(arglist, name_params) + ")";
4525 }
4526 } else if (style.substr(0, 3) == "Cob") {
4527 string cob_type;
4528 string exn_cob;
4529 if (style == "CobCl") {
4530 cob_type = "(" + service_name_ + "CobClient";
4531 if (gen_templates_) {
4532 cob_type += "T<Protocol_>";
4533 }
4534 cob_type += "* client)";
4535 } else if (style == "CobSv") {
4536 cob_type = (ttype->is_void() ? "()" : ("(" + type_name(ttype) + " const& _return)"));
4537 if (has_xceptions) {
4538 exn_cob
4539 = ", ::std::function<void(::apache::thrift::TDelayedException* _throw)> /* exn_cob */";
4540 }
4541 } else {
4542 throw "UNKNOWN STYLE";
4543 }
4544
4545 return "void " + prefix + tfunction->get_name() + "(::std::function<void" + cob_type + "> cob"
4546 + exn_cob + argument_list(arglist, name_params, true) + ")";
4547 } else {
4548 throw "UNKNOWN STYLE";
4549 }
4550 }
4551
4552 /**
4553 * Renders a field list
4554 *
4555 * @param tstruct The struct definition
4556 * @return Comma sepearated list of all field names in that struct
4557 */
argument_list(t_struct * tstruct,bool name_params,bool start_comma)4558 string t_cpp_generator::argument_list(t_struct* tstruct, bool name_params, bool start_comma) {
4559 string result = "";
4560
4561 const vector<t_field*>& fields = tstruct->get_members();
4562 vector<t_field*>::const_iterator f_iter;
4563 bool first = !start_comma;
4564 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
4565 if (first) {
4566 first = false;
4567 } else {
4568 result += ", ";
4569 }
4570 result += type_name((*f_iter)->get_type(), false, true) + " "
4571 + (name_params ? (*f_iter)->get_name() : "/* " + (*f_iter)->get_name() + " */");
4572 }
4573 return result;
4574 }
4575
4576 /**
4577 * Converts the parse type to a C++ enum string for the given type.
4578 *
4579 * @param type Thrift Type
4580 * @return String of C++ code to definition of that type constant
4581 */
type_to_enum(t_type * type)4582 string t_cpp_generator::type_to_enum(t_type* type) {
4583 type = get_true_type(type);
4584
4585 if (type->is_base_type()) {
4586 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
4587 switch (tbase) {
4588 case t_base_type::TYPE_VOID:
4589 throw "NO T_VOID CONSTRUCT";
4590 case t_base_type::TYPE_STRING:
4591 return "::apache::thrift::protocol::T_STRING";
4592 case t_base_type::TYPE_BOOL:
4593 return "::apache::thrift::protocol::T_BOOL";
4594 case t_base_type::TYPE_I8:
4595 return "::apache::thrift::protocol::T_BYTE";
4596 case t_base_type::TYPE_I16:
4597 return "::apache::thrift::protocol::T_I16";
4598 case t_base_type::TYPE_I32:
4599 return "::apache::thrift::protocol::T_I32";
4600 case t_base_type::TYPE_I64:
4601 return "::apache::thrift::protocol::T_I64";
4602 case t_base_type::TYPE_DOUBLE:
4603 return "::apache::thrift::protocol::T_DOUBLE";
4604 }
4605 } else if (type->is_enum()) {
4606 return "::apache::thrift::protocol::T_I32";
4607 } else if (type->is_struct()) {
4608 return "::apache::thrift::protocol::T_STRUCT";
4609 } else if (type->is_xception()) {
4610 return "::apache::thrift::protocol::T_STRUCT";
4611 } else if (type->is_map()) {
4612 return "::apache::thrift::protocol::T_MAP";
4613 } else if (type->is_set()) {
4614 return "::apache::thrift::protocol::T_SET";
4615 } else if (type->is_list()) {
4616 return "::apache::thrift::protocol::T_LIST";
4617 }
4618
4619 throw "INVALID TYPE IN type_to_enum: " + type->get_name();
4620 }
4621
get_include_prefix(const t_program & program) const4622 string t_cpp_generator::get_include_prefix(const t_program& program) const {
4623 string include_prefix = program.get_include_prefix();
4624 if (!use_include_prefix_ || (include_prefix.size() > 0 && include_prefix[0] == '/')) {
4625 // if flag is turned off or this is absolute path, return empty prefix
4626 return "";
4627 }
4628
4629 string::size_type last_slash = string::npos;
4630 if ((last_slash = include_prefix.rfind("/")) != string::npos) {
4631 return include_prefix.substr(0, last_slash)
4632 + (get_program()->is_out_path_absolute() ? "/" : "/" + out_dir_base_ + "/");
4633 }
4634
4635 return "";
4636 }
4637
get_legal_program_name(std::string program_name)4638 string t_cpp_generator::get_legal_program_name(std::string program_name)
4639 {
4640 std::size_t found = 0;
4641
4642 while(true) {
4643 found = program_name.find('.');
4644
4645 if(found != string::npos) {
4646 program_name = program_name.replace(found, 1, "_");
4647 } else {
4648 break;
4649 }
4650 }
4651
4652 return program_name;
4653 }
4654
4655 THRIFT_REGISTER_GENERATOR(
4656 cpp,
4657 "C++",
4658 " cob_style: Generate \"Continuation OBject\"-style classes.\n"
4659 " no_client_completion:\n"
4660 " Omit calls to completion__() in CobClient class.\n"
4661 " no_default_operators:\n"
4662 " Omits generation of default operators ==, != and <\n"
4663 " templates: Generate templatized reader/writer methods.\n"
4664 " pure_enums: Generate pure enums instead of wrapper classes.\n"
4665 " include_prefix: Use full include paths in generated files.\n"
4666 " moveable_types: Generate move constructors and assignment operators.\n"
4667 " no_ostream_operators:\n"
4668 " Omit generation of ostream definitions.\n"
4669 " no_skeleton: Omits generation of skeleton.\n")
4670