r1459@opsdev009 (orig r77477): dreiss | 2008-01-11 12:59:03 -0800
[amiethrift.git] / compiler / cpp / src / generate / t_cocoa_generator.cc
blob1356c35598f08cc5d392d7e680dd3128754dd8ee
1 // Copyright (c) 2006- Facebook
2 // Distributed under the Thrift Software License
3 //
4 // See accompanying file LICENSE or visit the Thrift site at:
5 // http://developers.facebook.com/thrift/
7 #include <stdlib.h>
8 #include <sys/stat.h>
9 #include <sstream>
10 #include "t_cocoa_generator.h"
11 #include "platform.h"
12 using namespace std;
14 /**
15 * Prepares for file generation by opening up the necessary file output
16 * streams.
18 void t_cocoa_generator::init_generator() {
19 // Make output directory
20 MKDIR(get_out_dir().c_str());
21 cocoa_prefix_ = program_->get_cocoa_prefix();
23 // we have a .h header file...
24 string f_header_name = program_name_+".h";
25 string f_header_fullname = get_out_dir()+f_header_name;
26 f_header_.open(f_header_fullname.c_str());
28 f_header_ <<
29 autogen_comment() <<
30 endl;
32 f_header_ <<
33 cocoa_imports() <<
34 cocoa_thrift_imports();
36 // ...and a .m implementation file
37 string f_impl_name = get_out_dir()+program_name_+".m";
38 f_impl_.open(f_impl_name.c_str());
40 f_impl_ <<
41 autogen_comment() <<
42 endl;
44 f_impl_ <<
45 cocoa_imports() <<
46 cocoa_thrift_imports() <<
47 "#import \"" << f_header_name << "\"" << endl <<
48 endl;
52 /**
53 * Prints standard Cocoa imports
55 * @return List of imports for Cocoa libraries
57 string t_cocoa_generator::cocoa_imports() {
58 return
59 string() +
60 "#import <Cocoa/Cocoa.h>\n" +
61 "\n";
64 /**
65 * Prints thrift runtime imports
67 * @return List of imports necessary for thrift runtime
69 string t_cocoa_generator::cocoa_thrift_imports() {
70 string result = string() +
71 "#import <TProtocol.h>\n" +
72 "#import <TApplicationException.h>\n" +
73 "#import <TProtocolUtil.h>\n" +
74 "\n";
76 // Include other Thrift includes
77 const vector<t_program*>& includes = program_->get_includes();
78 for (size_t i = 0; i < includes.size(); ++i) {
79 result += "#import \"" + includes[i]->get_name() + ".h\"" + "\n";
81 result += "\n";
83 return result;
87 /**
88 * Finish up generation.
90 void t_cocoa_generator::close_generator()
92 // stick our constants declarations at the end of the header file
93 // since they refer to things we are defining.
94 f_header_ << constants_declarations_;
97 /**
98 * Generates a typedef. This is just a simple 1-liner in objective-c
100 * @param ttypedef The type definition
102 void t_cocoa_generator::generate_typedef(t_typedef* ttypedef) {
103 f_header_ <<
104 indent() << "typedef " << type_name(ttypedef->get_type()) << " " << cocoa_prefix_ << ttypedef->get_symbolic() << ";" << endl <<
105 endl;
109 * Generates code for an enumerated type. In Objective-C, this is
110 * essentially the same as the thrift definition itself, using the
111 * enum keyword in Objective-C. For namespace purposes, the name of
112 * the enum plus an underscore is prefixed onto each element.
114 * @param tenum The enumeration
116 void t_cocoa_generator::generate_enum(t_enum* tenum) {
117 f_header_ <<
118 indent() << "enum " << cocoa_prefix_ << tenum->get_name() << " {" << endl;
119 indent_up();
121 vector<t_enum_value*> constants = tenum->get_constants();
122 vector<t_enum_value*>::iterator c_iter;
123 bool first = true;
124 for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
125 if (first) {
126 first = false;
127 } else {
128 f_header_ <<
129 "," << endl;
131 f_header_ <<
132 indent() << tenum->get_name() << "_" << (*c_iter)->get_name();
133 if ((*c_iter)->has_value()) {
134 f_header_ <<
135 " = " << (*c_iter)->get_value();
139 indent_down();
140 f_header_ <<
141 endl <<
142 "};" << endl <<
143 endl;
147 * Generates a class that holds all the constants. Primitive values
148 * could have been placed outside this class, but I just put
149 * everything in for consistency.
151 void t_cocoa_generator::generate_consts(std::vector<t_const*> consts) {
152 std::ostringstream const_interface;
153 string constants_class_name = cocoa_prefix_ + program_name_ + "Constants";
155 const_interface << "@interface " << constants_class_name << " ";
156 scope_up(const_interface);
157 scope_down(const_interface);
159 // getter method for each constant defined.
160 vector<t_const*>::iterator c_iter;
161 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
162 string name = (*c_iter)->get_name();
163 t_type* type = (*c_iter)->get_type();
164 const_interface <<
165 "+ (" << type_name(type) << ") " << name << ";" << endl;
168 const_interface << "@end";
170 // this gets spit into the header file in ::close_generator
171 constants_declarations_ = const_interface.str();
173 // static variables in the .m hold all constant values
174 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
175 string name = (*c_iter)->get_name();
176 t_type* type = (*c_iter)->get_type();
177 f_impl_ <<
178 "static " << type_name(type) << " " << cocoa_prefix_ << name;
179 if (!type->is_container() && !type->is_struct()) {
180 f_impl_ << " = " << render_const_value(name, type, (*c_iter)->get_value());
182 f_impl_ << ";" << endl;
184 f_impl_ << endl;
186 f_impl_ << "@implementation " << constants_class_name << endl;
188 // initialize complex constants when the class is loaded
189 f_impl_ << "+ (void) initialize ";
190 scope_up(f_impl_);
192 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
193 if ((*c_iter)->get_type()->is_container() ||
194 (*c_iter)->get_type()->is_struct()) {
195 string name = (*c_iter)->get_name();
196 f_impl_ << indent() << name << " = " << render_const_value(name,
197 (*c_iter)->get_type(),
198 (*c_iter)->get_value());
199 f_impl_ << ";" << endl;
202 scope_down(f_impl_);
204 // getter method for each constant
205 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
206 string name = (*c_iter)->get_name();
207 t_type* type = (*c_iter)->get_type();
208 f_impl_ <<
209 "+ (" << type_name(type) << ") " << name;
210 scope_up(f_impl_);
211 indent(f_impl_) << "return " << name << ";" << endl;
212 scope_down(f_impl_);
215 f_impl_ << "@end" << endl << endl;
220 * Generates a struct definition for a thrift data type. This is a class
221 * with protected data members, read(), write(), and getters and setters.
223 * @param tstruct The struct definition
225 void t_cocoa_generator::generate_struct(t_struct* tstruct) {
226 generate_cocoa_struct_interface(f_header_, tstruct, false);
227 generate_cocoa_struct_implementation(f_impl_, tstruct, false);
231 * Exceptions are structs, but they inherit from NSException
233 * @param tstruct The struct definition
235 void t_cocoa_generator::generate_xception(t_struct* txception) {
236 generate_cocoa_struct_interface(f_header_, txception, true);
237 generate_cocoa_struct_implementation(f_impl_, txception, true);
242 * Generate the interface for a struct
244 * @param tstruct The struct definition
246 void t_cocoa_generator::generate_cocoa_struct_interface(ofstream &out,
247 t_struct* tstruct,
248 bool is_exception) {
249 out << "@interface " << cocoa_prefix_ << tstruct->get_name() << " : ";
251 if (is_exception) {
252 out << "NSException ";
253 } else {
254 out << "NSObject ";
257 scope_up(out);
259 // members are protected. this is redundant, but explicit.
260 // f_header_ << endl << "@protected:" << endl;
262 const vector<t_field*>& members = tstruct->get_members();
264 // member varialbes
265 vector<t_field*>::const_iterator m_iter;
266 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
267 out << indent() << declare_field(*m_iter) << endl;
270 if (members.size() > 0) {
271 out << endl;
272 // isset fields
273 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
274 indent(out) <<
275 "BOOL __" << (*m_iter)->get_name() << "_isset;" << endl;
279 scope_down(out);
280 out << endl;
282 // initializer for all fields
283 if (!members.empty()) {
284 generate_cocoa_struct_initializer_signature(out, tstruct);
285 out << ";" << endl;
287 out << endl;
289 // read and write
290 out << "- (void) read: (id <TProtocol>) inProtocol;" << endl;
291 out << "- (void) write: (id <TProtocol>) outProtocol;" << endl;
292 out << endl;
294 // getters and setters
295 generate_cocoa_struct_field_accessor_declarations(out, tstruct, is_exception);
297 out << "@end" << endl << endl;
302 * Generate signature for initializer of struct with a parameter for
303 * each field.
305 void t_cocoa_generator::generate_cocoa_struct_initializer_signature(ofstream &out,
306 t_struct* tstruct) {
307 const vector<t_field*>& members = tstruct->get_members();
308 vector<t_field*>::const_iterator m_iter;
309 indent(out) << "- (id) initWith";
310 for (m_iter = members.begin(); m_iter != members.end(); ) {
311 if (m_iter == members.begin()) {
312 out << capitalize((*m_iter)->get_name());
313 } else {
314 out << (*m_iter)->get_name();
316 out << ": (" << type_name((*m_iter)->get_type()) << ") " <<
317 (*m_iter)->get_name();
318 ++m_iter;
319 if (m_iter != members.end()) {
320 out << " ";
327 * Generate getter and setter declarations for all fields, plus an
328 * IsSet getter.
330 void t_cocoa_generator::generate_cocoa_struct_field_accessor_declarations(ofstream &out,
331 t_struct* tstruct,
332 bool is_exception) {
333 const vector<t_field*>& members = tstruct->get_members();
334 vector<t_field*>::const_iterator m_iter;
335 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
336 out << indent() << "- (" << type_name((*m_iter)->get_type()) << ") " << decapitalize((*m_iter)->get_name()) << ";" << endl;
337 out << indent() << "- (void) set" << capitalize((*m_iter)->get_name()) <<
338 ": (" << type_name((*m_iter)->get_type()) << ") " << (*m_iter)->get_name() << ";" << endl;
339 out << indent() << "- (BOOL) " << (*m_iter)->get_name() << "IsSet;" << endl << endl;
345 * Generate struct implementation.
347 * @param tstruct The struct definition
348 * @param is_exception Is this an exception?
349 * @param is_result If this is a result it needs a different writer
351 void t_cocoa_generator::generate_cocoa_struct_implementation(ofstream &out,
352 t_struct* tstruct,
353 bool is_exception,
354 bool is_result) {
355 indent(out) <<
356 "@implementation " << cocoa_prefix_ << tstruct->get_name() << endl;
358 // exceptions need to call the designated initializer on NSException
359 if (is_exception) {
360 out << indent() << "- (id) init" << endl;
361 scope_up(out);
362 out << indent() << "return [super initWithName: @\"" << tstruct->get_name() <<
363 "\" reason: @\"unknown\" userInfo: nil];" << endl;
364 scope_down(out);
367 // initializer with all fields as params
368 const vector<t_field*>& members = tstruct->get_members();
369 if (!members.empty()) {
370 generate_cocoa_struct_initializer_signature(out, tstruct);
371 out << endl;
372 scope_up(out);
373 if (is_exception) {
374 out << indent() << "self = [self init];" << endl;
375 } else {
376 out << indent() << "self = [super init];" << endl;
379 vector<t_field*>::const_iterator m_iter;
380 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
381 t_type* t = get_true_type((*m_iter)->get_type());
382 out << indent() << "__" << (*m_iter)->get_name() << " = ";
383 if (type_can_be_null(t)) {
384 out << "[" << (*m_iter)->get_name() << " retain];" << endl;
385 } else {
386 out << (*m_iter)->get_name() << ";" << endl;
388 out << indent() << "__" << (*m_iter)->get_name() << "_isset = YES;" << endl;
391 out << indent() << "return self;" << endl;
392 scope_down(out);
393 out << endl;
396 // dealloc
397 if (!members.empty()) {
398 out << "- (void) dealloc" << endl;
399 scope_up(out);
401 vector<t_field*>::const_iterator m_iter;
402 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
403 t_type* t = get_true_type((*m_iter)->get_type());
404 if (type_can_be_null(t)) {
405 indent(out) << "[__" << (*m_iter)->get_name() << " release];" << endl;
409 out << indent() << "[super dealloc];" << endl;
410 scope_down(out);
411 out << endl;
414 // the rest of the methods
415 generate_cocoa_struct_field_accessor_implementations(out, tstruct, is_exception);
416 generate_cocoa_struct_reader(out, tstruct);
417 if (is_result) {
418 generate_cocoa_struct_result_writer(out, tstruct);
419 } else {
420 generate_cocoa_struct_writer(out, tstruct);
422 generate_cocoa_struct_description(out, tstruct);
424 out << "@end" << endl << endl;
429 * Generates a function to read all the fields of the struct.
431 * @param tstruct The struct definition
433 void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out,
434 t_struct* tstruct) {
435 out <<
436 "- (void) read: (id <TProtocol>) inProtocol" << endl;
437 scope_up(out);
439 const vector<t_field*>& fields = tstruct->get_members();
440 vector<t_field*>::const_iterator f_iter;
442 // Declare stack tmp variables
443 indent(out) << "NSString * fieldName;" << endl;
444 indent(out) << "int fieldType;" << endl;
445 indent(out) << "int fieldID;" << endl;
446 out << endl;
448 indent(out) << "[inProtocol readStructBeginReturningName: NULL];" << endl;
450 // Loop over reading in fields
451 indent(out) <<
452 "while (true)" << endl;
453 scope_up(out);
455 // Read beginning field marker
456 indent(out) <<
457 "[inProtocol readFieldBeginReturningName: &fieldName type: &fieldType fieldID: &fieldID];" << endl;
459 // Check for field STOP marker and break
460 indent(out) <<
461 "if (fieldType == TType_STOP) { " << endl;
462 indent_up();
463 indent(out) <<
464 "break;" << endl;
465 indent_down();
466 indent(out) <<
467 "}" << endl;
469 // Switch statement on the field we are reading
470 indent(out) <<
471 "switch (fieldID)" << endl;
473 scope_up(out);
475 // Generate deserialization code for known cases
476 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
477 indent(out) <<
478 "case " << (*f_iter)->get_key() << ":" << endl;
479 indent_up();
480 indent(out) <<
481 "if (fieldType == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl;
482 indent_up();
484 generate_deserialize_field(out, *f_iter, "fieldValue");
485 indent(out) << call_field_setter(*f_iter, "fieldValue") << endl;
486 // if this is an allocated field, release it since the struct
487 // is now retaining it
488 if (type_can_be_null((*f_iter)->get_type())) {
489 // deserialized strings are autorelease, so don't release them
490 if (!(get_true_type((*f_iter)->get_type())->is_string())) {
491 indent(out) << "[fieldValue release];" << endl;
495 indent_down();
496 out <<
497 indent() << "} else { " << endl <<
498 indent() << " [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl <<
499 indent() << "}" << endl <<
500 indent() << "break;" << endl;
501 indent_down();
504 // In the default case we skip the field
505 out <<
506 indent() << "default:" << endl <<
507 indent() << " [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl <<
508 indent() << " break;" << endl;
510 scope_down(out);
512 // Read field end marker
513 indent(out) <<
514 "[inProtocol readFieldEnd];" << endl;
516 scope_down(out);
518 out <<
519 indent() << "[inProtocol readStructEnd];" << endl;
521 indent_down();
522 out <<
523 indent() << "}" << endl <<
524 endl;
528 * Generates a function to write all the fields of the struct
530 * @param tstruct The struct definition
532 void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out,
533 t_struct* tstruct) {
534 out <<
535 indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
536 indent_up();
538 string name = tstruct->get_name();
539 const vector<t_field*>& fields = tstruct->get_members();
540 vector<t_field*>::const_iterator f_iter;
542 out <<
543 indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
545 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
546 out <<
547 indent() << "if (__" << (*f_iter)->get_name() << "_isset) {" << endl;
548 indent_up();
549 bool null_allowed = type_can_be_null((*f_iter)->get_type());
550 if (null_allowed) {
551 out <<
552 indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
553 indent_up();
556 indent(out) << "[outProtocol writeFieldBeginWithName: @\"" <<
557 (*f_iter)->get_name() << "\" type: " << type_to_enum((*f_iter)->get_type()) <<
558 " fieldID: " << (*f_iter)->get_key() << "];" << endl;
560 // Write field contents
561 generate_serialize_field(out, *f_iter, "__"+(*f_iter)->get_name());
563 // Write field closer
564 indent(out) <<
565 "[outProtocol writeFieldEnd];" << endl;
567 if (null_allowed) {
568 scope_down(out);
570 scope_down(out);
572 // Write the struct map
573 out <<
574 indent() << "[outProtocol writeFieldStop];" << endl <<
575 indent() << "[outProtocol writeStructEnd];" << endl;
577 indent_down();
578 out <<
579 indent() << "}" << endl <<
580 endl;
584 * Generates a function to write all the fields of the struct, which
585 * is a function result. These fields are only written if they are
586 * set, and only one of them can be set at a time.
588 * @param tstruct The struct definition
590 void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out,
591 t_struct* tstruct) {
592 out <<
593 indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
594 indent_up();
596 string name = tstruct->get_name();
597 const vector<t_field*>& fields = tstruct->get_members();
598 vector<t_field*>::const_iterator f_iter;
600 out <<
601 indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
603 bool first = true;
604 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
605 if (first) {
606 first = false;
607 out <<
608 endl <<
609 indent() << "if ";
610 } else {
611 out <<
612 " else if ";
615 out <<
616 "(__" << (*f_iter)->get_name() << "_isset) {" << endl;
617 indent_up();
619 bool null_allowed = type_can_be_null((*f_iter)->get_type());
620 if (null_allowed) {
621 out <<
622 indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
623 indent_up();
626 indent(out) << "[outProtocol writeFieldBeginWithName: @\"" <<
627 (*f_iter)->get_name() << "\" type: " << type_to_enum((*f_iter)->get_type()) <<
628 " fieldID: " << (*f_iter)->get_key() << "];" << endl;
630 // Write field contents
631 generate_serialize_field(out, *f_iter, "__"+(*f_iter)->get_name());
633 // Write field closer
634 indent(out) <<
635 "[outProtocol writeFieldEnd];" << endl;
637 if (null_allowed) {
638 indent_down();
639 indent(out) << "}" << endl;
642 indent_down();
643 indent(out) << "}";
645 // Write the struct map
646 out <<
647 endl <<
648 indent() << "[outProtocol writeFieldStop];" << endl <<
649 indent() << "[outProtocol writeStructEnd];" << endl;
651 indent_down();
652 out <<
653 indent() << "}" << endl <<
654 endl;
658 * Generate property accessor methods for all fields in the struct.
659 * getter, setter, isset getter.
661 * @param tstruct The struct definition
663 void t_cocoa_generator::generate_cocoa_struct_field_accessor_implementations(ofstream& out,
664 t_struct* tstruct,
665 bool is_exception) {
666 const vector<t_field*>& fields = tstruct->get_members();
667 vector<t_field*>::const_iterator f_iter;
668 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
669 t_field* field = *f_iter;
670 t_type* type = get_true_type(field->get_type());
671 std::string field_name = field->get_name();
672 std::string cap_name = field_name;
673 cap_name[0] = toupper(cap_name[0]);
675 // Simple getter
676 indent(out) << "- (" << type_name(type) << ") ";
677 out << field_name << " {" << endl;
678 indent_up();
679 if (!type_can_be_null(type)) {
680 indent(out) << "return __" << field_name << ";" << endl;
681 } else {
682 indent(out) << "return [[__" << field_name << " retain] autorelease];" << endl;
684 indent_down();
685 indent(out) << "}" << endl << endl;
687 // Simple setter
688 indent(out) << "- (void) set" << cap_name << ": (" << type_name(type) <<
689 ") " << field_name << " {" << endl;
690 indent_up();
691 if (!type_can_be_null(type)) {
692 indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
693 } else {
694 indent(out) << "[" << field_name << " retain];" << endl;
695 indent(out) << "[__" << field_name << " release];" << endl;
696 indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
698 indent(out) << "__" << field_name << "_isset = YES;" << endl;
699 indent_down();
700 indent(out) << "}" << endl << endl;
702 // IsSet
703 indent(out) << "- (BOOL) " << field_name << "IsSet {" << endl;
704 indent_up();
705 indent(out) << "return __" << field_name << "_isset;" << endl;
706 indent_down();
707 indent(out) << "}" << endl << endl;
709 // Unsetter - do we need this?
710 indent(out) << "- (void) unset" << cap_name << " {" << endl;
711 indent_up();
712 if (type_can_be_null(type)) {
713 indent(out) << "[__" << field_name << " release];" << endl;
714 indent(out) << "__" << field_name << " = nil;" << endl;
716 indent(out) << "__" << field_name << "_isset = NO;" << endl;
717 indent_down();
718 indent(out) << "}" << endl << endl;
723 * Generates a description method for the given struct
725 * @param tstruct The struct definition
727 void t_cocoa_generator::generate_cocoa_struct_description(ofstream& out,
728 t_struct* tstruct) {
729 out <<
730 indent() << "- (NSString *) description {" << endl;
731 indent_up();
733 out <<
734 indent() << "NSMutableString * ms = [NSMutableString stringWithString: @\"" <<
735 tstruct->get_name() << "(\"];" << endl;
737 const vector<t_field*>& fields = tstruct->get_members();
738 vector<t_field*>::const_iterator f_iter;
739 bool first = true;
740 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
741 if (first) {
742 first = false;
743 indent(out) << "[ms appendString: @\"" << (*f_iter)->get_name() << ":\"];" << endl;
744 } else {
745 indent(out) << "[ms appendString: @\"," << (*f_iter)->get_name() << ":\"];" << endl;
747 t_type* ttype = (*f_iter)->get_type();
748 indent(out) << "[ms appendFormat: @\"" << format_string_for_type(ttype) << "\", __" <<
749 (*f_iter)->get_name() << "];" << endl;
751 out <<
752 indent() << "[ms appendString: @\")\"];" << endl <<
753 indent() << "return [ms copy];" << endl;
755 indent_down();
756 indent(out) << "}" << endl <<
757 endl;
762 * Generates a thrift service. In Objective-C this consists of a
763 * protocol definition, a client interface and a client implementation.
765 * @param tservice The service definition
767 void t_cocoa_generator::generate_service(t_service* tservice) {
768 generate_cocoa_service_protocol(f_header_, tservice);
769 generate_cocoa_service_client_interface(f_header_, tservice);
770 generate_cocoa_service_helpers(tservice);
771 generate_cocoa_service_client_implementation(f_impl_, tservice);
776 * Generates structs for all the service return types
778 * @param tservice The service
780 void t_cocoa_generator::generate_cocoa_service_helpers(t_service* tservice) {
781 vector<t_function*> functions = tservice->get_functions();
782 vector<t_function*>::iterator f_iter;
783 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
784 generate_function_helpers(*f_iter);
788 string t_cocoa_generator::function_result_helper_struct_type(t_function* tfunction) {
789 return capitalize(tfunction->get_name()) + "Result_";
794 * Generates a struct and helpers for a function.
796 * @param tfunction The function
798 void t_cocoa_generator::generate_function_helpers(t_function* tfunction) {
799 if (tfunction->is_async()) {
800 return;
803 // create a result struct with a success field of the return type,
804 // and a field for each type of exception thrown
805 t_struct result(program_, function_result_helper_struct_type(tfunction));
806 t_field success(tfunction->get_returntype(), "success", 0);
807 if (!tfunction->get_returntype()->is_void()) {
808 result.append(&success);
811 t_struct* xs = tfunction->get_xceptions();
812 const vector<t_field*>& fields = xs->get_members();
813 vector<t_field*>::const_iterator f_iter;
814 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
815 result.append(*f_iter);
818 // generate the result struct
819 generate_cocoa_struct_interface(f_impl_, &result, false);
820 generate_cocoa_struct_implementation(f_impl_, &result, false, true);
824 * Generates a service protocol definition.
826 * @param tservice The service to generate a protocol definition for
828 void t_cocoa_generator::generate_cocoa_service_protocol(ofstream& out,
829 t_service* tservice) {
830 out << "@protocol " << cocoa_prefix_ << tservice->get_name() << " <NSObject>" << endl;
832 vector<t_function*> functions = tservice->get_functions();
833 vector<t_function*>::iterator f_iter;
834 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
835 out << "- " << function_signature(*f_iter) << ";" <<
836 " // throws ";
837 t_struct* xs = (*f_iter)->get_xceptions();
838 const std::vector<t_field*>& xceptions = xs->get_members();
839 vector<t_field*>::const_iterator x_iter;
840 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
841 out << type_name((*x_iter)->get_type()) + ", ";
843 out << "TException" << endl;
845 out << "@end" << endl << endl;
850 * Generates a service client interface definition.
852 * @param tservice The service to generate a client interface definition for
854 void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out,
855 t_service* tservice) {
856 out << "@interface " << cocoa_prefix_ << tservice->get_name() << "Client : NSObject <" <<
857 cocoa_prefix_ << tservice->get_name() << "> ";
859 scope_up(out);
860 out << indent() << "id <TProtocol> inProtocol;" << endl;
861 out << indent() << "id <TProtocol> outProtocol;" << endl;
862 scope_down(out);
864 out << "- (id) initWithProtocol: (id <TProtocol>) protocol;" << endl;
865 out << "- (id) initWithInProtocol: (id <TProtocol>) inProtocol outProtocol: (id <TProtocol>) outProtocol;" << endl;
866 out << "@end" << endl << endl;
871 * Generates a service client implementation.
873 * @param tservice The service to generate an implementation for
875 void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& out,
876 t_service* tservice) {
877 out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "Client" << endl;
879 // initializers
880 out << "- (id) initWithProtocol: (id <TProtocol>) protocol" << endl;
881 scope_up(out);
882 out << indent() << "return [self initWithInProtocol: protocol outProtocol: protocol];" << endl;
883 scope_down(out);
884 out << endl;
886 out << "- (id) initWithInProtocol: (id <TProtocol>) anInProtocol outProtocol: (id <TProtocol>) anOutProtocol" << endl;
887 scope_up(out);
888 out << indent() << "[super init];" << endl;
889 out << indent() << "inProtocol = [anInProtocol retain];" << endl;
890 out << indent() << "outProtocol = [anOutProtocol retain];" << endl;
891 out << indent() << "return self;" << endl;
892 scope_down(out);
893 out << endl;
895 // dealloc
896 out << "- (void) dealloc" << endl;
897 scope_up(out);
898 out << indent() << "[inProtocol release];" << endl;
899 out << indent() << "[outProtocol release];" << endl;
900 out << indent() << "[super dealloc];" << endl;
901 scope_down(out);
902 out << endl;
904 // generate client method implementations
905 vector<t_function*> functions = tservice->get_functions();
906 vector<t_function*>::const_iterator f_iter;
907 for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
908 string funname = (*f_iter)->get_name();
910 t_function send_function(g_type_void,
911 string("send_") + (*f_iter)->get_name(),
912 (*f_iter)->get_arglist());
914 string argsname = (*f_iter)->get_name() + "_args";
916 // Open function
917 indent(out) <<
918 "- " << function_signature(&send_function) << endl;
919 scope_up(out);
921 // Serialize the request
922 out <<
923 indent() << "[outProtocol writeMessageBeginWithName: @\"" << funname << "\"" <<
924 " type: TMessageType_CALL" <<
925 " sequenceID: 0];" << endl;
927 out <<
928 indent() << "[outProtocol writeStructBeginWithName: @\"" << argsname << "\"];" << endl;
930 // write out function parameters
931 t_struct* arg_struct = (*f_iter)->get_arglist();
932 const vector<t_field*>& fields = arg_struct->get_members();
933 vector<t_field*>::const_iterator fld_iter;
934 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
935 string fieldName = (*fld_iter)->get_name();
936 if (type_can_be_null((*fld_iter)->get_type())) {
937 out << indent() << "if (" << fieldName << " != nil)";
938 scope_up(out);
940 out <<
941 indent() << "[outProtocol writeFieldBeginWithName: @\"" << fieldName << "\""
942 " type: " << type_to_enum((*fld_iter)->get_type()) <<
943 " fieldID: " << (*fld_iter)->get_key() << "];" << endl;
945 generate_serialize_field(out, *fld_iter, fieldName);
947 out <<
948 indent() << "[outProtocol writeFieldEnd];" << endl;
950 if (type_can_be_null((*fld_iter)->get_type())) {
951 scope_down(out);
955 out <<
956 indent() << "[outProtocol writeFieldStop];" << endl;
957 out <<
958 indent() << "[outProtocol writeStructEnd];" << endl;
960 out <<
961 indent() << "[outProtocol writeMessageEnd];" << endl <<
962 indent() << "[[outProtocol transport] flush];" << endl;
964 scope_down(out);
965 out << endl;
967 if (!(*f_iter)->is_async()) {
968 t_struct noargs(program_);
969 t_function recv_function((*f_iter)->get_returntype(),
970 string("recv_") + (*f_iter)->get_name(),
971 &noargs,
972 (*f_iter)->get_xceptions());
973 // Open function
974 indent(out) <<
975 "- " << function_signature(&recv_function) << endl;
976 scope_up(out);
978 // TODO(mcslee): Message validation here, was the seqid etc ok?
980 // check for an exception
981 out <<
982 indent() << "int msgType = 0;" << endl <<
983 indent() << "[inProtocol readMessageBeginReturningName: nil type: &msgType sequenceID: NULL];" << endl <<
984 indent() << "if (msgType == TMessageType_EXCEPTION) {" << endl <<
985 indent() << " TApplicationException * x = [TApplicationException read: inProtocol];" << endl <<
986 indent() << " [inProtocol readMessageEnd];" << endl <<
987 indent() << " @throw x;" << endl <<
988 indent() << "}" << endl;
990 // FIXME - could optimize here to reduce creation of temporary objects.
991 string resultname = function_result_helper_struct_type(*f_iter);
992 out <<
993 indent() << cocoa_prefix_ << resultname << " * result = [[[" << cocoa_prefix_ <<
994 resultname << " alloc] init] autorelease];" << endl;
995 indent(out) << "[result read: inProtocol];" << endl;
996 indent(out) << "[inProtocol readMessageEnd];" << endl;
998 // Careful, only return _result if not a void function
999 if (!(*f_iter)->get_returntype()->is_void()) {
1000 out <<
1001 indent() << "if ([result successIsSet]) {" << endl <<
1002 indent() << " return [result success];" << endl <<
1003 indent() << "}" << endl;
1006 t_struct* xs = (*f_iter)->get_xceptions();
1007 const std::vector<t_field*>& xceptions = xs->get_members();
1008 vector<t_field*>::const_iterator x_iter;
1009 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
1010 out <<
1011 indent() << "if ([result " << (*x_iter)->get_name() << "IsSet]) {" << endl <<
1012 indent() << " @throw [result " << (*x_iter)->get_name() << "];" << endl <<
1013 indent() << "}" << endl;
1016 // If you get here it's an exception, unless a void function
1017 if ((*f_iter)->get_returntype()->is_void()) {
1018 indent(out) <<
1019 "return;" << endl;
1020 } else {
1021 out <<
1022 indent() << "@throw [TApplicationException exceptionWithType: TApplicationException_MISSING_RESULT" << endl <<
1023 indent() << " reason: @\"" << (*f_iter)->get_name() << " failed: unknown result\"];" << endl;
1026 // Close function
1027 scope_down(out);
1028 out << endl;
1031 // Open function
1032 indent(out) <<
1033 "- " << function_signature(*f_iter) << endl;
1034 scope_up(out);
1035 indent(out) <<
1036 "[self send_" << funname;
1038 // Declare the function arguments
1039 bool first = true;
1040 for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
1041 if (first) {
1042 first = false;
1043 } else {
1044 out << " ";
1046 out << ": " << (*fld_iter)->get_name();
1048 out << "];" << endl;
1050 if (!(*f_iter)->is_async()) {
1051 out << indent();
1052 if (!(*f_iter)->get_returntype()->is_void()) {
1053 out << "return ";
1055 out <<
1056 "[self recv_" << funname << "];" << endl;
1058 scope_down(out);
1059 out << endl;
1062 indent_down();
1064 out << "@end" << endl << endl;
1069 * Deserializes a field of any type.
1071 * @param tfield The field
1072 * @param fieldName The variable name for this field
1074 void t_cocoa_generator::generate_deserialize_field(ofstream& out,
1075 t_field* tfield,
1076 string fieldName) {
1077 t_type* type = get_true_type(tfield->get_type());
1079 if (type->is_void()) {
1080 throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " +
1081 tfield->get_name();
1084 if (type->is_struct() || type->is_xception()) {
1085 generate_deserialize_struct(out,
1086 (t_struct*)type,
1087 fieldName);
1088 } else if (type->is_container()) {
1089 generate_deserialize_container(out, type, fieldName);
1090 } else if (type->is_base_type() || type->is_enum()) {
1091 indent(out) <<
1092 type_name(type) << " " << fieldName << " = [inProtocol ";
1094 if (type->is_base_type()) {
1095 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1096 switch (tbase) {
1097 case t_base_type::TYPE_VOID:
1098 throw "compiler error: cannot serialize void field in a struct: " +
1099 tfield->get_name();
1100 break;
1101 case t_base_type::TYPE_STRING:
1102 if (((t_base_type*)type)->is_binary()) {
1103 out << "readBinary];";
1104 } else {
1105 out << "readString];";
1107 break;
1108 case t_base_type::TYPE_BOOL:
1109 out << "readBool];";
1110 break;
1111 case t_base_type::TYPE_BYTE:
1112 out << "readByte];";
1113 break;
1114 case t_base_type::TYPE_I16:
1115 out << "readI16];";
1116 break;
1117 case t_base_type::TYPE_I32:
1118 out << "readI32];";
1119 break;
1120 case t_base_type::TYPE_I64:
1121 out << "readI64];";
1122 break;
1123 case t_base_type::TYPE_DOUBLE:
1124 out << "readDouble];";
1125 break;
1126 default:
1127 throw "compiler error: no Objective-C name for base type " + t_base_type::t_base_name(tbase);
1129 } else if (type->is_enum()) {
1130 out << "readI32];";
1132 out <<
1133 endl;
1134 } else {
1135 printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
1136 tfield->get_name().c_str(), type_name(type).c_str());
1141 * Generates an unserializer for a struct, allocates the struct and invokes read:
1143 void t_cocoa_generator::generate_deserialize_struct(ofstream& out,
1144 t_struct* tstruct,
1145 string fieldName) {
1146 indent(out) << type_name(tstruct) << fieldName << " = [[" <<
1147 type_name(tstruct, true) << " alloc] init];" << endl;
1148 indent(out) << "[" << fieldName << " read: inProtocol];" << endl;
1152 * Deserializes a container by reading its size and then iterating
1154 void t_cocoa_generator::generate_deserialize_container(ofstream& out,
1155 t_type* ttype,
1156 string fieldName) {
1157 string size = tmp("_size");
1158 indent(out) << "int " << size << ";" << endl;
1160 // Declare variables, read header
1161 if (ttype->is_map()) {
1162 indent(out)
1163 << "[inProtocol readMapBeginReturningKeyType: NULL valueType: NULL size: &" <<
1164 size << "];" << endl;
1165 indent(out) << "NSMutableDictionary * " << fieldName <<
1166 " = [[NSMutableDictionary alloc] initWithCapacity: " << size << "];" << endl;
1167 } else if (ttype->is_set()) {
1168 indent(out)
1169 << "[inProtocol readSetBeginReturningElementType: NULL size: &" << size << "];" << endl;
1170 indent(out) << "NSMutableSet * " << fieldName <<
1171 " = [[NSMutableSet alloc] initWithCapacity: " << size << "];" << endl;
1172 } else if (ttype->is_list()) {
1173 indent(out)
1174 << "[inProtocol readListBeginReturningElementType: NULL size: &" << size << "];" << endl;
1175 indent(out) << "NSMutableArray * " << fieldName <<
1176 " = [[NSMutableArray alloc] initWithCapacity: " << size << "];" << endl;
1178 // FIXME - the code above does not verify that the element types of
1179 // the containers being read match the element types of the
1180 // containers we are reading into. Does that matter?
1182 // For loop iterates over elements
1183 string i = tmp("_i");
1184 indent(out) << "int " << i << ";" << endl <<
1185 indent() << "for (" << i << " = 0; " <<
1186 i << " < " << size << "; " <<
1187 "++" << i << ")" << endl;
1189 scope_up(out);
1191 if (ttype->is_map()) {
1192 generate_deserialize_map_element(out, (t_map*)ttype, fieldName);
1193 } else if (ttype->is_set()) {
1194 generate_deserialize_set_element(out, (t_set*)ttype, fieldName);
1195 } else if (ttype->is_list()) {
1196 generate_deserialize_list_element(out, (t_list*)ttype, fieldName);
1199 scope_down(out);
1201 // Read container end
1202 if (ttype->is_map()) {
1203 indent(out) << "[inProtocol readMapEnd];" << endl;
1204 } else if (ttype->is_set()) {
1205 indent(out) << "[inProtocol readSetEnd];" << endl;
1206 } else if (ttype->is_list()) {
1207 indent(out) << "[inProtocol readListEnd];" << endl;
1214 * Take a variable of a given type and wrap it in code to make it
1215 * suitable for putting into a container, if necessary. Basically,
1216 * wrap scaler primitives in NSNumber objects.
1218 string t_cocoa_generator::containerize(t_type * ttype,
1219 string fieldName)
1221 // FIXME - optimize here to avoid autorelease pool?
1222 ttype = get_true_type(ttype);
1223 if (ttype->is_enum()) {
1224 return "[NSNumber numberWithInt: " + fieldName + "]";
1225 } else if (ttype->is_base_type()) {
1226 t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base();
1227 switch (tbase) {
1228 case t_base_type::TYPE_VOID:
1229 throw "can't containerize void";
1230 case t_base_type::TYPE_BOOL:
1231 return "[NSNumber numberWithBool: " + fieldName + "]";
1232 case t_base_type::TYPE_BYTE:
1233 return "[NSNumber numberWithUnsignedChar: " + fieldName + "]";
1234 case t_base_type::TYPE_I16:
1235 return "[NSNumber numberWithShort: " + fieldName + "]";
1236 case t_base_type::TYPE_I32:
1237 return "[NSNumber numberWithLong: " + fieldName + "]";
1238 case t_base_type::TYPE_I64:
1239 return "[NSNumber numberWithLongLong: " + fieldName + "]";
1240 case t_base_type::TYPE_DOUBLE:
1241 return "[NSNumber numberWithDouble: " + fieldName + "]";
1242 default:
1243 break;
1247 // do nothing
1248 return fieldName;
1253 * Generates code to deserialize a map element
1255 void t_cocoa_generator::generate_deserialize_map_element(ofstream& out,
1256 t_map* tmap,
1257 string fieldName) {
1258 string key = tmp("_key");
1259 string val = tmp("_val");
1260 t_field fkey(tmap->get_key_type(), key);
1261 t_field fval(tmap->get_val_type(), val);
1263 generate_deserialize_field(out, &fkey, key);
1264 generate_deserialize_field(out, &fval, val);
1266 indent(out) <<
1267 "[" << fieldName << " setObject: " << containerize(fval.get_type(), val) <<
1268 " forKey: " << containerize(fkey.get_type(), key) << "];" << endl;
1272 * Deserializes a set element
1274 void t_cocoa_generator::generate_deserialize_set_element(ofstream& out,
1275 t_set* tset,
1276 string fieldName) {
1277 string elem = tmp("_elem");
1278 t_field felem(tset->get_elem_type(), elem);
1280 generate_deserialize_field(out, &felem, elem);
1282 indent(out) <<
1283 "[" << fieldName << " addObject: " << containerize(felem.get_type(), elem) << "];" << endl;
1287 * Deserializes a list element
1289 void t_cocoa_generator::generate_deserialize_list_element(ofstream& out,
1290 t_list* tlist,
1291 string fieldName) {
1292 string elem = tmp("_elem");
1293 t_field felem(tlist->get_elem_type(), elem);
1295 generate_deserialize_field(out, &felem, elem);
1297 indent(out) <<
1298 "[" << fieldName << " addObject: " << containerize(felem.get_type(), elem) << "];" << endl;
1303 * Serializes a field of any type.
1305 * @param tfield The field to serialize
1306 * @param fieldName Name to of the variable holding the field
1308 void t_cocoa_generator::generate_serialize_field(ofstream& out,
1309 t_field* tfield,
1310 string fieldName) {
1311 t_type* type = get_true_type(tfield->get_type());
1313 // Do nothing for void types
1314 if (type->is_void()) {
1315 throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
1316 tfield->get_name();
1319 if (type->is_struct() || type->is_xception()) {
1320 generate_serialize_struct(out,
1321 (t_struct*)type,
1322 fieldName);
1323 } else if (type->is_container()) {
1324 generate_serialize_container(out,
1325 type,
1326 fieldName);
1327 } else if (type->is_base_type() || type->is_enum()) {
1328 indent(out) <<
1329 "[outProtocol ";
1331 if (type->is_base_type()) {
1332 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1333 switch (tbase) {
1334 case t_base_type::TYPE_VOID:
1335 throw
1336 "compiler error: cannot serialize void field in a struct: " + fieldName;
1337 break;
1338 case t_base_type::TYPE_STRING:
1339 if (((t_base_type*)type)->is_binary()) {
1340 out << "writeBinary: " << fieldName << "];";
1341 } else {
1342 out << "writeString: " << fieldName << "];";
1344 break;
1345 case t_base_type::TYPE_BOOL:
1346 out << "writeBool: " << fieldName << "];";
1347 break;
1348 case t_base_type::TYPE_BYTE:
1349 out << "writeByte: " << fieldName << "];";
1350 break;
1351 case t_base_type::TYPE_I16:
1352 out << "writeI16: " << fieldName << "];";
1353 break;
1354 case t_base_type::TYPE_I32:
1355 out << "writeI32: " << fieldName << "];";
1356 break;
1357 case t_base_type::TYPE_I64:
1358 out << "writeI64: " << fieldName << "];";
1359 break;
1360 case t_base_type::TYPE_DOUBLE:
1361 out << "writeDouble: " << fieldName << "];";
1362 break;
1363 default:
1364 throw "compiler error: no Java name for base type " + t_base_type::t_base_name(tbase);
1366 } else if (type->is_enum()) {
1367 out << "writeI32: " << fieldName << "];";
1369 out << endl;
1370 } else {
1371 printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
1372 tfield->get_name().c_str(),
1373 type_name(type).c_str());
1378 * Serialize a struct.
1380 * @param tstruct The struct to serialize
1381 * @param fieldName Name of variable holding struct
1383 void t_cocoa_generator::generate_serialize_struct(ofstream& out,
1384 t_struct* tstruct,
1385 string fieldName) {
1386 out <<
1387 indent() << "[" << fieldName << " write: outProtocol];" << endl;
1391 * Serializes a container by writing its size then the elements.
1393 * @param ttype The type of container
1394 * @param fieldName Name of variable holding container
1396 void t_cocoa_generator::generate_serialize_container(ofstream& out,
1397 t_type* ttype,
1398 string fieldName) {
1399 scope_up(out);
1401 if (ttype->is_map()) {
1402 indent(out) <<
1403 "[outProtocol writeMapBeginWithKeyType: " <<
1404 type_to_enum(((t_map*)ttype)->get_key_type()) << " valueType: " <<
1405 type_to_enum(((t_map*)ttype)->get_val_type()) << " size: [" <<
1406 fieldName << " count]];" << endl;
1407 } else if (ttype->is_set()) {
1408 indent(out) <<
1409 "[outProtocol writeSetBeginWithElementType: " <<
1410 type_to_enum(((t_set*)ttype)->get_elem_type()) << " size: [" <<
1411 fieldName << " count]];" << endl;
1412 } else if (ttype->is_list()) {
1413 indent(out) <<
1414 "[outProtocol writeListBeginWithElementType: " <<
1415 type_to_enum(((t_list*)ttype)->get_elem_type()) << " size: [" <<
1416 fieldName << " count]];" << endl;
1419 string iter = tmp("_iter");
1420 string key;
1421 if (ttype->is_map()) {
1422 key = tmp("key");
1423 indent(out) << "NSEnumerator * " << iter << " = [" << fieldName << " keyEnumerator];" << endl;
1424 indent(out) << "id " << key << ";" << endl;
1425 indent(out) << "while ((" << key << " = [" << iter << " nextObject]))" << endl;
1426 } else if (ttype->is_set()) {
1427 key = tmp("obj");
1428 indent(out) << "NSEnumerator * " << iter << " = [" << fieldName << " objectEnumerator];" << endl;
1429 indent(out) << "id " << key << ";" << endl;
1430 indent(out) << "while ((" << key << " = [" << iter << " nextObject]))" << endl;
1431 } else if (ttype->is_list()) {
1432 key = tmp("i");
1433 indent(out) << "int " << key << ";" << endl;
1434 indent(out) <<
1435 "for (" << key << " = 0; " << key << " < [" << fieldName << " count]; " << key << "++)" << endl;
1438 scope_up(out);
1440 if (ttype->is_map()) {
1441 generate_serialize_map_element(out, (t_map*)ttype, key, fieldName);
1442 } else if (ttype->is_set()) {
1443 generate_serialize_set_element(out, (t_set*)ttype, key);
1444 } else if (ttype->is_list()) {
1445 generate_serialize_list_element(out, (t_list*)ttype, key, fieldName);
1448 scope_down(out);
1450 if (ttype->is_map()) {
1451 indent(out) <<
1452 "[outProtocol writeMapEnd];" << endl;
1453 } else if (ttype->is_set()) {
1454 indent(out) <<
1455 "[outProtocol writeSetEnd];" << endl;
1456 } else if (ttype->is_list()) {
1457 indent(out) <<
1458 "[outProtocol writeListEnd];" << endl;
1461 scope_down(out);
1465 * Given a field variable name, wrap it in code that converts it to a
1466 * primitive type, if necessary.
1468 string t_cocoa_generator::decontainerize(t_field * tfield,
1469 string fieldName)
1471 t_type * ttype = get_true_type(tfield->get_type());
1472 if (ttype->is_enum()) {
1473 return "[" + fieldName + " intValue]";
1474 } else if (ttype->is_base_type()) {
1475 t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base();
1476 switch (tbase) {
1477 case t_base_type::TYPE_VOID:
1478 throw "can't decontainerize void";
1479 case t_base_type::TYPE_BOOL:
1480 return "[" + fieldName + " boolValue]";
1481 case t_base_type::TYPE_BYTE:
1482 return "[" + fieldName + " unsignedCharValue]";
1483 case t_base_type::TYPE_I16:
1484 return "[" + fieldName + " shortValue]";
1485 case t_base_type::TYPE_I32:
1486 return "[" + fieldName + " longValue]";
1487 case t_base_type::TYPE_I64:
1488 return "[" + fieldName + " longLongValue]";
1489 case t_base_type::TYPE_DOUBLE:
1490 return "[" + fieldName + " doubleValue]";
1491 default:
1492 break;
1496 // do nothing
1497 return fieldName;
1502 * Serializes the members of a map.
1504 void t_cocoa_generator::generate_serialize_map_element(ofstream& out,
1505 t_map* tmap,
1506 string key,
1507 string mapName) {
1508 t_field kfield(tmap->get_key_type(), key);
1509 generate_serialize_field(out, &kfield, decontainerize(&kfield, key));
1510 t_field vfield(tmap->get_val_type(), "[" + mapName + " objectForKey: " + key + "]");
1511 generate_serialize_field(out, &vfield, decontainerize(&vfield, vfield.get_name()));
1515 * Serializes the members of a set.
1517 void t_cocoa_generator::generate_serialize_set_element(ofstream& out,
1518 t_set* tset,
1519 string elementName) {
1520 t_field efield(tset->get_elem_type(), elementName);
1521 generate_serialize_field(out, &efield, decontainerize(&efield, elementName));
1525 * Serializes the members of a list.
1527 void t_cocoa_generator::generate_serialize_list_element(ofstream& out,
1528 t_list* tlist,
1529 string index,
1530 string listName) {
1531 t_field efield(tlist->get_elem_type(), "[" + listName + " objectAtIndex: " + index + "]");
1532 generate_serialize_field(out, &efield, decontainerize(&efield, efield.get_name()));
1537 * Returns an Objective-C name
1539 * @param ttype The type
1540 * @param class_ref Do we want a Class reference istead of a type reference?
1541 * @return Java type name, i.e. HashMap<Key,Value>
1543 string t_cocoa_generator::type_name(t_type* ttype, bool class_ref) {
1544 if (ttype->is_typedef()) {
1545 return cocoa_prefix_ + ttype->get_name();
1548 string result;
1549 if (ttype->is_base_type()) {
1550 return base_type_name((t_base_type*)ttype);
1551 } else if (ttype->is_enum()) {
1552 return "int";
1553 } else if (ttype->is_map()) {
1554 result = "NSDictionary";
1555 } else if (ttype->is_set()) {
1556 result = "NSSet";
1557 } else if (ttype->is_list()) {
1558 result = "NSArray";
1559 } else {
1560 // Check for prefix
1561 t_program* program = ttype->get_program();
1562 if (program != NULL) {
1563 result = program->get_cocoa_prefix() + ttype->get_name();
1564 } else {
1565 result = ttype->get_name();
1569 if (!class_ref) {
1570 result += " *";
1572 return result;
1576 * Returns the Objective-C type that corresponds to the thrift type.
1578 * @param tbase The base type
1580 string t_cocoa_generator::base_type_name(t_base_type* type) {
1581 t_base_type::t_base tbase = type->get_base();
1583 switch (tbase) {
1584 case t_base_type::TYPE_VOID:
1585 return "void";
1586 case t_base_type::TYPE_STRING:
1587 if (type->is_binary()) {
1588 return "NSData *";
1589 } else {
1590 return "NSString *";
1592 case t_base_type::TYPE_BOOL:
1593 return "BOOL";
1594 case t_base_type::TYPE_BYTE:
1595 return "uint8_t";
1596 case t_base_type::TYPE_I16:
1597 return"int16_t";
1598 case t_base_type::TYPE_I32:
1599 return "int32_t";
1600 case t_base_type::TYPE_I64:
1601 return"int64_t";
1602 case t_base_type::TYPE_DOUBLE:
1603 return "double";
1604 default:
1605 throw "compiler error: no objective-c name for base type " + t_base_type::t_base_name(tbase);
1611 * Spit out code that evaluates to the specified constant value.
1613 string t_cocoa_generator::render_const_value(string name,
1614 t_type* type,
1615 t_const_value* value,
1616 bool containerize_it) {
1617 std::ostringstream render;
1619 if (type->is_base_type()) {
1620 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1621 switch (tbase) {
1622 case t_base_type::TYPE_STRING:
1623 render << "@\"" + value->get_string() + "\"";
1624 break;
1625 case t_base_type::TYPE_BOOL:
1626 render << ((value->get_integer() > 0) ? "YES" : "NO");
1627 break;
1628 case t_base_type::TYPE_BYTE:
1629 case t_base_type::TYPE_I16:
1630 case t_base_type::TYPE_I32:
1631 case t_base_type::TYPE_I64:
1632 render << value->get_integer();
1633 break;
1634 case t_base_type::TYPE_DOUBLE:
1635 if (value->get_type() == t_const_value::CV_INTEGER) {
1636 render << value->get_integer();
1637 } else {
1638 render << value->get_double();
1640 break;
1641 default:
1642 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
1644 } else if (type->is_enum()) {
1645 render << value->get_integer();
1646 } else if (type->is_struct() || type->is_xception()) {
1647 render << "[[" << type_name(type, true) << " alloc] initWith";
1648 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
1649 vector<t_field*>::const_iterator f_iter;
1650 const map<t_const_value*, t_const_value*>& val = value->get_map();
1651 map<t_const_value*, t_const_value*>::const_iterator v_iter;
1652 bool first = true;
1653 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
1654 t_type* field_type = NULL;
1655 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1656 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
1657 field_type = (*f_iter)->get_type();
1660 if (field_type == NULL) {
1661 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
1663 if (first) {
1664 render << capitalize(v_iter->first->get_string());
1665 first = false;
1666 } else {
1667 render << " " << v_iter->first->get_string();
1669 render << ": " << render_const_value(name, field_type, v_iter->second);
1671 render << "]";
1672 } else if (type->is_map()) {
1673 render << "[[NSDictionary alloc] initWithObjectsAndKeys: ";
1674 t_type* ktype = ((t_map*)type)->get_key_type();
1675 t_type* vtype = ((t_map*)type)->get_val_type();
1676 const map<t_const_value*, t_const_value*>& val = value->get_map();
1677 map<t_const_value*, t_const_value*>::const_iterator v_iter;
1678 bool first = true;
1679 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
1680 string key = render_const_value(name, ktype, v_iter->first, true);
1681 string val = render_const_value(name, vtype, v_iter->second, true);
1682 if (first) {
1683 first = false;
1684 } else {
1685 render << ", ";
1687 render << val << ", " << key;
1689 render << ", nil]";
1690 } else if (type->is_list()) {
1691 render << "[[NSArray alloc] initWithObjects: ";
1692 t_type * etype = ((t_list*)type)->get_elem_type();
1693 const vector<t_const_value*>& val = value->get_list();
1694 bool first = true;
1695 vector<t_const_value*>::const_iterator v_iter;
1696 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
1697 if (first) {
1698 first = false;
1699 } else {
1700 render << ", ";
1702 render << render_const_value(name, etype, *v_iter, true);
1704 render << ", nil]";
1705 } else if (type->is_set()) {
1706 render << "[[NSSet alloc] initWithObjects: ";
1707 t_type * etype = ((t_set*)type)->get_elem_type();
1708 const vector<t_const_value*>& val = value->get_list();
1709 bool first = true;
1710 vector<t_const_value*>::const_iterator v_iter;
1711 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
1712 if (first) {
1713 first = false;
1714 } else {
1715 render << ", ";
1717 render << render_const_value(name, etype, *v_iter, true);
1719 render << ", nil]";
1720 } else {
1721 throw "don't know how to render constant for type: " + type->get_name();
1724 if (containerize_it) {
1725 return containerize(type, render.str());
1728 return render.str();
1733 * Declares a field.
1735 * @param ttype The type
1737 string t_cocoa_generator::declare_field(t_field* tfield) {
1738 return type_name(tfield->get_type()) + " __" + tfield->get_name() + ";";
1742 * Renders a function signature
1744 * @param tfunction Function definition
1745 * @return String of rendered function definition
1747 string t_cocoa_generator::function_signature(t_function* tfunction) {
1748 t_type* ttype = tfunction->get_returntype();
1749 std::string result =
1750 "(" + type_name(ttype) + ") " + tfunction->get_name() + argument_list(tfunction->get_arglist());
1751 return result;
1756 * Renders a colon separated list of types and names, suitable for an
1757 * objective-c parameter list
1759 string t_cocoa_generator::argument_list(t_struct* tstruct) {
1760 string result = "";
1762 const vector<t_field*>& fields = tstruct->get_members();
1763 vector<t_field*>::const_iterator f_iter;
1764 bool first = true;
1765 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1766 if (first) {
1767 first = false;
1768 } else {
1769 result += " ";
1771 result += ": (" + type_name((*f_iter)->get_type()) + ") " + (*f_iter)->get_name();
1773 return result;
1778 * Converts the parse type to an Objective-C enum string for the given type.
1780 string t_cocoa_generator::type_to_enum(t_type* type) {
1781 type = get_true_type(type);
1783 if (type->is_base_type()) {
1784 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1785 switch (tbase) {
1786 case t_base_type::TYPE_VOID:
1787 throw "NO T_VOID CONSTRUCT";
1788 case t_base_type::TYPE_STRING:
1789 return "TType_STRING";
1790 case t_base_type::TYPE_BOOL:
1791 return "TType_BOOL";
1792 case t_base_type::TYPE_BYTE:
1793 return "TType_BYTE";
1794 case t_base_type::TYPE_I16:
1795 return "TType_I16";
1796 case t_base_type::TYPE_I32:
1797 return "TType_I32";
1798 case t_base_type::TYPE_I64:
1799 return "TType_I64";
1800 case t_base_type::TYPE_DOUBLE:
1801 return "TType_DOUBLE";
1803 } else if (type->is_enum()) {
1804 return "TType_I32";
1805 } else if (type->is_struct() || type->is_xception()) {
1806 return "TType_STRUCT";
1807 } else if (type->is_map()) {
1808 return "TType_MAP";
1809 } else if (type->is_set()) {
1810 return "TType_SET";
1811 } else if (type->is_list()) {
1812 return "TType_LIST";
1815 throw "INVALID TYPE IN type_to_enum: " + type->get_name();
1820 * Returns a format string specifier for the supplied parse type.
1822 string t_cocoa_generator::format_string_for_type(t_type* type) {
1823 type = get_true_type(type);
1825 if (type->is_base_type()) {
1826 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1827 switch (tbase) {
1828 case t_base_type::TYPE_VOID:
1829 throw "NO T_VOID CONSTRUCT";
1830 case t_base_type::TYPE_STRING:
1831 return "\\\"%@\\\"";
1832 case t_base_type::TYPE_BOOL:
1833 return "%i";
1834 case t_base_type::TYPE_BYTE:
1835 return "%i";
1836 case t_base_type::TYPE_I16:
1837 return "%hi";
1838 case t_base_type::TYPE_I32:
1839 return "%i";
1840 case t_base_type::TYPE_I64:
1841 return "%qi";
1842 case t_base_type::TYPE_DOUBLE:
1843 return "%f";
1845 } else if (type->is_enum()) {
1846 return "%i";
1847 } else if (type->is_struct() || type->is_xception()) {
1848 return "%@";
1849 } else if (type->is_map()) {
1850 return "%@";
1851 } else if (type->is_set()) {
1852 return "%@";
1853 } else if (type->is_list()) {
1854 return "%@";
1857 throw "INVALID TYPE IN format_string_for_type: " + type->get_name();
1861 * Generate a call to a field's setter.
1863 * @param tfield Field the setter is being called on
1864 * @param fieldName Name of variable to pass to setter
1867 string t_cocoa_generator::call_field_setter(t_field* tfield, string fieldName) {
1868 return "[self set" + capitalize(tfield->get_name()) + ": " + fieldName + "];";