THRIFT-2905 Cocoa compiler should have option to produce "modern" Objective-C
Client: Cocoa (ObjectiveC & Swift)
Author: Kevin Wooten <kevin@wooten.com>
This closes #539
diff --git a/compiler/cpp/CMakeLists.txt b/compiler/cpp/CMakeLists.txt
index 2d0c3f0..94b3c19 100644
--- a/compiler/cpp/CMakeLists.txt
+++ b/compiler/cpp/CMakeLists.txt
@@ -109,6 +109,7 @@
THRIFT_ADD_COMPILER(php "Enable compiler for PHP" ON)
THRIFT_ADD_COMPILER(erl "Enable compiler for Erlang" ON)
THRIFT_ADD_COMPILER(cocoa "Enable compiler for Cocoa Objective-C" ON)
+THRIFT_ADD_COMPILER(swift "Enable compiler for Cocoa Swift" ON)
THRIFT_ADD_COMPILER(st "Enable compiler for Smalltalk" ON)
THRIFT_ADD_COMPILER(ocaml "Enable compiler for OCaml" ON)
THRIFT_ADD_COMPILER(hs "Enable compiler for Haskell" ON)
diff --git a/compiler/cpp/Makefile.am b/compiler/cpp/Makefile.am
index 2aa6913..427062c 100644
--- a/compiler/cpp/Makefile.am
+++ b/compiler/cpp/Makefile.am
@@ -83,6 +83,7 @@
src/generate/t_php_generator.cc \
src/generate/t_erl_generator.cc \
src/generate/t_cocoa_generator.cc \
+ src/generate/t_swift_generator.cc \
src/generate/t_st_generator.cc \
src/generate/t_ocaml_generator.cc \
src/generate/t_hs_generator.cc \
diff --git a/compiler/cpp/compiler.vcxproj b/compiler/cpp/compiler.vcxproj
index bc1215f..fbd41ad 100644
--- a/compiler/cpp/compiler.vcxproj
+++ b/compiler/cpp/compiler.vcxproj
@@ -78,6 +78,7 @@
<ClCompile Include="src\generate\t_py_generator.cc" />
<ClCompile Include="src\generate\t_rb_generator.cc" />
<ClCompile Include="src\generate\t_st_generator.cc" />
+ <ClCompile Include="src\generate\t_swift_generator.cc" />
<ClCompile Include="src\generate\t_xsd_generator.cc" />
<ClCompile Include="src\main.cc" />
<ClCompile Include="src\md5.c" />
diff --git a/compiler/cpp/compiler.vcxproj.filters b/compiler/cpp/compiler.vcxproj.filters
index 5126019..6e41afb 100644
--- a/compiler/cpp/compiler.vcxproj.filters
+++ b/compiler/cpp/compiler.vcxproj.filters
@@ -165,6 +165,9 @@
<ClCompile Include="src\generate\t_st_generator.cc">
<Filter>generate</Filter>
</ClCompile>
+ <ClCompile Include="src\generate\t_swift_generator.cc">
+ <Filter>generate</Filter>
+ </ClCompile>
<ClCompile Include="src\generate\t_xsd_generator.cc">
<Filter>generate</Filter>
</ClCompile>
diff --git a/compiler/cpp/src/generate/t_cocoa_generator.cc b/compiler/cpp/src/generate/t_cocoa_generator.cc
index a90c937..f8924bb 100644
--- a/compiler/cpp/src/generate/t_cocoa_generator.cc
+++ b/compiler/cpp/src/generate/t_cocoa_generator.cc
@@ -59,7 +59,16 @@
iter = parsed_options.find("async_clients");
async_clients_ = (iter != parsed_options.end());
-
+
+ iter = parsed_options.find("promise_kit");
+ promise_kit_ = (iter != parsed_options.end());
+
+ iter = parsed_options.find("debug_descriptions");
+ debug_descriptions_ = (iter != parsed_options.end());
+
+ iter = parsed_options.find("pods");
+ pods_ = (iter != parsed_options.end());
+
out_dir_base_ = "gen-cocoa";
}
@@ -108,11 +117,13 @@
void generate_cocoa_struct_encode_with_coder_method(ofstream& out,
t_struct* tstruct,
bool is_exception);
+ void generate_cocoa_struct_copy_method(ofstream& out,
+ t_struct* tstruct,
+ bool is_exception);
void generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct);
- void generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct);
- void generate_cocoa_struct_field_accessor_declarations(std::ofstream& out,
- t_struct* tstruct,
- bool is_exception);
+ void generate_cocoa_struct_is_equal_method(ofstream& out,
+ t_struct* tstruct,
+ bool is_exception);
void generate_cocoa_struct_field_accessor_implementations(std::ofstream& out,
t_struct* tstruct,
bool is_exception);
@@ -122,9 +133,9 @@
void generate_cocoa_struct_validator(std::ofstream& out, t_struct* tstruct);
void generate_cocoa_struct_description(std::ofstream& out, t_struct* tstruct);
- std::string function_result_helper_struct_type(t_function* tfunction);
- std::string function_args_helper_struct_type(t_function* tfunction);
- void generate_function_helpers(t_function* tfunction);
+ std::string function_result_helper_struct_type(t_service *tservice, t_function* tfunction);
+ std::string function_args_helper_struct_type(t_service* tservice, t_function* tfunction);
+ void generate_function_helpers(t_service *tservice, t_function* tfunction);
/**
* Service-level generation functions
@@ -137,10 +148,17 @@
void generate_cocoa_service_client_async_interface(std::ofstream& out, t_service* tservice);
void generate_cocoa_service_client_send_function_implementation(ofstream& out,
- t_function* tfunction);
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol);
void generate_cocoa_service_client_send_function_invocation(ofstream& out, t_function* tfunction);
+ void generate_cocoa_service_client_send_async_function_invocation(ofstream& out,
+ t_function* tfunction,
+ string failureBlockName);
void generate_cocoa_service_client_recv_function_implementation(ofstream& out,
- t_function* tfunction);
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol);
void generate_cocoa_service_client_implementation(std::ofstream& out, t_service* tservice);
void generate_cocoa_service_client_async_implementation(std::ofstream& out, t_service* tservice);
@@ -194,18 +212,25 @@
std::string cocoa_prefix();
std::string cocoa_imports();
std::string cocoa_thrift_imports();
- std::string type_name(t_type* ttype, bool class_ref = false);
+ std::string type_name(t_type* ttype, bool class_ref = false, bool needs_mutable = false);
std::string base_type_name(t_base_type* tbase);
- std::string declare_field(t_field* tfield);
std::string declare_property(t_field* tfield);
- std::string function_signature(t_function* tfunction);
- std::string async_function_signature(t_function* tfunction);
- std::string argument_list(t_struct* tstruct);
+ std::string declare_property_isset(t_field* tfield);
+ std::string declare_property_unset(t_field* tfield);
+ std::string invalid_return_statement(t_function* tfunction);
+ std::string function_signature(t_function* tfunction, bool include_error);
+ std::string async_function_signature(t_function* tfunction, bool include_error);
+ std::string promise_function_signature(t_function* tfunction);
+ std::string argument_list(t_struct* tstruct, string protocol_name, bool include_error);
std::string type_to_enum(t_type* ttype);
std::string format_string_for_type(t_type* type);
+ std::string format_cast_for_type(t_type* type);
std::string call_field_setter(t_field* tfield, std::string fieldName);
std::string containerize(t_type* ttype, std::string fieldName);
std::string decontainerize(t_field* tfield, std::string fieldName);
+ std::string decontainerize(t_type* ttype, std::string fieldName);
+ std::string getter_name(string field_name);
+ std::string setter_name(string field_name);
bool type_can_be_null(t_type* ttype) {
ttype = get_true_type(ttype);
@@ -217,6 +242,7 @@
private:
std::string cocoa_prefix_;
std::string constants_declarations_;
+ int error_constant_;
/**
* File streams
@@ -228,6 +254,9 @@
bool log_unexpected_;
bool validate_required_;
bool async_clients_;
+ bool promise_kit_;
+ bool debug_descriptions_;
+ bool pods_;
};
/**
@@ -240,7 +269,7 @@
cocoa_prefix_ = program_->get_namespace("cocoa");
// we have a .h header file...
- string f_header_name = program_name_ + ".h";
+ string f_header_name = cocoa_prefix_ + capitalize(program_name_) + ".h";
string f_header_fullname = get_out_dir() + f_header_name;
f_header_.open(f_header_fullname.c_str());
@@ -249,13 +278,16 @@
f_header_ << cocoa_imports() << cocoa_thrift_imports();
// ...and a .m implementation file
- string f_impl_name = get_out_dir() + program_name_ + ".m";
- f_impl_.open(f_impl_name.c_str());
+ string f_impl_name = cocoa_prefix_ + capitalize(program_name_) + ".m";
+ string f_impl_fullname = get_out_dir() + f_impl_name;
+ f_impl_.open(f_impl_fullname.c_str());
f_impl_ << autogen_comment() << endl;
f_impl_ << cocoa_imports() << cocoa_thrift_imports() << "#import \"" << f_header_name << "\""
<< endl << endl;
+
+ error_constant_ = 60000;
}
/**
@@ -273,25 +305,52 @@
* @return List of imports necessary for thrift runtime
*/
string t_cocoa_generator::cocoa_thrift_imports() {
- string result = string() + "#import \"TProtocol.h\"\n" + "#import \"TApplicationException.h\"\n"
- + "#import \"TProtocolException.h\"\n"
- + "#import \"TProtocolUtil.h\"\n"
- + "#import \"TProcessor.h\"\n"
- + "#import \"TObjective-C.h\"\n"
- + "#import \"TBase.h\"\n"
- + "#import \"TAsyncTransport.h\"\n"
- + "#import \"TProtocolFactory.h\"\n"
- + "#import \"TBaseClient.h\"\n"
- + "\n";
+
+ vector<string> includes_list;
+ includes_list.push_back("TProtocol.h");
+ includes_list.push_back("TProtocolFactory.h");
+ includes_list.push_back("TApplicationError.h");
+ includes_list.push_back("TProtocolError.h");
+ includes_list.push_back("TProtocolUtil.h");
+ includes_list.push_back("TProcessor.h");
+ includes_list.push_back("TBase.h");
+ includes_list.push_back("TAsyncTransport.h");
+ includes_list.push_back("TBaseClient.h");
+
+ std::ostringstream includes;
+
+ vector<string>::const_iterator i_iter;
+ for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+ includes << "#import ";
+ if (pods_) {
+ includes << "<Thrift/" << *i_iter << ">";
+ } else {
+ includes << "\"" << *i_iter << "\"";
+ }
+ includes << endl;
+ }
+
+ includes << endl;
+
+ if (promise_kit_) {
+ includes << "#import ";
+ if (pods_) {
+ includes << "<PromiseKit/PromiseKit.h>";
+ } else {
+ includes << "\"PromiseKit.h\"";
+ }
+ includes << endl;
+ }
// Include other Thrift includes
- const vector<t_program*>& includes = program_->get_includes();
- for (size_t i = 0; i < includes.size(); ++i) {
- result += "#import \"" + includes[i]->get_name() + ".h\"" + "\n";
+ const vector<t_program*>& other_includes = program_->get_includes();
+ for (size_t i = 0; i < other_includes.size(); ++i) {
+ includes << "#import \"" << other_includes[i]->get_name() << ".h\"" << endl;
}
- result += "\n";
+
+ includes << endl;
- return result;
+ return includes.str();
}
/**
@@ -309,20 +368,46 @@
* @param ttypedef The type definition
*/
void t_cocoa_generator::generate_typedef(t_typedef* ttypedef) {
+ if (ttypedef->get_type()->is_map()) {
+ t_map *map = (t_map *)ttypedef->get_type();
+ if (map->get_key_type()->is_struct()) {
+ f_header_ << indent() << "@class " << type_name(map->get_key_type(), true) << ";" << endl;
+ }
+ if (map->get_val_type()->is_struct()) {
+ f_header_ << indent() << "@class " << type_name(map->get_val_type(), true) << ";" << endl;
+ }
+ }
+ else if (ttypedef->get_type()->is_set()) {
+ t_set *set = (t_set *)ttypedef->get_type();
+ if (set->get_elem_type()->is_struct()) {
+ f_header_ << indent() << "@class " << type_name(set->get_elem_type(), true) << ";" << endl;
+ }
+ }
+ else if (ttypedef->get_type()->is_list()) {
+ t_list *list = (t_list *)ttypedef->get_type();
+ if (list->get_elem_type()->is_struct()) {
+ f_header_ << indent() << "@class " << type_name(list->get_elem_type(), true) << ";" << endl;
+ }
+ }
f_header_ << indent() << "typedef " << type_name(ttypedef->get_type()) << " " << cocoa_prefix_
<< ttypedef->get_symbolic() << ";" << endl << endl;
+ if (ttypedef->get_type()->is_container()) {
+ f_header_ << indent() << "typedef " << type_name(ttypedef->get_type(), false, true) << " " << cocoa_prefix_
+ << "Mutable" << ttypedef->get_symbolic() << ";" << endl << endl;
+ }
}
/**
* Generates code for an enumerated type. In Objective-C, this is
- * essentially the same as the thrift definition itself, using the
- * enum keyword in Objective-C. For namespace purposes, the name of
- * the enum plus an underscore is prefixed onto each element.
+ * essentially the same as the thrift definition itself, instead using
+ * NS_ENUM keyword in Objective-C. For namespace purposes, the name of
+ * the enum is prefixed to each element in keeping with Cocoa & Swift
+ * standards.
*
* @param tenum The enumeration
*/
void t_cocoa_generator::generate_enum(t_enum* tenum) {
- f_header_ << indent() << "enum " << cocoa_prefix_ << tenum->get_name() << " {" << endl;
+ f_header_ << indent() << "typedef NS_ENUM(SInt32, " << cocoa_prefix_ << tenum->get_name() << ") {" << endl;
indent_up();
vector<t_enum_value*> constants = tenum->get_constants();
@@ -334,7 +419,7 @@
} else {
f_header_ << "," << endl;
}
- f_header_ << indent() << tenum->get_name() << "_" << (*c_iter)->get_name();
+ f_header_ << indent() << cocoa_prefix_ << tenum->get_name() << (*c_iter)->get_name();
f_header_ << " = " << (*c_iter)->get_value();
}
@@ -343,36 +428,63 @@
}
/**
- * Generates a class that holds all the constants. Primitive values
- * could have been placed outside this class, but I just put
- * everything in for consistency.
+ * Generates a class that holds all the constants.
*/
void t_cocoa_generator::generate_consts(std::vector<t_const*> consts) {
std::ostringstream const_interface;
- string constants_class_name = cocoa_prefix_ + program_name_ + "Constants";
- const_interface << "@interface " << constants_class_name << " : NSObject ";
- scope_up(const_interface);
- scope_down(const_interface);
+ const_interface << "FOUNDATION_EXPORT NSString *" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain;" << endl
+ << endl;
+
- // getter method for each constant defined.
+ bool needs_class = false;
+
+ // Public constants for base types & strings
vector<t_const*>::iterator c_iter;
for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
- string name = (*c_iter)->get_name();
t_type* type = (*c_iter)->get_type();
- const_interface << "+ (" << type_name(type) << ") " << name << ";" << endl;
+ if (!type->is_container() && !type->is_struct()) {
+ const_interface << "FOUNDATION_EXPORT " << type_name(type) << " "
+ << cocoa_prefix_ << capitalize((*c_iter)->get_name()) << ";" << endl;
+ }
+ else {
+ needs_class = true;
+ }
}
+
+
+ string constants_class_name = cocoa_prefix_ + capitalize(program_name_) + "Constants";
- const_interface << "@end";
+ if (needs_class) {
+
+ const_interface << "@interface " << constants_class_name << " : NSObject ";
+ scope_up(const_interface);
+ scope_down(const_interface);
+
+ // getter method for each constant defined.
+ for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+ string name = (*c_iter)->get_name();
+ t_type* type = (*c_iter)->get_type();
+ if (type->is_container() || type->is_struct()) {
+ t_type* type = (*c_iter)->get_type();
+ const_interface << "+ (" << type_name(type) << ") " << name << ";" << endl;
+ }
+ }
+
+ const_interface << "@end";
+ }
// this gets spit into the header file in ::close_generator
constants_declarations_ = const_interface.str();
+
+ f_impl_ << "NSString *" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain = "
+ << "@\"" << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain\";" << endl << endl;
- // static variables in the .m hold all constant values
+ // variables in the .m hold all simple constant values
for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
string name = (*c_iter)->get_name();
t_type* type = (*c_iter)->get_type();
- f_impl_ << "static " << type_name(type) << " " << cocoa_prefix_ << name;
+ f_impl_ << type_name(type) << " " << cocoa_prefix_ << name;
if (!type->is_container() && !type->is_struct()) {
f_impl_ << " = " << render_const_value(f_impl_, type, (*c_iter)->get_value());
}
@@ -380,36 +492,40 @@
}
f_impl_ << endl;
- f_impl_ << "@implementation " << constants_class_name << endl;
+ if (needs_class) {
+ f_impl_ << "@implementation " << constants_class_name << endl;
- // initialize complex constants when the class is loaded
- f_impl_ << "+ (void) initialize ";
- scope_up(f_impl_);
-
- for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
- if ((*c_iter)->get_type()->is_container() || (*c_iter)->get_type()->is_struct()) {
- print_const_value(f_impl_,
- cocoa_prefix_ + (*c_iter)->get_name(),
- (*c_iter)->get_type(),
- (*c_iter)->get_value(),
- false,
- false);
- f_impl_ << ";" << endl;
- }
- }
- scope_down(f_impl_);
-
- // getter method for each constant
- for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
- string name = (*c_iter)->get_name();
- t_type* type = (*c_iter)->get_type();
- f_impl_ << "+ (" << type_name(type) << ") " << name;
+ // initialize complex constants when the class is loaded
+ f_impl_ << "+ (void) initialize ";
scope_up(f_impl_);
- indent(f_impl_) << "return " << cocoa_prefix_ << name << ";" << endl;
- scope_down(f_impl_);
- }
- f_impl_ << "@end" << endl << endl;
+ for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+ if ((*c_iter)->get_type()->is_container() || (*c_iter)->get_type()->is_struct()) {
+ print_const_value(f_impl_,
+ cocoa_prefix_ + (*c_iter)->get_name(),
+ (*c_iter)->get_type(),
+ (*c_iter)->get_value(),
+ false,
+ false);
+ f_impl_ << ";" << endl;
+ }
+ }
+ scope_down(f_impl_);
+
+ // getter method for each constant
+ for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+ string name = (*c_iter)->get_name();
+ t_type* type = (*c_iter)->get_type();
+ if (type->is_container() || type->is_struct()) {
+ f_impl_ << "+ (" << type_name(type) << ") " << name;
+ scope_up(f_impl_);
+ indent(f_impl_) << "return " << cocoa_prefix_ << name << ";" << endl;
+ scope_down(f_impl_);
+ }
+ }
+
+ f_impl_ << "@end" << endl << endl;
+ }
}
/**
@@ -441,51 +557,38 @@
void t_cocoa_generator::generate_cocoa_struct_interface(ofstream& out,
t_struct* tstruct,
bool is_exception) {
+
+ if (is_exception) {
+ out << "enum {" << endl
+ << " " << cocoa_prefix_ << capitalize(program_name_) << "Error" << tstruct->get_name() << " = -" << error_constant_++ << endl
+ << "};" << endl
+ << endl;
+ }
+
out << "@interface " << cocoa_prefix_ << tstruct->get_name() << " : ";
if (is_exception) {
- out << "NSException ";
+ out << "NSError ";
} else {
out << "NSObject ";
}
- out << "<TBase, NSCoding> ";
-
- scope_up(out);
-
- // members are protected. this is redundant, but explicit.
- // f_header_ << endl << "@protected:" << endl;
-
- const vector<t_field*>& members = tstruct->get_members();
-
- // member varialbes
- vector<t_field*>::const_iterator m_iter;
- for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- out << indent() << declare_field(*m_iter) << endl;
- }
-
- if (members.size() > 0) {
- out << endl;
- // isset fields
- for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- indent(out) << "BOOL __" << (*m_iter)->get_name() << "_isset;" << endl;
- }
- }
-
- scope_down(out);
+ out << "<TBase, NSCoding, NSCopying> " << endl;
+
out << endl;
// properties
+ const vector<t_field*>& members = tstruct->get_members();
if (members.size() > 0) {
- out << "#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)"
- << endl;
+ vector<t_field*>::const_iterator m_iter;
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
out << indent() << declare_property(*m_iter) << endl;
+ out << indent() << declare_property_isset(*m_iter) << endl;
+ out << indent() << declare_property_unset(*m_iter) << endl;
+ out << endl;
}
- out << "#endif" << endl << endl;
}
-
- // default initializer
- out << indent() << "- (id) init;" << endl;
+
+ out << endl;
// initializer for all fields
if (!members.empty()) {
@@ -494,17 +597,6 @@
}
out << endl;
- // read and write
- out << "- (void) read: (id <TProtocol>) inProtocol;" << endl;
- out << "- (void) write: (id <TProtocol>) outProtocol;" << endl;
- out << endl;
-
- // validator
- out << "- (void) validate;" << endl << endl;
-
- // getters and setters
- generate_cocoa_struct_field_accessor_declarations(out, tstruct, is_exception);
-
out << "@end" << endl << endl;
}
@@ -516,7 +608,7 @@
t_struct* tstruct) {
const vector<t_field*>& members = tstruct->get_members();
vector<t_field*>::const_iterator m_iter;
- indent(out) << "- (id) initWith";
+ indent(out) << "- (instancetype) initWith";
for (m_iter = members.begin(); m_iter != members.end();) {
if (m_iter == members.begin()) {
out << capitalize((*m_iter)->get_name());
@@ -532,41 +624,25 @@
}
/**
- * Generate getter and setter declarations for all fields, plus an
- * IsSet getter.
- */
-void t_cocoa_generator::generate_cocoa_struct_field_accessor_declarations(ofstream& out,
- t_struct* tstruct,
- bool is_exception) {
- (void)is_exception;
- const vector<t_field*>& members = tstruct->get_members();
- vector<t_field*>::const_iterator m_iter;
- for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- out << indent() << "#if !__has_feature(objc_arc)" << endl;
- out << indent() << "- (" << type_name((*m_iter)->get_type()) << ") "
- << decapitalize((*m_iter)->get_name()) << ";" << endl;
- out << indent() << "- (void) set" << capitalize((*m_iter)->get_name()) << ": ("
- << type_name((*m_iter)->get_type()) << ") " << (*m_iter)->get_name() << ";" << endl;
- out << indent() << "#endif" << endl;
- out << indent() << "- (BOOL) " << (*m_iter)->get_name() << "IsSet;" << endl << endl;
- }
-}
-
-/**
* Generate the initWithCoder method for this struct so it's compatible with
* the NSCoding protocol
*/
void t_cocoa_generator::generate_cocoa_struct_init_with_coder_method(ofstream& out,
t_struct* tstruct,
bool is_exception) {
- indent(out) << "- (id) initWithCoder: (NSCoder *) decoder" << endl;
+
+ indent(out) << "- (instancetype) initWithCoder: (NSCoder *) decoder" << endl;
scope_up(out);
+
if (is_exception) {
// NSExceptions conform to NSCoding, so we can call super
- out << indent() << "self = [super initWithCoder: decoder];" << endl;
+ indent(out) << "self = [super initWithCoder: decoder];" << endl;
} else {
- out << indent() << "self = [super init];" << endl;
+ indent(out) << "self = [super init];" << endl;
}
+
+ indent(out) << "if (self) ";
+ scope_up(out);
const vector<t_field*>& members = tstruct->get_members();
vector<t_field*>::const_iterator m_iter;
@@ -576,9 +652,9 @@
out << indent() << "if ([decoder containsValueForKey: @\"" << (*m_iter)->get_name() << "\"])"
<< endl;
scope_up(out);
- out << indent() << "__" << (*m_iter)->get_name() << " = ";
+ out << indent() << "_" << (*m_iter)->get_name() << " = ";
if (type_can_be_null(t)) {
- out << "[[decoder decodeObjectForKey: @\"" << (*m_iter)->get_name() << "\"] retain_stub];"
+ out << "[decoder decodeObjectForKey: @\"" << (*m_iter)->get_name() << "\"];"
<< endl;
} else if (t->is_enum()) {
out << "[decoder decodeIntForKey: @\"" << (*m_iter)->get_name() << "\"];" << endl;
@@ -608,9 +684,11 @@
+ t_base_type::t_base_name(tbase);
}
}
- out << indent() << "__" << (*m_iter)->get_name() << "_isset = YES;" << endl;
+ out << indent() << "_" << (*m_iter)->get_name() << "IsSet = YES;" << endl;
scope_down(out);
}
+
+ scope_down(out);
out << indent() << "return self;" << endl;
scope_down(out);
@@ -624,8 +702,10 @@
void t_cocoa_generator::generate_cocoa_struct_encode_with_coder_method(ofstream& out,
t_struct* tstruct,
bool is_exception) {
+
indent(out) << "- (void) encodeWithCoder: (NSCoder *) encoder" << endl;
scope_up(out);
+
if (is_exception) {
// NSExceptions conform to NSCoding, so we can call super
out << indent() << "[super encodeWithCoder: encoder];" << endl;
@@ -636,40 +716,39 @@
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
t_type* t = get_true_type((*m_iter)->get_type());
- out << indent() << "if (__" << (*m_iter)->get_name() << "_isset)" << endl;
+ out << indent() << "if (_" << (*m_iter)->get_name() << "IsSet)" << endl;
scope_up(out);
- // out << indent() << "__" << (*m_iter)->get_name() << " = ";
if (type_can_be_null(t)) {
- out << indent() << "[encoder encodeObject: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeObject: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
} else if (t->is_enum()) {
- out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
} else {
t_base_type::t_base tbase = ((t_base_type*)t)->get_base();
switch (tbase) {
case t_base_type::TYPE_BOOL:
- out << indent() << "[encoder encodeBool: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeBool: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
case t_base_type::TYPE_BYTE:
- out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
case t_base_type::TYPE_I16:
- out << indent() << "[encoder encodeInt: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeInt: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
case t_base_type::TYPE_I32:
- out << indent() << "[encoder encodeInt32: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeInt32: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
case t_base_type::TYPE_I64:
- out << indent() << "[encoder encodeInt64: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeInt64: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
case t_base_type::TYPE_DOUBLE:
- out << indent() << "[encoder encodeDouble: __" << (*m_iter)->get_name() << " forKey: @\""
+ out << indent() << "[encoder encodeDouble: _" << (*m_iter)->get_name() << " forKey: @\""
<< (*m_iter)->get_name() << "\"];" << endl;
break;
default:
@@ -685,6 +764,38 @@
}
/**
+ * Generate the copy method for this struct
+ */
+void t_cocoa_generator::generate_cocoa_struct_copy_method(ofstream& out, t_struct* tstruct, bool is_exception) {
+ out << indent() << "- (instancetype) copyWithZone:(NSZone *)zone" << endl;
+ scope_up(out);
+
+ if (is_exception) {
+ out << indent() << type_name(tstruct) << " val = [" << cocoa_prefix_ << tstruct->get_name() << " errorWithDomain: self.domain code: self.code userInfo: self.userInfo];" << endl;
+ } else {
+ out << indent() << type_name(tstruct) << " val = [" << cocoa_prefix_ << tstruct->get_name() << " new];" << endl;
+ }
+
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ t_type* t = get_true_type((*m_iter)->get_type());
+ if (type_can_be_null(t)) {
+ out << indent() << "val." << (*m_iter)->get_name() << " = [self." << (*m_iter)->get_name() << " copy];";
+ } else {
+ out << indent() << "val." << (*m_iter)->get_name() << " = self." << (*m_iter)->get_name() << ";";
+ }
+ out << endl;
+ }
+
+ out << indent() << "return val;" << endl;
+
+ scope_down(out);
+ out << endl;
+}
+
+/**
* Generate the hash method for this struct
*/
void t_cocoa_generator::generate_cocoa_struct_hash_method(ofstream& out, t_struct* tstruct) {
@@ -697,14 +808,14 @@
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
t_type* t = get_true_type((*m_iter)->get_type());
- out << indent() << "hash = (hash * 31) ^ __" << (*m_iter)->get_name()
- << "_isset ? 2654435761 : 0;" << endl;
- out << indent() << "if (__" << (*m_iter)->get_name() << "_isset)" << endl;
+ out << indent() << "hash = (hash * 31) ^ _" << (*m_iter)->get_name()
+ << "IsSet ? 2654435761 : 0;" << endl;
+ out << indent() << "if (_" << (*m_iter)->get_name() << "IsSet)" << endl;
scope_up(out);
if (type_can_be_null(t)) {
- out << indent() << "hash = (hash * 31) ^ [__" << (*m_iter)->get_name() << " hash];" << endl;
+ out << indent() << "hash = (hash * 31) ^ [_" << (*m_iter)->get_name() << " hash];" << endl;
} else {
- out << indent() << "hash = (hash * 31) ^ [@(__" << (*m_iter)->get_name() << ") hash];"
+ out << indent() << "hash = (hash * 31) ^ [@(_" << (*m_iter)->get_name() << ") hash];"
<< endl;
}
scope_down(out);
@@ -718,7 +829,7 @@
/**
* Generate the isEqual method for this struct
*/
-void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct) {
+void t_cocoa_generator::generate_cocoa_struct_is_equal_method(ofstream& out, t_struct* tstruct, bool is_exception) {
indent(out) << "- (BOOL) isEqual: (id) anObject" << endl;
scope_up(out);
@@ -730,38 +841,49 @@
string class_name = cocoa_prefix_ + tstruct->get_name();
- indent(out) << "if (![anObject isKindOfClass:[" << class_name << " class]]) {" << endl;
- indent_up();
- indent(out) << "return NO;" << endl;
- indent_down();
- indent(out) << "}" << endl;
-
- indent(out) << class_name << " *other = (" << class_name << " *)anObject;" << endl;
-
- const vector<t_field*>& members = tstruct->get_members();
- vector<t_field*>::const_iterator m_iter;
-
- for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- t_type* t = get_true_type((*m_iter)->get_type());
- string name = (*m_iter)->get_name();
- if (type_can_be_null(t)) {
- out << indent() << "if ((__" << name << "_isset != other->__" << name << "_isset) ||" << endl
- << indent() << " "
- << "(__" << name << "_isset && "
- << "((__" << name << " || other->__" << name << ") && "
- << "![__" << name << " isEqual:other->__" << name << "]))) {" << endl;
- } else {
- out << indent() << "if ((__" << name << "_isset != other->__" << name << "_isset) ||" << endl
- << indent() << " "
- << "(__" << name << "_isset && "
- << "(__" << name << " != other->__" << name << "))) {" << endl;
- }
+ if (is_exception) {
+ indent(out) << "if (![super isEqual:anObject]) {" << endl;
+ indent_up();
+ indent(out) << "return NO;" << endl;
+ indent_down();
+ indent(out) << "}" << endl << endl;
+ }
+ else {
+ indent(out) << "if (![anObject isKindOfClass:[" << class_name << " class]]) {" << endl;
indent_up();
indent(out) << "return NO;" << endl;
indent_down();
indent(out) << "}" << endl;
}
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ if (!members.empty()) {
+ indent(out) << class_name << " *other = (" << class_name << " *)anObject;" << endl;
+
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ t_type* t = get_true_type((*m_iter)->get_type());
+ string name = (*m_iter)->get_name();
+ if (type_can_be_null(t)) {
+ out << indent() << "if ((_" << name << "IsSet != other->_" << name << "IsSet) ||" << endl
+ << indent() << " "
+ << "(_" << name << "IsSet && "
+ << "((_" << name << " || other->_" << name << ") && "
+ << "![_" << name << " isEqual:other->_" << name << "]))) {" << endl;
+ } else {
+ out << indent() << "if ((_" << name << "IsSet != other->_" << name << "IsSet) ||" << endl
+ << indent() << " "
+ << "(_" << name << "IsSet && "
+ << "(_" << name << " != other->_" << name << "))) {" << endl;
+ }
+ indent_up();
+ indent(out) << "return NO;" << endl;
+ indent_down();
+ indent(out) << "}" << endl;
+ }
+ }
+
out << indent() << "return YES;" << endl;
scope_down(out);
out << endl;
@@ -785,10 +907,11 @@
// exceptions need to call the designated initializer on NSException
if (is_exception) {
- out << indent() << "- (id) init" << endl;
+ out << indent() << "- (instancetype) init" << endl;
scope_up(out);
- out << indent() << "return [super initWithName: @\"" << cocoa_prefix_ << tstruct->get_name()
- << "\" reason: @\"unknown\" userInfo: nil];" << endl;
+ out << indent() << "return [super initWithDomain: " << cocoa_prefix_ << capitalize(program_name_) << "ErrorDomain" << endl
+ << indent() << " code: " << cocoa_prefix_ << capitalize(program_name_) << "Error" << tstruct->get_name() << endl
+ << indent() << " userInfo: nil];" << endl;
scope_down(out);
out << endl;
} else {
@@ -796,12 +919,12 @@
// default initializer
// setup instance variables with default values
- indent(out) << "- (id) init" << endl;
+ indent(out) << "- (instancetype) init" << endl;
scope_up(out);
indent(out) << "self = [super init];" << endl;
+ indent(out) << "if (self)";
+ scope_up(out);
if (members.size() > 0) {
- out << "#if TARGET_OS_IPHONE || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)"
- << endl;
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
t_type* t = get_true_type((*m_iter)->get_type());
if ((*m_iter)->get_value() != NULL) {
@@ -813,8 +936,8 @@
true);
}
}
- out << "#endif" << endl;
}
+ scope_down(out);
indent(out) << "return self;" << endl;
scope_down(out);
out << endl;
@@ -830,17 +953,19 @@
} else {
out << indent() << "self = [super init];" << endl;
}
-
+
+ indent(out) << "if (self)";
+ scope_up(out);
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- t_type* t = get_true_type((*m_iter)->get_type());
- out << indent() << "__" << (*m_iter)->get_name() << " = ";
- if (type_can_be_null(t)) {
- out << "[" << (*m_iter)->get_name() << " retain_stub];" << endl;
+ out << indent() << "_" << (*m_iter)->get_name() << " = ";
+ if (get_true_type((*m_iter)->get_type())->is_container()) {
+ out << "[" << (*m_iter)->get_name() << " mutableCopy];" << endl;
} else {
out << (*m_iter)->get_name() << ";" << endl;
}
- out << indent() << "__" << (*m_iter)->get_name() << "_isset = YES;" << endl;
+ out << indent() << "_" << (*m_iter)->get_name() << "IsSet = YES;" << endl;
}
+ scope_down(out);
out << indent() << "return self;" << endl;
scope_down(out);
@@ -853,24 +978,9 @@
generate_cocoa_struct_encode_with_coder_method(out, tstruct, is_exception);
// hash and isEqual for NSObject
generate_cocoa_struct_hash_method(out, tstruct);
- generate_cocoa_struct_is_equal_method(out, tstruct);
-
- // dealloc
- if (!members.empty()) {
- out << "- (void) dealloc" << endl;
- scope_up(out);
-
- for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
- t_type* t = get_true_type((*m_iter)->get_type());
- if (type_can_be_null(t)) {
- indent(out) << "[__" << (*m_iter)->get_name() << " release_stub];" << endl;
- }
- }
-
- out << indent() << "[super dealloc_stub];" << endl;
- scope_down(out);
- out << endl;
- }
+ generate_cocoa_struct_is_equal_method(out, tstruct, is_exception);
+ // copy for NSObject
+ generate_cocoa_struct_copy_method(out, tstruct, is_exception);
// the rest of the methods
generate_cocoa_struct_field_accessor_implementations(out, tstruct, is_exception);
@@ -892,7 +1002,7 @@
* @param tstruct The struct definition
*/
void t_cocoa_generator::generate_cocoa_struct_reader(ofstream& out, t_struct* tstruct) {
- out << "- (void) read: (id <TProtocol>) inProtocol" << endl;
+ out << "- (BOOL) read: (id <TProtocol>) inProtocol error: (NSError *__autoreleasing *)__thriftError" << endl;
scope_up(out);
const vector<t_field*>& fields = tstruct->get_members();
@@ -900,11 +1010,11 @@
// Declare stack tmp variables
indent(out) << "NSString * fieldName;" << endl;
- indent(out) << "int fieldType;" << endl;
- indent(out) << "int fieldID;" << endl;
+ indent(out) << "SInt32 fieldType;" << endl;
+ indent(out) << "SInt32 fieldID;" << endl;
out << endl;
- indent(out) << "[inProtocol readStructBeginReturningName: NULL];" << endl;
+ indent(out) << "if (![inProtocol readStructBeginReturningName: NULL error: __thriftError]) return NO;" << endl;
// Loop over reading in fields
indent(out) << "while (true)" << endl;
@@ -912,11 +1022,11 @@
// Read beginning field marker
indent(out)
- << "[inProtocol readFieldBeginReturningName: &fieldName type: &fieldType fieldID: &fieldID];"
+ << "if (![inProtocol readFieldBeginReturningName: &fieldName type: &fieldType fieldID: &fieldID error: __thriftError]) return NO;"
<< endl;
// Check for field STOP marker and break
- indent(out) << "if (fieldType == TType_STOP) { " << endl;
+ indent(out) << "if (fieldType == TTypeSTOP) { " << endl;
indent_up();
indent(out) << "break;" << endl;
indent_down();
@@ -936,23 +1046,16 @@
generate_deserialize_field(out, *f_iter, "fieldValue");
indent(out) << call_field_setter(*f_iter, "fieldValue") << endl;
- // if this is an allocated field, release it since the struct
- // is now retaining it
- if (type_can_be_null((*f_iter)->get_type())) {
- // deserialized strings are autorelease, so don't release them
- if (!(get_true_type((*f_iter)->get_type())->is_string())) {
- indent(out) << "[fieldValue release_stub];" << endl;
- }
- }
indent_down();
out << indent() << "} else { " << endl;
if (log_unexpected_) {
out << indent() << " NSLog(@\"%s: field ID %i has unexpected type %i. Skipping.\", "
- "__PRETTY_FUNCTION__, fieldID, fieldType);" << endl;
+ "__PRETTY_FUNCTION__, (int)fieldID, (int)fieldType);" << endl;
}
- out << indent() << " [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl
- << indent() << "}" << endl << indent() << "break;" << endl;
+
+ out << indent() << " if (![TProtocolUtil skipType: fieldType onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+ out << indent() << "}" << endl << indent() << "break;" << endl;
indent_down();
}
@@ -960,25 +1063,29 @@
out << indent() << "default:" << endl;
if (log_unexpected_) {
out << indent() << " NSLog(@\"%s: unexpected field ID %i with type %i. Skipping.\", "
- "__PRETTY_FUNCTION__, fieldID, fieldType);" << endl;
+ "__PRETTY_FUNCTION__, (int)fieldID, (int)fieldType);" << endl;
}
- out << indent() << " [TProtocolUtil skipType: fieldType onProtocol: inProtocol];" << endl
- << indent() << " break;" << endl;
+
+ out << indent() << " if (![TProtocolUtil skipType: fieldType onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+
+ out << indent() << " break;" << endl;
scope_down(out);
// Read field end marker
- indent(out) << "[inProtocol readFieldEnd];" << endl;
+ indent(out) << "if (![inProtocol readFieldEnd: __thriftError]) return NO;" << endl;
scope_down(out);
- out << indent() << "[inProtocol readStructEnd];" << endl;
+ out << indent() << "if (![inProtocol readStructEnd: __thriftError]) return NO;" << endl;
// performs various checks (e.g. check that all required fields are set)
if (validate_required_) {
- out << indent() << "[self validate];" << endl;
+ out << indent() << "if (![self validate: __thriftError]) return NO;" << endl;
}
+ indent(out) << "return YES;" << endl;
+
indent_down();
out << indent() << "}" << endl << endl;
}
@@ -989,33 +1096,33 @@
* @param tstruct The struct definition
*/
void t_cocoa_generator::generate_cocoa_struct_writer(ofstream& out, t_struct* tstruct) {
- out << indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
+ out << indent() << "- (BOOL) write: (id <TProtocol>) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl;
indent_up();
string name = tstruct->get_name();
const vector<t_field*>& fields = tstruct->get_members();
vector<t_field*>::const_iterator f_iter;
- out << indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
+ out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << name << "\" error: __thriftError]) return NO;" << endl;
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
- out << indent() << "if (__" << (*f_iter)->get_name() << "_isset) {" << endl;
+ out << indent() << "if (_" << (*f_iter)->get_name() << "IsSet) {" << endl;
indent_up();
bool null_allowed = type_can_be_null((*f_iter)->get_type());
if (null_allowed) {
- out << indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
+ out << indent() << "if (_" << (*f_iter)->get_name() << " != nil) {" << endl;
indent_up();
}
- indent(out) << "[outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
+ indent(out) << "if (![outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
<< "\" type: " << type_to_enum((*f_iter)->get_type())
- << " fieldID: " << (*f_iter)->get_key() << "];" << endl;
+ << " fieldID: " << (*f_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
// Write field contents
- generate_serialize_field(out, *f_iter, "__" + (*f_iter)->get_name());
+ generate_serialize_field(out, *f_iter, "_" + (*f_iter)->get_name());
// Write field closer
- indent(out) << "[outProtocol writeFieldEnd];" << endl;
+ indent(out) << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
if (null_allowed) {
scope_down(out);
@@ -1023,9 +1130,11 @@
scope_down(out);
}
// Write the struct map
- out << indent() << "[outProtocol writeFieldStop];" << endl << indent()
- << "[outProtocol writeStructEnd];" << endl;
+ out << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;" << endl
+ << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;" << endl;
+ indent(out) << "return YES;" << endl;
+
indent_down();
out << indent() << "}" << endl << endl;
}
@@ -1038,14 +1147,14 @@
* @param tstruct The struct definition
*/
void t_cocoa_generator::generate_cocoa_struct_result_writer(ofstream& out, t_struct* tstruct) {
- out << indent() << "- (void) write: (id <TProtocol>) outProtocol {" << endl;
+ out << indent() << "- (BOOL) write: (id <TProtocol>) outProtocol error: (NSError *__autoreleasing *)__thriftError {" << endl;
indent_up();
string name = tstruct->get_name();
const vector<t_field*>& fields = tstruct->get_members();
vector<t_field*>::const_iterator f_iter;
- out << indent() << "[outProtocol writeStructBeginWithName: @\"" << name << "\"];" << endl;
+ out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << name << "\" error: __thriftError]) return NO;" << endl;
bool first = true;
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
@@ -1056,24 +1165,24 @@
out << " else if ";
}
- out << "(__" << (*f_iter)->get_name() << "_isset) {" << endl;
+ out << "(_" << (*f_iter)->get_name() << "IsSet) {" << endl;
indent_up();
bool null_allowed = type_can_be_null((*f_iter)->get_type());
if (null_allowed) {
- out << indent() << "if (__" << (*f_iter)->get_name() << " != nil) {" << endl;
+ out << indent() << "if (_" << (*f_iter)->get_name() << " != nil) {" << endl;
indent_up();
}
- indent(out) << "[outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
+ indent(out) << "if (![outProtocol writeFieldBeginWithName: @\"" << (*f_iter)->get_name()
<< "\" type: " << type_to_enum((*f_iter)->get_type())
- << " fieldID: " << (*f_iter)->get_key() << "];" << endl;
+ << " fieldID: " << (*f_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
// Write field contents
- generate_serialize_field(out, *f_iter, "__" + (*f_iter)->get_name());
+ generate_serialize_field(out, *f_iter, "_" + (*f_iter)->get_name());
// Write field closer
- indent(out) << "[outProtocol writeFieldEnd];" << endl;
+ indent(out) << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
if (null_allowed) {
indent_down();
@@ -1084,9 +1193,12 @@
indent(out) << "}";
}
// Write the struct map
- out << endl << indent() << "[outProtocol writeFieldStop];" << endl << indent()
- << "[outProtocol writeStructEnd];" << endl;
+ out << endl << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;"
+ << endl << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;"
+ << endl;
+ indent(out) << "return YES;" << endl;
+
indent_down();
out << indent() << "}" << endl << endl;
}
@@ -1098,7 +1210,7 @@
* @param tstruct The struct definition
*/
void t_cocoa_generator::generate_cocoa_struct_validator(ofstream& out, t_struct* tstruct) {
- out << indent() << "- (void) validate {" << endl;
+ out << indent() << "- (BOOL) validate: (NSError *__autoreleasing *)__thriftError {" << endl;
indent_up();
const vector<t_field*>& fields = tstruct->get_members();
@@ -1108,13 +1220,19 @@
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
t_field* field = (*f_iter);
if ((*f_iter)->get_req() == t_field::T_REQUIRED) {
- out << indent() << "if (!__" << field->get_name() << "_isset) {" << endl << indent()
- << " @throw [TProtocolException exceptionWithName: @\"TProtocolException\"" << endl
- << indent() << " reason: @\"Required field '"
- << (*f_iter)->get_name() << "' is not set.\"];" << endl << indent() << "}" << endl;
+ out << indent() << "if (!_" << field->get_name() << "IsSet) ";
+ scope_up(out);
+ indent(out) << "if (__thriftError) ";
+ scope_up(out);
+ out << indent() << "*__thriftError = [NSError errorWithDomain: TProtocolErrorDomain" << endl
+ << indent() << " code: TProtocolErrorUnknown" << endl
+ << indent() << " userInfo: @{TProtocolErrorExtendedErrorKey: @(TProtocolExtendedErrorMissingRequiredField)," << endl
+ << indent() << " TProtocolErrorFieldNameKey: @\"" << (*f_iter)->get_name() << "\"}];" << endl;
+ scope_down(out);
+ scope_down(out);
}
}
-
+ indent(out) << "return YES;" << endl;
indent_down();
out << indent() << "}" << endl << endl;
}
@@ -1138,37 +1256,12 @@
std::string cap_name = field_name;
cap_name[0] = toupper(cap_name[0]);
- // Simple getter
- indent(out) << "- (" << type_name(type) << ") ";
- out << field_name << " {" << endl;
- indent_up();
- if (!type_can_be_null(type)) {
- indent(out) << "return __" << field_name << ";" << endl;
- } else {
- indent(out) << "return [[__" << field_name << " retain_stub] autorelease_stub];" << endl;
- }
- indent_down();
- indent(out) << "}" << endl << endl;
-
// Simple setter
- indent(out) << "- (void) set" << cap_name << ": (" << type_name(type) << ") " << field_name
+ indent(out) << "- (void) set" << cap_name << ": (" << type_name(type, false, true) << ") " << field_name
<< " {" << endl;
indent_up();
- if (!type_can_be_null(type)) {
- indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
- } else {
- indent(out) << "[" << field_name << " retain_stub];" << endl;
- indent(out) << "[__" << field_name << " release_stub];" << endl;
- indent(out) << "__" << field_name << " = " << field_name << ";" << endl;
- }
- indent(out) << "__" << field_name << "_isset = YES;" << endl;
- indent_down();
- indent(out) << "}" << endl << endl;
-
- // IsSet
- indent(out) << "- (BOOL) " << field_name << "IsSet {" << endl;
- indent_up();
- indent(out) << "return __" << field_name << "_isset;" << endl;
+ indent(out) << "_" << field_name << " = " << field_name << ";" << endl;
+ indent(out) << "_" << field_name << "IsSet = YES;" << endl;
indent_down();
indent(out) << "}" << endl << endl;
@@ -1176,10 +1269,9 @@
indent(out) << "- (void) unset" << cap_name << " {" << endl;
indent_up();
if (type_can_be_null(type)) {
- indent(out) << "[__" << field_name << " release_stub];" << endl;
- indent(out) << "__" << field_name << " = nil;" << endl;
+ indent(out) << "_" << field_name << " = nil;" << endl;
}
- indent(out) << "__" << field_name << "_isset = NO;" << endl;
+ indent(out) << "_" << field_name << "IsSet = NO;" << endl;
indent_down();
indent(out) << "}" << endl << endl;
}
@@ -1191,7 +1283,14 @@
* @param tstruct The struct definition
*/
void t_cocoa_generator::generate_cocoa_struct_description(ofstream& out, t_struct* tstruct) {
- out << indent() << "- (NSString *) description {" << endl;
+
+ // Allow use of debugDescription so the app can add description via a cateogory/extension
+ if (debug_descriptions_) {
+ out << indent() << "- (NSString *) debugDescription {" << endl;
+ }
+ else {
+ out << indent() << "- (NSString *) description {" << endl;
+ }
indent_up();
out << indent() << "NSMutableString * ms = [NSMutableString stringWithString: @\""
@@ -1208,8 +1307,8 @@
indent(out) << "[ms appendString: @\"," << (*f_iter)->get_name() << ":\"];" << endl;
}
t_type* ttype = (*f_iter)->get_type();
- indent(out) << "[ms appendFormat: @\"" << format_string_for_type(ttype) << "\", __"
- << (*f_iter)->get_name() << "];" << endl;
+ indent(out) << "[ms appendFormat: @\"" << format_string_for_type(ttype) << "\", "
+ << format_cast_for_type(ttype) << "_" << (*f_iter)->get_name() << "];" << endl;
}
out << indent() << "[ms appendString: @\")\"];" << endl << indent()
<< "return [NSString stringWithString: ms];" << endl;
@@ -1247,23 +1346,35 @@
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
t_struct* ts = (*f_iter)->get_arglist();
- generate_cocoa_struct_interface(f_impl_, ts, false);
- generate_cocoa_struct_implementation(f_impl_, ts, false, false);
- generate_function_helpers(*f_iter);
+
+ string qname = function_args_helper_struct_type(tservice, *f_iter);
+
+ t_struct qname_ts = t_struct(ts->get_program(), qname);
+
+ const vector<t_field*>& members = ts->get_members();
+ vector<t_field*>::const_iterator m_iter;
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ qname_ts.append(*m_iter);
+ }
+
+ generate_cocoa_struct_interface(f_impl_, &qname_ts, false);
+ generate_cocoa_struct_implementation(f_impl_, &qname_ts, false, false);
+ generate_function_helpers(tservice, *f_iter);
}
}
-string t_cocoa_generator::function_result_helper_struct_type(t_function* tfunction) {
+string t_cocoa_generator::function_result_helper_struct_type(t_service *tservice, t_function* tfunction) {
if (tfunction->is_oneway()) {
- return capitalize(tfunction->get_name());
+ return tservice->get_name() + "_" + tfunction->get_name();
} else {
- return capitalize(tfunction->get_name()) + "_result";
+ return tservice->get_name() + "_" + tfunction->get_name() + "_result";
}
}
-string t_cocoa_generator::function_args_helper_struct_type(t_function* tfunction) {
- return tfunction->get_name() + "_args";
+string t_cocoa_generator::function_args_helper_struct_type(t_service *tservice, t_function* tfunction) {
+ return tservice->get_name() + "_" + tfunction->get_name() + "_args";
}
/**
@@ -1271,14 +1382,14 @@
*
* @param tfunction The function
*/
-void t_cocoa_generator::generate_function_helpers(t_function* tfunction) {
+void t_cocoa_generator::generate_function_helpers(t_service *tservice, t_function* tfunction) {
if (tfunction->is_oneway()) {
return;
}
// create a result struct with a success field of the return type,
// and a field for each type of exception thrown
- t_struct result(program_, function_result_helper_struct_type(tfunction));
+ t_struct result(program_, function_result_helper_struct_type(tservice, tfunction));
t_field success(tfunction->get_returntype(), "success", 0);
if (!tfunction->get_returntype()->is_void()) {
result.append(&success);
@@ -1307,7 +1418,7 @@
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
- out << "- " << function_signature(*f_iter) << ";"
+ out << "- " << function_signature(*f_iter, true) << ";"
<< " // throws ";
t_struct* xs = (*f_iter)->get_xceptions();
const std::vector<t_field*>& xceptions = xs->get_members();
@@ -1332,7 +1443,10 @@
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
- out << "- " << async_function_signature(*f_iter) << ";" << endl;
+ out << "- " << async_function_signature(*f_iter, false) << ";" << endl;
+ if (promise_kit_) {
+ out << "- " << promise_function_signature(*f_iter) << ";" << endl;
+ }
}
out << "@end" << endl << endl;
}
@@ -1345,7 +1459,7 @@
void t_cocoa_generator::generate_cocoa_service_client_interface(ofstream& out,
t_service* tservice) {
out << "@interface " << cocoa_prefix_ << tservice->get_name() << "Client : TBaseClient <"
- << cocoa_prefix_ << tservice->get_name() << "> ";
+ << cocoa_prefix_ << tservice->get_name() << "> " << endl;
out << "- (id) initWithProtocol: (id <TProtocol>) protocol;" << endl;
out << "- (id) initWithInProtocol: (id <TProtocol>) inProtocol outProtocol: (id <TProtocol>) "
@@ -1361,14 +1475,11 @@
void t_cocoa_generator::generate_cocoa_service_client_async_interface(ofstream& out,
t_service* tservice) {
out << "@interface " << cocoa_prefix_ << tservice->get_name() << "ClientAsync : TBaseClient <"
- << cocoa_prefix_ << tservice->get_name() << "Async> ";
+ << cocoa_prefix_ << tservice->get_name() << "Async> " << endl
+ << endl;
- scope_up(out);
- out << indent() << "id <TAsyncTransport> asyncTransport;" << endl;
- scope_down(out);
-
- out << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) factory "
- "transport: (id <TAsyncTransport>) transport;" << endl;
+ out << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) protocolFactory "
+ << "transportFactory: (id <TAsyncTransportFactory>) transportFactory;" << endl;
out << "@end" << endl << endl;
}
@@ -1382,12 +1493,7 @@
void t_cocoa_generator::generate_cocoa_service_server_interface(ofstream& out,
t_service* tservice) {
out << "@interface " << cocoa_prefix_ << tservice->get_name()
- << "Processor : NSObject <TProcessor> ";
-
- scope_up(out);
- out << indent() << "id <" << cocoa_prefix_ << tservice->get_name() << "> mService;" << endl;
- out << indent() << "NSDictionary * mMethodMap;" << endl;
- scope_down(out);
+ << "Processor : NSObject <TProcessor> " << endl;
out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_
<< tservice->get_name() << ">) service;" << endl;
@@ -1398,25 +1504,28 @@
void t_cocoa_generator::generate_cocoa_service_client_send_function_implementation(
ofstream& out,
- t_function* tfunction) {
+ t_service *tservice,
+ t_function* tfunction,
+ bool needs_protocol) {
string funname = tfunction->get_name();
- t_function send_function(g_type_void,
+ t_function send_function(g_type_bool,
string("send_") + tfunction->get_name(),
tfunction->get_arglist());
- string argsname = tfunction->get_name() + "_args";
+ string argsname = function_args_helper_struct_type(tservice, tfunction);
// Open function
- indent(out) << "- " << function_signature(&send_function) << endl;
+ indent(out) << "- (BOOL) send_" << tfunction->get_name() << argument_list(tfunction->get_arglist(), needs_protocol ? "outProtocol" : "", true) << endl;
scope_up(out);
-
+
// Serialize the request
- out << indent() << "[outProtocol writeMessageBeginWithName: @\"" << funname << "\""
- << (tfunction->is_oneway() ? " type: TMessageType_ONEWAY" : " type: TMessageType_CALL")
- << " sequenceID: 0];" << endl;
+ out << indent() << "if (![outProtocol writeMessageBeginWithName: @\"" << funname << "\""
+ << (tfunction->is_oneway() ? " type: TMessageTypeONEWAY" : " type: TMessageTypeCALL")
+ << " sequenceID: 0 error: __thriftError]) return NO;" << endl;
- out << indent() << "[outProtocol writeStructBeginWithName: @\"" << argsname << "\"];" << endl;
+ out << indent() << "if (![outProtocol writeStructBeginWithName: @\"" << argsname
+ << "\" error: __thriftError]) return NO;" << endl;
// write out function parameters
t_struct* arg_struct = tfunction->get_arglist();
@@ -1428,14 +1537,14 @@
out << indent() << "if (" << fieldName << " != nil)";
scope_up(out);
}
- out << indent() << "[outProtocol writeFieldBeginWithName: @\"" << fieldName
+ out << indent() << "if (![outProtocol writeFieldBeginWithName: @\"" << fieldName
<< "\""
" type: " << type_to_enum((*fld_iter)->get_type())
- << " fieldID: " << (*fld_iter)->get_key() << "];" << endl;
+ << " fieldID: " << (*fld_iter)->get_key() << " error: __thriftError]) return NO;" << endl;
generate_serialize_field(out, *fld_iter, fieldName);
- out << indent() << "[outProtocol writeFieldEnd];" << endl;
+ out << indent() << "if (![outProtocol writeFieldEnd: __thriftError]) return NO;" << endl;
if (type_can_be_null((*fld_iter)->get_type())) {
indent_down();
@@ -1443,63 +1552,91 @@
}
}
- out << indent() << "[outProtocol writeFieldStop];" << endl;
- out << indent() << "[outProtocol writeStructEnd];" << endl;
- out << indent() << "[outProtocol writeMessageEnd];" << endl;
+ out << indent() << "if (![outProtocol writeFieldStop: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![outProtocol writeStructEnd: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![outProtocol writeMessageEnd: __thriftError]) return NO;" << endl;
+ out << indent() << "return YES;" << endl;
scope_down(out);
out << endl;
}
void t_cocoa_generator::generate_cocoa_service_client_recv_function_implementation(
ofstream& out,
- t_function* tfunction) {
- t_struct noargs(program_);
- t_function recv_function(tfunction->get_returntype(),
- string("recv_") + tfunction->get_name(),
- &noargs,
- tfunction->get_xceptions());
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol) {
+
+
// Open function
- indent(out) << "- " << function_signature(&recv_function) << endl;
+ indent(out) << "- (BOOL) recv_" << tfunction->get_name();
+ if (!tfunction->get_returntype()->is_void()) {
+ out << ": (" << type_name(tfunction->get_returntype(), false, true) << " *) result ";
+ if (needs_protocol) {
+ out << "protocol";
+ } else {
+ out << "error";
+ }
+ }
+ if (needs_protocol) {
+ out << ": (id<TProtocol>) inProtocol error";
+ }
+ out << ": (NSError *__autoreleasing *)__thriftError" << endl;
scope_up(out);
// TODO(mcslee): Message validation here, was the seqid etc ok?
// check for an exception
- out << indent() << "TApplicationException * x = [self checkIncomingMessageException];" << endl
- << indent() << "if (x != nil)";
+ out << indent() << "NSError *incomingException = [self checkIncomingMessageException: inProtocol];" << endl
+ << indent() << "if (incomingException)";
scope_up(out);
- out << indent() << "@throw x;" << endl;
+ out << indent() << "if (__thriftError)";
+ scope_up(out);
+ out << indent() << "*__thriftError = incomingException;" << endl;
+ scope_down(out);
+ out << indent() << "return NO;" << endl;
scope_down(out);
// FIXME - could optimize here to reduce creation of temporary objects.
- string resultname = function_result_helper_struct_type(tfunction);
- out << indent() << cocoa_prefix_ << resultname << " * result = [[[" << cocoa_prefix_ << resultname
- << " alloc] init] autorelease_stub];" << endl;
- indent(out) << "[result read: inProtocol];" << endl;
- indent(out) << "[inProtocol readMessageEnd];" << endl;
+ string resultname = function_result_helper_struct_type(tservice, tfunction);
+ out << indent() << cocoa_prefix_ << resultname << " * resulter = [" << cocoa_prefix_ << resultname << " new];" << endl;
+ indent(out) << "if (![resulter read: inProtocol error: __thriftError]) return NO;" << endl;
+ indent(out) << "if (![inProtocol readMessageEnd: __thriftError]) return NO;" << endl;
// Careful, only return _result if not a void function
if (!tfunction->get_returntype()->is_void()) {
- out << indent() << "if ([result successIsSet]) {" << endl << indent()
- << " return [result success];" << endl << indent() << "}" << endl;
+ out << indent() << "if (resulter.successIsSet)";
+ scope_up(out);
+ out << indent() << "*result = resulter.success;" << endl;
+ out << indent() << "return YES;" << endl;
+ scope_down(out);
}
t_struct* xs = tfunction->get_xceptions();
const std::vector<t_field*>& xceptions = xs->get_members();
vector<t_field*>::const_iterator x_iter;
for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
- out << indent() << "if ([result " << (*x_iter)->get_name() << "IsSet]) {" << endl << indent()
- << " @throw [result " << (*x_iter)->get_name() << "];" << endl << indent() << "}" << endl;
+ out << indent() << "if (resulter." << (*x_iter)->get_name() << "IsSet)";
+ scope_up(out);
+ out << indent() << "if (__thriftError)";
+ scope_up(out);
+ out << indent() << "*__thriftError = [resulter " << (*x_iter)->get_name() << "];" << endl;
+ scope_down(out);
+ out << indent() << "return NO;" << endl;
+ scope_down(out);
}
// If you get here it's an exception, unless a void function
if (tfunction->get_returntype()->is_void()) {
- indent(out) << "return;" << endl;
+ indent(out) << "return YES;" << endl;
} else {
- out << indent() << "@throw [TApplicationException exceptionWithType: "
- "TApplicationException_MISSING_RESULT" << endl << indent()
- << " reason: @\"" << tfunction->get_name()
- << " failed: unknown result\"];" << endl;
+ out << indent() << "if (__thriftError)";
+ scope_up(out);
+ out << indent() << "*__thriftError = [NSError errorWithDomain: TApplicationErrorDomain" << endl
+ << indent() << " code: TApplicationErrorMissingResult" << endl
+ << indent() << " userInfo: @{TApplicationErrorMethodKey: @\""
+ << tfunction->get_name() << "\"}];" << endl;
+ scope_down(out);
+ out << indent() << "return NO;" << endl;
}
// Close function
@@ -1513,12 +1650,13 @@
* @param tfunction The service to generate an implementation for
*/
void t_cocoa_generator::generate_cocoa_service_client_send_function_invocation(
- ofstream& out,
- t_function* tfunction) {
+ ofstream& out,
+ t_function* tfunction) {
+
t_struct* arg_struct = tfunction->get_arglist();
const vector<t_field*>& fields = arg_struct->get_members();
vector<t_field*>::const_iterator fld_iter;
- indent(out) << "[self send_" << tfunction->get_name();
+ out << indent() << "if (![self send_" << tfunction->get_name();
bool first = true;
for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
string fieldName = (*fld_iter)->get_name();
@@ -1530,7 +1668,45 @@
out << fieldName << ": " << fieldName;
}
}
- out << "];" << endl;
+ if (!fields.empty()) {
+ out << " error";
+ }
+ out << ": __thriftError]) " << invalid_return_statement(tfunction) << endl;
+}
+
+/**
+ * Generates an invocation of a given 'send_' function.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_cocoa_generator::generate_cocoa_service_client_send_async_function_invocation(
+ ofstream& out,
+ t_function* tfunction,
+ string failureBlockName) {
+
+ t_struct* arg_struct = tfunction->get_arglist();
+ const vector<t_field*>& fields = arg_struct->get_members();
+ vector<t_field*>::const_iterator fld_iter;
+ out << indent() << "if (![self send_" << tfunction->get_name();
+ bool first = true;
+ for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
+ string fieldName = (*fld_iter)->get_name();
+ out << " ";
+ if (first) {
+ first = false;
+ out << ": " << fieldName;
+ } else {
+ out << fieldName << ": " << fieldName;
+ }
+ }
+ if (!fields.empty()) {
+ out << " protocol";
+ }
+ out << ": protocol error: &thriftError]) ";
+ scope_up(out);
+ out << indent() << failureBlockName << "(thriftError);" << endl
+ << indent() << "return;" << endl;
+ scope_down(out);
}
/**
@@ -1540,7 +1716,20 @@
*/
void t_cocoa_generator::generate_cocoa_service_client_implementation(ofstream& out,
t_service* tservice) {
- out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "Client" << endl;
+
+ string name = cocoa_prefix_ + tservice->get_name() + "Client";
+
+ out << "@interface " << name << " () ";
+ scope_up(out);
+ out << endl;
+ out << indent() << "id<TProtocol> inProtocol;" << endl;
+ out << indent() << "id<TProtocol> outProtocol;" << endl;
+ out << endl;
+ scope_down(out);
+ out << endl;
+ out << "@end" << endl << endl;
+
+ out << "@implementation " << name << endl;
// initializers
out << "- (id) initWithProtocol: (id <TProtocol>) protocol" << endl;
@@ -1553,8 +1742,11 @@
"anOutProtocol" << endl;
scope_up(out);
out << indent() << "self = [super init];" << endl;
- out << indent() << "inProtocol = [anInProtocol retain_stub];" << endl;
- out << indent() << "outProtocol = [anOutProtocol retain_stub];" << endl;
+ out << indent() << "if (self) ";
+ scope_up(out);
+ out << indent() << "inProtocol = anInProtocol;" << endl;
+ out << indent() << "outProtocol = anOutProtocol;" << endl;
+ scope_down(out);
out << indent() << "return self;" << endl;
scope_down(out);
out << endl;
@@ -1564,29 +1756,40 @@
vector<t_function*>::const_iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
- generate_cocoa_service_client_send_function_implementation(out, *f_iter);
+ generate_cocoa_service_client_send_function_implementation(out, tservice, *f_iter, false);
if (!(*f_iter)->is_oneway()) {
- generate_cocoa_service_client_recv_function_implementation(out, *f_iter);
+ generate_cocoa_service_client_recv_function_implementation(out, tservice, *f_iter, false);
}
// Open function
- indent(out) << "- " << function_signature(*f_iter) << endl;
+ indent(out) << "- " << function_signature(*f_iter, true) << endl;
scope_up(out);
generate_cocoa_service_client_send_function_invocation(out, *f_iter);
- out << indent() << "[[outProtocol transport] flush];" << endl;
+ out << indent() << "if (![[outProtocol transport] flush: __thriftError]) " << invalid_return_statement(*f_iter) << endl;
if (!(*f_iter)->is_oneway()) {
- out << indent();
- if (!(*f_iter)->get_returntype()->is_void()) {
- out << "return ";
+ if ((*f_iter)->get_returntype()->is_void()) {
+ out << indent() << "if (![self recv_" << (*f_iter)->get_name() << ": __thriftError]) return NO;" << endl;
+ out << indent() << "return YES;" << endl;
+ } else {
+ out << indent() << type_name((*f_iter)->get_returntype(), false, true) << " __result;" << endl
+ << indent() << "if (![self recv_" << (*f_iter)->get_name() << ": &__result error: __thriftError]) "
+ << invalid_return_statement(*f_iter) << endl;
+ if (type_can_be_null((*f_iter)->get_returntype())) {
+ out << indent() << "return __result;" << endl;
+ } else {
+ out << indent() << "return @(__result);" << endl;
+ }
}
- out << "[self recv_" << (*f_iter)->get_name() << "];" << endl;
+ }
+ else {
+ out << indent() << "return YES;" << endl;
}
scope_down(out);
out << endl;
}
- indent_down();
+
out << "@end" << endl << endl;
}
@@ -1597,16 +1800,30 @@
*/
void t_cocoa_generator::generate_cocoa_service_client_async_implementation(ofstream& out,
t_service* tservice) {
- out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "ClientAsync" << endl
- << endl << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) factory "
- "transport: (id <TAsyncTransport>) transport;" << endl;
+
+ string name = cocoa_prefix_ + tservice->get_name() + "ClientAsync";
+
+ out << "@interface " << name << " () ";
+ scope_up(out);
+ out << endl;
+ out << indent() << "id<TProtocolFactory> protocolFactory;" << endl;
+ out << indent() << "id<TAsyncTransportFactory> transportFactory;" << endl;
+ out << endl;
+ scope_down(out);
+ out << endl;
+ out << "@end" << endl << endl;
+
+
+ out << "@implementation " << name << endl
+ << endl << "- (id) initWithProtocolFactory: (id <TProtocolFactory>) aProtocolFactory "
+ "transportFactory: (id <TAsyncTransportFactory>) aTransportFactory;" << endl;
scope_up(out);
out << indent() << "self = [super init];" << endl;
- out << indent() << "inProtocol = [[factory newProtocolOnTransport:transport] retain_stub];"
- << endl;
- out << indent() << "outProtocol = inProtocol;" << endl;
- out << indent() << "asyncTransport = transport;" << endl;
+ out << indent() << "if (self) {" << endl;
+ out << indent() << " protocolFactory = aProtocolFactory;" << endl;
+ out << indent() << " transportFactory = aTransportFactory;" << endl;
+ out << indent() << "}" << endl;
out << indent() << "return self;" << endl;
scope_down(out);
out << endl;
@@ -1616,57 +1833,120 @@
vector<t_function*>::const_iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
- generate_cocoa_service_client_send_function_implementation(out, *f_iter);
+ generate_cocoa_service_client_send_function_implementation(out, tservice, *f_iter, true);
if (!(*f_iter)->is_oneway()) {
- generate_cocoa_service_client_recv_function_implementation(out, *f_iter);
+ generate_cocoa_service_client_recv_function_implementation(out, tservice, *f_iter, true);
}
// Open function
- indent(out) << "- " << async_function_signature(*f_iter) << endl;
+ indent(out) << "- " << async_function_signature(*f_iter, false) << endl;
scope_up(out);
- indent(out) << "@try {" << endl;
- indent_up();
- generate_cocoa_service_client_send_function_invocation(out, *f_iter);
- indent_down();
- out << indent() << "} @catch(TException * texception) {" << endl;
- indent_up();
- out << indent() << "failureBlock(texception);" << endl << indent() << "return;" << endl;
- indent_down();
- indent(out) << "}" << endl;
+
+ out << indent() << "NSError *thriftError;" << endl
+ << indent() << "id<TAsyncTransport> transport = [transportFactory newTransport];" << endl
+ << indent() << "id<TProtocol> protocol = [protocolFactory newProtocolOnTransport:transport];" << endl
+ << endl;
+
+ generate_cocoa_service_client_send_async_function_invocation(out, *f_iter, "failureBlock");
- out << indent() << "[asyncTransport flush:^{" << endl;
+ out << indent() << "[transport flushWithCompletion:^{" << endl;
indent_up();
- out << indent() << "@try {" << endl;
- indent_up();
-
- string recv_invocation = "[self recv_" + (*f_iter)->get_name() + "]";
- if (!(*f_iter)->is_oneway() && (*f_iter)->get_returntype()->is_void()) {
- out << indent() << recv_invocation << ";" << endl;
+ if (!(*f_iter)->is_oneway()) {
+ out << indent() << "NSError *thriftError;" << endl;
+
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << indent() << type_name((*f_iter)->get_returntype()) << " result;" << endl;
+ }
+ out << indent() << "if (![self recv_" << (*f_iter)->get_name();
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << ": &result protocol";
+ }
+ out << ": protocol error: &thriftError]) ";
+ scope_up(out);
+ out << indent() << "failureBlock(thriftError);" << endl
+ << indent() << "return;" << endl;
+ scope_down(out);
}
+
out << indent() << "responseBlock(";
if (!(*f_iter)->is_oneway() && !(*f_iter)->get_returntype()->is_void()) {
- out << recv_invocation;
+ out << "result";
}
out << ");" << endl;
indent_down();
-
- out << indent() << "} @catch(TException * texception) {" << endl;
- indent_up();
-
- out << indent() << "failureBlock(texception);" << endl;
-
- indent_down();
- out << indent() << "}" << endl;
-
- indent_down();
+
out << indent() << "} failure:failureBlock];" << endl;
-
+
scope_down(out);
out << endl;
+
+ // Promise function
+ if (promise_kit_) {
+
+ indent(out) << "- " << promise_function_signature(*f_iter) << endl;
+ scope_up(out);
+
+ out << indent() << "return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolver) {" << endl;
+ indent_up();
+
+ out << indent() << "NSError *thriftError;" << endl
+ << indent() << "id<TAsyncTransport> transport = [transportFactory newTransport];" << endl
+ << indent() << "id<TProtocol> protocol = [protocolFactory newProtocolOnTransport:transport];" << endl
+ << endl;
+
+ generate_cocoa_service_client_send_async_function_invocation(out, *f_iter, "resolver");
+
+ out << indent() << "[transport flushWithCompletion:^{" << endl;
+ indent_up();
+
+ if (!(*f_iter)->is_oneway()) {
+ out << indent() << "NSError *thriftError;" << endl;
+
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << indent() << type_name((*f_iter)->get_returntype()) << " result;" << endl;
+ }
+ out << indent() << "if (![self recv_" << (*f_iter)->get_name();
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << ": &result protocol";
+ }
+ out << ": protocol error: &thriftError]) ";
+ scope_up(out);
+ out << indent() << "resolver(thriftError);" << endl
+ << indent() << "return;" << endl;
+ scope_down(out);
+ }
+
+ out << indent() << "resolver(";
+ if ((*f_iter)->is_oneway() || (*f_iter)->get_returntype()->is_void()) {
+ out << "@YES";
+ } else if (type_can_be_null((*f_iter)->get_returntype())) {
+ out << "result";
+ } else {
+ out << "@(result)";
+ }
+ out << ");" << endl;
+
+ indent_down();
+
+ out << indent() << "} failure:^(NSError *error) {" << endl;
+ indent_up();
+ out << indent() << "resolver(error);" << endl;
+ indent_down();
+ out << indent() << "}];" << endl;
+
+ indent_down();
+ out << indent() << "}];" << endl;
+
+ scope_down(out);
+
+ out << endl;
+
+ }
+
}
out << "@end" << endl << endl;
@@ -1680,19 +1960,29 @@
*/
void t_cocoa_generator::generate_cocoa_service_server_implementation(ofstream& out,
t_service* tservice) {
- out << "@implementation " << cocoa_prefix_ << tservice->get_name() << "Processor" << endl;
+
+ string name = cocoa_prefix_ + tservice->get_name() + "Processor";
+
+ out << "@interface " << name << " () ";
+
+ scope_up(out);
+ out << indent() << "id <" << cocoa_prefix_ << tservice->get_name() << "> service;" << endl;
+ out << indent() << "NSDictionary * methodMap;" << endl;
+ scope_down(out);
+
+ out << "@end" << endl << endl;
+
+ out << "@implementation " << name << endl;
// initializer
out << endl;
- out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_
- << tservice->get_name() << ">) service" << endl;
+ out << "- (id) initWith" << tservice->get_name() << ": (id <" << cocoa_prefix_ << tservice->get_name() << ">) aService" << endl;
scope_up(out);
out << indent() << "self = [super init];" << endl;
- out << indent() << "if (!self) {" << endl;
- out << indent() << " return nil;" << endl;
- out << indent() << "}" << endl;
- out << indent() << "mService = [service retain_stub];" << endl;
- out << indent() << "mMethodMap = [[NSMutableDictionary dictionary] retain_stub];" << endl;
+ out << indent() << "if (self) ";
+ scope_up(out);
+ out << indent() << "service = aService;" << endl;
+ out << indent() << "methodMap = [NSMutableDictionary dictionary];" << endl;
// generate method map for routing incoming calls
vector<t_function*> functions = tservice->get_functions();
@@ -1700,16 +1990,15 @@
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
string funname = (*f_iter)->get_name();
scope_up(out);
- out << indent() << "SEL s = @selector(process_" << funname
- << "_withSequenceID:inProtocol:outProtocol:);" << endl;
+ out << indent() << "SEL s = @selector(process_" << funname << "_withSequenceID:inProtocol:outProtocol:error:);" << endl;
out << indent() << "NSMethodSignature * sig = [self methodSignatureForSelector: s];" << endl;
- out << indent()
- << "NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: sig];" << endl;
+ out << indent() << "NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: sig];" << endl;
out << indent() << "[invocation setSelector: s];" << endl;
out << indent() << "[invocation retainArguments];" << endl;
- out << indent() << "[mMethodMap setValue: invocation forKey: @\"" << funname << "\"];" << endl;
+ out << indent() << "[methodMap setValue: invocation forKey: @\"" << funname << "\"];" << endl;
scope_down(out);
}
+ scope_down(out);
out << indent() << "return self;" << endl;
scope_down(out);
@@ -1718,33 +2007,36 @@
out << endl;
out << indent() << "- (id<" << cocoa_prefix_ << tservice->get_name() << ">) service" << endl;
out << indent() << "{" << endl;
- out << indent() << " return [[mService retain_stub] autorelease_stub];" << endl;
+ out << indent() << " return service;" << endl;
out << indent() << "}" << endl;
// implementation of the TProcess method, which dispatches the incoming call using the method map
out << endl;
out << indent() << "- (BOOL) processOnInputProtocol: (id <TProtocol>) inProtocol" << endl;
out << indent() << " outputProtocol: (id <TProtocol>) outProtocol" << endl;
+ out << indent() << " error: (NSError *__autoreleasing *)__thriftError" << endl;
out << indent() << "{" << endl;
out << indent() << " NSString * messageName;" << endl;
- out << indent() << " int messageType;" << endl;
- out << indent() << " int seqID;" << endl;
- out << indent() << " [inProtocol readMessageBeginReturningName: &messageName" << endl;
+ out << indent() << " SInt32 messageType;" << endl;
+ out << indent() << " SInt32 seqID;" << endl;
+ out << indent() << " if (![inProtocol readMessageBeginReturningName: &messageName" << endl;
out << indent() << " type: &messageType" << endl;
- out << indent() << " sequenceID: &seqID];" << endl;
- out << indent() << " NSInvocation * invocation = [mMethodMap valueForKey: messageName];" << endl;
+ out << indent() << " sequenceID: &seqID" << endl;
+ out << indent() << " error: __thriftError]) return NO;" << endl;
+ out << indent() << " NSInvocation * invocation = [methodMap valueForKey: messageName];" << endl;
out << indent() << " if (invocation == nil) {" << endl;
- out << indent() << " [TProtocolUtil skipType: TType_STRUCT onProtocol: inProtocol];" << endl;
- out << indent() << " [inProtocol readMessageEnd];" << endl;
- out << indent() << " TApplicationException * x = [TApplicationException exceptionWithType: "
- "TApplicationException_UNKNOWN_METHOD reason: [NSString stringWithFormat: "
- "@\"Invalid method name: '%@'\", messageName]];" << endl;
- out << indent() << " [outProtocol writeMessageBeginWithName: messageName" << endl;
- out << indent() << " type: TMessageType_EXCEPTION" << endl;
- out << indent() << " sequenceID: seqID];" << endl;
- out << indent() << " [x write: outProtocol];" << endl;
- out << indent() << " [outProtocol writeMessageEnd];" << endl;
- out << indent() << " [[outProtocol transport] flush];" << endl;
+ out << indent() << " if (![TProtocolUtil skipType: TTypeSTRUCT onProtocol: inProtocol error: __thriftError]) return NO;" << endl;
+ out << indent() << " if (![inProtocol readMessageEnd: __thriftError]) return NO;" << endl;
+ out << indent() << " NSError * x = [NSError errorWithDomain: TApplicationErrorDomain" << endl;
+ out << indent() << " code: TApplicationErrorUnknownMethod" << endl;
+ out << indent() << " userInfo: @{TApplicationErrorMethodKey: messageName}];" << endl;
+ out << indent() << " if (![outProtocol writeMessageBeginWithName: messageName" << endl;
+ out << indent() << " type: TMessageTypeEXCEPTION" << endl;
+ out << indent() << " sequenceID: seqID" << endl;
+ out << indent() << " error: __thriftError]) return NO;" << endl;
+ out << indent() << " if (![x write: outProtocol error: __thriftError]) return NO;" << endl;
+ out << indent() << " if (![outProtocol writeMessageEnd: __thriftError]) return NO;" << endl;
+ out << indent() << " if (![[outProtocol transport] flush: __thriftError]) return NO;" << endl;
out << indent() << " return YES;" << endl;
out << indent() << " }" << endl;
out << indent() << " // NSInvocation does not conform to NSCopying protocol" << endl;
@@ -1754,6 +2046,7 @@
out << indent() << " [i setArgument: &seqID atIndex: 2];" << endl;
out << indent() << " [i setArgument: &inProtocol atIndex: 3];" << endl;
out << indent() << " [i setArgument: &outProtocol atIndex: 4];" << endl;
+ out << indent() << " [i setArgument: &__thriftError atIndex: 5];" << endl;
out << indent() << " [i setTarget: self];" << endl;
out << indent() << " [i invoke];" << endl;
out << indent() << " return YES;" << endl;
@@ -1765,27 +2058,35 @@
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
out << endl;
string funname = (*f_iter)->get_name();
- out << indent() << "- (void) process_" << funname
- << "_withSequenceID: (int32_t) seqID inProtocol: (id<TProtocol>) inProtocol outProtocol: "
- "(id<TProtocol>) outProtocol" << endl;
+ out << indent() << "- (BOOL) process_" << funname
+ << "_withSequenceID: (SInt32) seqID inProtocol: (id<TProtocol>) inProtocol outProtocol: "
+ "(id<TProtocol>) outProtocol error:(NSError *__autoreleasing *)__thriftError" << endl;
scope_up(out);
- string argstype = cocoa_prefix_ + function_args_helper_struct_type(*f_iter);
- out << indent() << argstype << " * args = [[" << argstype << " alloc] init];" << endl;
- out << indent() << "[args read: inProtocol];" << endl;
- out << indent() << "[inProtocol readMessageEnd];" << endl;
+ string argstype = cocoa_prefix_ + function_args_helper_struct_type(tservice, *f_iter);
+ out << indent() << argstype << " * args = [" << argstype << " new];" << endl;
+ out << indent() << "if (![args read: inProtocol error: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![inProtocol readMessageEnd: __thriftError]) return NO;" << endl;
// prepare the result if not oneway
if (!(*f_iter)->is_oneway()) {
- string resulttype = cocoa_prefix_ + function_result_helper_struct_type(*f_iter);
- out << indent() << resulttype << " * result = [[" << resulttype << " alloc] init];" << endl;
+ string resulttype = cocoa_prefix_ + function_result_helper_struct_type(tservice, *f_iter);
+ out << indent() << resulttype << " * result = [" << resulttype << " new];" << endl;
}
// make the call to the actual service object
out << indent();
- if (!(*f_iter)->get_returntype()->is_void()) {
- out << "[result setSuccess: ";
+ if ((*f_iter)->get_returntype()->is_void()) {
+ out << "BOOL";
+ } else if (type_can_be_null((*f_iter)->get_returntype())) {
+ out << type_name((*f_iter)->get_returntype(), false, true);
+ } else {
+ out << "NSNumber *";
}
- out << "[mService " << funname;
+ out << " serviceResult = ";
+ if ((*f_iter)->get_returntype()->get_true_type()->is_container()) {
+ out << "(" << type_name((*f_iter)->get_returntype(), false, true) << ")";
+ }
+ out << "[service " << funname;
// supplying arguments
t_struct* arg_struct = (*f_iter)->get_arglist();
const vector<t_field*>& fields = arg_struct->get_members();
@@ -1800,37 +2101,30 @@
out << " " << fieldName << ": [args " << fieldName << "]";
}
}
- out << "]";
- if (!(*f_iter)->get_returntype()->is_void()) {
- out << "]";
+ if (!fields.empty()) {
+ out << " error";
}
- out << ";" << endl;
-
+ out << ": __thriftError];" << endl;
+ out << indent() << "if (!serviceResult) return NO;" << endl;
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << indent() << "[result setSuccess: " << decontainerize((*f_iter)->get_returntype(), "serviceResult") << "];" << endl;
+ }
+
// write out the result if not oneway
if (!(*f_iter)->is_oneway()) {
- out << indent() << "[outProtocol writeMessageBeginWithName: @\"" << funname << "\"" << endl;
- out << indent() << " type: TMessageType_REPLY" << endl;
- out << indent() << " sequenceID: seqID];" << endl;
- out << indent() << "[result write: outProtocol];" << endl;
- out << indent() << "[outProtocol writeMessageEnd];" << endl;
- out << indent() << "[[outProtocol transport] flush];" << endl;
- out << indent() << "[result release_stub];" << endl;
+ out << indent() << "if (![outProtocol writeMessageBeginWithName: @\"" << funname << "\"" << endl;
+ out << indent() << " type: TMessageTypeREPLY" << endl;
+ out << indent() << " sequenceID: seqID" << endl;
+ out << indent() << " error: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![result write: outProtocol error: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![outProtocol writeMessageEnd: __thriftError]) return NO;" << endl;
+ out << indent() << "if (![[outProtocol transport] flush: __thriftError]) return NO;" << endl;
}
- out << indent() << "[args release_stub];" << endl;
+ out << indent() << "return YES;" << endl;
scope_down(out);
}
- // dealloc
- out << endl;
- out << "- (void) dealloc" << endl;
- scope_up(out);
- out << indent() << "[mService release_stub];" << endl;
- out << indent() << "[mMethodMap release_stub];" << endl;
- out << indent() << "[super dealloc_stub];" << endl;
- scope_down(out);
- out << endl;
-
out << "@end" << endl << endl;
}
@@ -1854,7 +2148,8 @@
} else if (type->is_container()) {
generate_deserialize_container(out, type, fieldName);
} else if (type->is_base_type() || type->is_enum()) {
- indent(out) << type_name(type) << " " << fieldName << " = [inProtocol ";
+ indent(out) << type_name(type) << " " << fieldName << ";" << endl;
+ indent(out) << "if (![inProtocol ";
if (type->is_base_type()) {
t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
@@ -1864,37 +2159,37 @@
break;
case t_base_type::TYPE_STRING:
if (((t_base_type*)type)->is_binary()) {
- out << "readBinary];";
+ out << "readBinary:&" << fieldName << " error: __thriftError]";
} else {
- out << "readString];";
+ out << "readString:&" << fieldName << " error: __thriftError]";
}
break;
case t_base_type::TYPE_BOOL:
- out << "readBool];";
+ out << "readBool:&" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_BYTE:
- out << "readByte];";
+ out << "readByte:(UInt8 *)&" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I16:
- out << "readI16];";
+ out << "readI16:&" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I32:
- out << "readI32];";
+ out << "readI32:&" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I64:
- out << "readI64];";
+ out << "readI64:&" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_DOUBLE:
- out << "readDouble];";
+ out << "readDouble:&" << fieldName << " error: __thriftError]";
break;
default:
throw "compiler error: no Objective-C name for base type "
+ t_base_type::t_base_name(tbase);
}
} else if (type->is_enum()) {
- out << "readI32];";
+ out << "readI32:&" << fieldName << " error: __thriftError]";
}
- out << endl;
+ out << ") return NO;" << endl;
} else {
printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
tfield->get_name().c_str(),
@@ -1910,7 +2205,7 @@
string fieldName) {
indent(out) << type_name(tstruct) << fieldName << " = [[" << type_name(tstruct, true)
<< " alloc] init];" << endl;
- indent(out) << "[" << fieldName << " read: inProtocol];" << endl;
+ indent(out) << "if (![" << fieldName << " read: inProtocol error: __thriftError]) return NO;" << endl;
}
/**
@@ -1920,21 +2215,20 @@
t_type* ttype,
string fieldName) {
string size = tmp("_size");
- indent(out) << "int " << size << ";" << endl;
+ indent(out) << "SInt32 " << size << ";" << endl;
// Declare variables, read header
if (ttype->is_map()) {
- indent(out) << "[inProtocol readMapBeginReturningKeyType: NULL valueType: NULL size: &" << size
- << "];" << endl;
+ indent(out) << "if (![inProtocol readMapBeginReturningKeyType: NULL valueType: NULL size: &" << size << " error: __thriftError]) return NO;" << endl;
indent(out) << "NSMutableDictionary * " << fieldName
<< " = [[NSMutableDictionary alloc] initWithCapacity: " << size << "];" << endl;
} else if (ttype->is_set()) {
- indent(out) << "[inProtocol readSetBeginReturningElementType: NULL size: &" << size << "];"
+ indent(out) << "if (![inProtocol readSetBeginReturningElementType: NULL size: &" << size << " error: __thriftError]) return NO;"
<< endl;
indent(out) << "NSMutableSet * " << fieldName
<< " = [[NSMutableSet alloc] initWithCapacity: " << size << "];" << endl;
} else if (ttype->is_list()) {
- indent(out) << "[inProtocol readListBeginReturningElementType: NULL size: &" << size << "];"
+ indent(out) << "if (![inProtocol readListBeginReturningElementType: NULL size: &" << size << " error: __thriftError]) return NO;"
<< endl;
indent(out) << "NSMutableArray * " << fieldName
<< " = [[NSMutableArray alloc] initWithCapacity: " << size << "];" << endl;
@@ -1963,11 +2257,11 @@
// Read container end
if (ttype->is_map()) {
- indent(out) << "[inProtocol readMapEnd];" << endl;
+ indent(out) << "if (![inProtocol readMapEnd: __thriftError]) return NO;" << endl;
} else if (ttype->is_set()) {
- indent(out) << "[inProtocol readSetEnd];" << endl;
+ indent(out) << "if (![inProtocol readSetEnd: __thriftError]) return NO;" << endl;
} else if (ttype->is_list()) {
- indent(out) << "[inProtocol readListEnd];" << endl;
+ indent(out) << "if (![inProtocol readListEnd: __thriftError]) return NO;" << endl;
}
}
@@ -1989,7 +2283,7 @@
case t_base_type::TYPE_BOOL:
return "[NSNumber numberWithBool: " + fieldName + "]";
case t_base_type::TYPE_BYTE:
- return "[NSNumber numberWithUnsignedChar: " + fieldName + "]";
+ return "[NSNumber numberWithChar: " + fieldName + "]";
case t_base_type::TYPE_I16:
return "[NSNumber numberWithShort: " + fieldName + "]";
case t_base_type::TYPE_I32:
@@ -2025,18 +2319,6 @@
indent(out) << "[" << fieldName << " setObject: " << containerize(valType, val)
<< " forKey: " << containerize(keyType, key) << "];" << endl;
-
- if (type_can_be_null(keyType)) {
- if (!(get_true_type(keyType)->is_string())) {
- indent(out) << "[" << containerize(keyType, key) << " release_stub];" << endl;
- }
- }
-
- if (type_can_be_null(valType)) {
- if (!(get_true_type(valType)->is_string())) {
- indent(out) << "[" << containerize(valType, val) << " release_stub];" << endl;
- }
- }
}
/**
@@ -2052,13 +2334,6 @@
generate_deserialize_field(out, &felem, elem);
indent(out) << "[" << fieldName << " addObject: " << containerize(type, elem) << "];" << endl;
-
- if (type_can_be_null(type)) {
- // deserialized strings are autorelease, so don't release them
- if (!(get_true_type(type)->is_string())) {
- indent(out) << "[" << containerize(type, elem) << " release_stub];" << endl;
- }
- }
}
/**
@@ -2074,12 +2349,6 @@
generate_deserialize_field(out, &felem, elem);
indent(out) << "[" << fieldName << " addObject: " << containerize(type, elem) << "];" << endl;
-
- if (type_can_be_null(type)) {
- if (!(get_true_type(type)->is_string())) {
- indent(out) << "[" << containerize(type, elem) << " release_stub];" << endl;
- }
- }
}
/**
@@ -2101,7 +2370,7 @@
} else if (type->is_container()) {
generate_serialize_container(out, type, fieldName);
} else if (type->is_base_type() || type->is_enum()) {
- indent(out) << "[outProtocol ";
+ indent(out) << "if (![outProtocol ";
if (type->is_base_type()) {
t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
@@ -2111,37 +2380,37 @@
break;
case t_base_type::TYPE_STRING:
if (((t_base_type*)type)->is_binary()) {
- out << "writeBinary: " << fieldName << "];";
+ out << "writeBinary: " << fieldName << " error: __thriftError]";
} else {
- out << "writeString: " << fieldName << "];";
+ out << "writeString: " << fieldName << " error: __thriftError]";
}
break;
case t_base_type::TYPE_BOOL:
- out << "writeBool: " << fieldName << "];";
+ out << "writeBool: " << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_BYTE:
- out << "writeByte: " << fieldName << "];";
+ out << "writeByte: (UInt8)" << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I16:
- out << "writeI16: " << fieldName << "];";
+ out << "writeI16: " << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I32:
- out << "writeI32: " << fieldName << "];";
+ out << "writeI32: " << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_I64:
- out << "writeI64: " << fieldName << "];";
+ out << "writeI64: " << fieldName << " error: __thriftError]";
break;
case t_base_type::TYPE_DOUBLE:
- out << "writeDouble: " << fieldName << "];";
+ out << "writeDouble: " << fieldName << " error: __thriftError]";
break;
default:
throw "compiler error: no Objective-C name for base type "
+ t_base_type::t_base_name(tbase);
}
} else if (type->is_enum()) {
- out << "writeI32: " << fieldName << "];";
+ out << "writeI32: " << fieldName << " error: __thriftError]";
}
- out << endl;
+ out << ") return NO;" << endl;
} else {
printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
tfield->get_name().c_str(),
@@ -2159,7 +2428,7 @@
t_struct* tstruct,
string fieldName) {
(void)tstruct;
- out << indent() << "[" << fieldName << " write: outProtocol];" << endl;
+ out << indent() << "if (![" << fieldName << " write: outProtocol error: __thriftError]) return NO;" << endl;
}
/**
@@ -2174,18 +2443,18 @@
scope_up(out);
if (ttype->is_map()) {
- indent(out) << "[outProtocol writeMapBeginWithKeyType: "
+ indent(out) << "if (![outProtocol writeMapBeginWithKeyType: "
<< type_to_enum(((t_map*)ttype)->get_key_type())
- << " valueType: " << type_to_enum(((t_map*)ttype)->get_val_type()) << " size: ["
- << fieldName << " count]];" << endl;
+ << " valueType: " << type_to_enum(((t_map*)ttype)->get_val_type()) << " size: (SInt32)["
+ << fieldName << " count] error: __thriftError]) return NO;" << endl;
} else if (ttype->is_set()) {
- indent(out) << "[outProtocol writeSetBeginWithElementType: "
- << type_to_enum(((t_set*)ttype)->get_elem_type()) << " size: [" << fieldName
- << " count]];" << endl;
+ indent(out) << "if (![outProtocol writeSetBeginWithElementType: "
+ << type_to_enum(((t_set*)ttype)->get_elem_type()) << " size: (SInt32)[" << fieldName
+ << " count] error: __thriftError]) return NO;" << endl;
} else if (ttype->is_list()) {
- indent(out) << "[outProtocol writeListBeginWithElementType: "
- << type_to_enum(((t_list*)ttype)->get_elem_type()) << " size: [" << fieldName
- << " count]];" << endl;
+ indent(out) << "if (![outProtocol writeListBeginWithElementType: "
+ << type_to_enum(((t_list*)ttype)->get_elem_type()) << " size: (SInt32)[" << fieldName
+ << " count] error: __thriftError]) return NO;" << endl;
}
string iter = tmp("_iter");
@@ -2221,11 +2490,11 @@
scope_down(out);
if (ttype->is_map()) {
- indent(out) << "[outProtocol writeMapEnd];" << endl;
+ indent(out) << "if (![outProtocol writeMapEnd: __thriftError]) return NO;" << endl;
} else if (ttype->is_set()) {
- indent(out) << "[outProtocol writeSetEnd];" << endl;
+ indent(out) << "if (![outProtocol writeSetEnd: __thriftError]) return NO;" << endl;
} else if (ttype->is_list()) {
- indent(out) << "[outProtocol writeListEnd];" << endl;
+ indent(out) << "if (![outProtocol writeListEnd: __thriftError]) return NO;" << endl;
}
scope_down(out);
@@ -2236,31 +2505,35 @@
* primitive type, if necessary.
*/
string t_cocoa_generator::decontainerize(t_field* tfield, string fieldName) {
- t_type* ttype = get_true_type(tfield->get_type());
+ return decontainerize(tfield->get_type(), fieldName);
+}
+
+string t_cocoa_generator::decontainerize(t_type* ttype, string fieldName) {
+ ttype = get_true_type(ttype);
if (ttype->is_enum()) {
return "[" + fieldName + " intValue]";
} else if (ttype->is_base_type()) {
t_base_type::t_base tbase = ((t_base_type*)ttype)->get_base();
switch (tbase) {
- case t_base_type::TYPE_VOID:
- throw "can't decontainerize void";
- case t_base_type::TYPE_BOOL:
- return "[" + fieldName + " boolValue]";
- case t_base_type::TYPE_BYTE:
- return "[" + fieldName + " unsignedCharValue]";
- case t_base_type::TYPE_I16:
- return "[" + fieldName + " shortValue]";
- case t_base_type::TYPE_I32:
- return "[" + fieldName + " longValue]";
- case t_base_type::TYPE_I64:
- return "[" + fieldName + " longLongValue]";
- case t_base_type::TYPE_DOUBLE:
- return "[" + fieldName + " doubleValue]";
- default:
- break;
+ case t_base_type::TYPE_VOID:
+ throw "can't decontainerize void";
+ case t_base_type::TYPE_BOOL:
+ return "[" + fieldName + " boolValue]";
+ case t_base_type::TYPE_BYTE:
+ return "((SInt8)[" + fieldName + " charValue])";
+ case t_base_type::TYPE_I16:
+ return "((SInt16)[" + fieldName + " shortValue])";
+ case t_base_type::TYPE_I32:
+ return "((SInt32)[" + fieldName + " longValue])";
+ case t_base_type::TYPE_I64:
+ return "((SInt64)[" + fieldName + " longLongValue])";
+ case t_base_type::TYPE_DOUBLE:
+ return "[" + fieldName + " doubleValue]";
+ default:
+ break;
}
}
-
+
// do nothing
return fieldName;
}
@@ -2304,25 +2577,32 @@
*
* @param ttype The type
* @param class_ref Do we want a Class reference istead of a type reference?
- * @return Java type name, i.e. HashMap<Key,Value>
+ * @return Objective-C type name, i.e. NSDictionary<Key,Value> *
*/
-string t_cocoa_generator::type_name(t_type* ttype, bool class_ref) {
+string t_cocoa_generator::type_name(t_type* ttype, bool class_ref, bool needs_mutable) {
if (ttype->is_typedef()) {
+ string name = (needs_mutable && ttype->get_true_type()->is_container()) ? "Mutable" + ttype->get_name() : ttype->get_name();
t_program* program = ttype->get_program();
- return program ? (program->get_namespace("cocoa") + ttype->get_name()) : ttype->get_name();
+ return program ? (program->get_namespace("cocoa") + name) : name;
}
string result;
if (ttype->is_base_type()) {
return base_type_name((t_base_type*)ttype);
} else if (ttype->is_enum()) {
- return "int";
+ return cocoa_prefix_ + ttype->get_name();
} else if (ttype->is_map()) {
- result = "NSMutableDictionary";
+ t_map *map = (t_map *)ttype;
+ result = needs_mutable ? "NSMutableDictionary" : "NSDictionary";
+ result += "<" + type_name(map->get_key_type()) + ", " + type_name(map->get_val_type()) + ">";
} else if (ttype->is_set()) {
- result = "NSMutableSet";
+ t_set *set = (t_set *)ttype;
+ result = needs_mutable ? "NSMutableSet" : "NSSet";
+ result += "<" + type_name(set->get_elem_type()) + ">";
} else if (ttype->is_list()) {
- result = "NSMutableArray";
+ t_list *list = (t_list *)ttype;
+ result = needs_mutable ? "NSMutableArray" : "NSArray";
+ result += "<" + type_name(list->get_elem_type()) + ">";
} else {
// Check for prefix
t_program* program = ttype->get_program();
@@ -2359,13 +2639,13 @@
case t_base_type::TYPE_BOOL:
return "BOOL";
case t_base_type::TYPE_BYTE:
- return "uint8_t";
+ return "SInt8";
case t_base_type::TYPE_I16:
- return "int16_t";
+ return "SInt16";
case t_base_type::TYPE_I32:
- return "int32_t";
+ return "SInt32";
case t_base_type::TYPE_I64:
- return "int64_t";
+ return "SInt64";
case t_base_type::TYPE_DOUBLE:
return "double";
default:
@@ -2404,10 +2684,10 @@
if (defval)
out << type_name(type) << " ";
if (defval || is_property)
- out << name << " = [[[" << type_name(type, true) << " alloc] init] autorelease_stub];"
+ out << name << " = [" << type_name(type, true) << " new];"
<< endl;
else
- out << name << " = [[" << type_name(type, true) << " alloc] init];" << endl;
+ out << name << " = [" << type_name(type, true) << " new];" << endl;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
t_type* field_type = NULL;
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
@@ -2429,12 +2709,8 @@
const map<t_const_value*, t_const_value*>& val = value->get_map();
map<t_const_value*, t_const_value*>::const_iterator v_iter;
if (defval)
- out << "NSMutableDictionary *";
- if (defval || is_property)
- out << name << " = [[[NSMutableDictionary alloc] initWithCapacity:" << val.size()
- << "] autorelease_stub]; " << endl;
- else
- out << name << " = [[NSMutableDictionary alloc] initWithCapacity:" << val.size() << "]; "
+ out << "NSMutableDictionary *"
+ << name << " = [[NSMutableDictionary alloc] initWithCapacity:" << val.size() << "]; "
<< endl;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
string key = render_const_value(out, ktype, v_iter->first, true);
@@ -2447,12 +2723,8 @@
const vector<t_const_value*>& val = value->get_list();
vector<t_const_value*>::const_iterator v_iter;
if (defval)
- out << "NSMutableArray *";
- if (defval || is_property)
- out << name << " = [[[NSMutableArray alloc] initWithCapacity:" << val.size()
- << "] autorelease_stub];" << endl;
- else
- out << name << " = [[NSMutableArray alloc] initWithCapacity:" << val.size() << "];" << endl;
+ out << "NSMutableArray *"
+ << name << " = [[NSMutableArray alloc] initWithCapacity:" << val.size() << "];" << endl;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
string val = render_const_value(out, etype, *v_iter, true);
indent(out) << "[" << name << " addObject:" << val << "];" << endl;
@@ -2463,12 +2735,8 @@
const vector<t_const_value*>& val = value->get_list();
vector<t_const_value*>::const_iterator v_iter;
if (defval)
- out << "NSMutableSet *";
- if (defval || is_property)
- out << name << " = [[[NSMutableSet alloc] initWithCapacity:" << val.size()
- << "] autorelease_stub];" << endl;
- else
- out << name << " = [[NSMutableSet alloc] initWithCapacity:" << val.size() << "];" << endl;
+ out << "NSMutableSet *"
+ << name << " = [[NSMutableSet alloc] initWithCapacity:" << val.size() << "];" << endl;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
string val = render_const_value(out, etype, *v_iter, true);
indent(out) << "[" << name << " addObject:" << val << "];" << endl;
@@ -2670,12 +2938,35 @@
#endif
/**
- * Declares a field.
+ * Declares an Objective-C 2.0 property.
*
- * @param ttype The type
+ * @param tfield The field to declare a property for
*/
-string t_cocoa_generator::declare_field(t_field* tfield) {
- return type_name(tfield->get_type()) + " __" + tfield->get_name() + ";";
+string t_cocoa_generator::declare_property(t_field* tfield) {
+ std::ostringstream render;
+ render << "@property (";
+
+ if (type_can_be_null(tfield->get_type())) {
+ render << "strong, ";
+ } else {
+ render << "assign, ";
+ }
+
+ render << "nonatomic) " << type_name(tfield->get_type(), false, true) << " "
+ << tfield->get_name() << ";";
+
+ // Check if the property name is an Objective-C return +1 count signal
+ if ((tfield->get_name().length() >= 3 && tfield->get_name().substr(0,3) == "new") ||
+ (tfield->get_name().length() >= 6 && tfield->get_name().substr(0,6) == "create") ||
+ (tfield->get_name().length() >= 5 && tfield->get_name().substr(0,5) == "alloc")) {
+ // Let Objective-C know not to return +1 for object pointers
+ if (type_can_be_null(tfield->get_type())) {
+ render << endl;
+ render << "- (" + type_name(tfield->get_type()) + ") " + decapitalize(tfield->get_name()) + " __attribute__((objc_method_family(none)));";
+ }
+ }
+
+ return render.str();
}
/**
@@ -2683,18 +2974,30 @@
*
* @param tfield The field to declare a property for
*/
-string t_cocoa_generator::declare_property(t_field* tfield) {
- std::ostringstream render;
- render << "@property (nonatomic, ";
+string t_cocoa_generator::declare_property_isset(t_field* tfield) {
+ return "@property (assign, nonatomic) BOOL " + decapitalize(tfield->get_name()) + "IsSet;";
+}
- if (type_can_be_null(tfield->get_type()))
- render << "retain, ";
+/**
+ * Declares property unset method.
+ *
+ * @param tfield The field to declare a property for
+ */
+string t_cocoa_generator::declare_property_unset(t_field* tfield) {
+ return "- (void) unset" + capitalize(tfield->get_name()) + ";";
+}
- render << "getter=" << decapitalize(tfield->get_name()) << ", setter=set"
- << capitalize(tfield->get_name()) + ":) " << type_name(tfield->get_type()) << " "
- << tfield->get_name() << ";";
-
- return render.str();
+/**
+ * Renders the early out return statement
+ *
+ * @param tfunction Function definition
+ * @return String of rendered invalid return statment
+ */
+string t_cocoa_generator::invalid_return_statement(t_function *tfunction) {
+ if ((tfunction->get_returntype()->is_void())) {
+ return "return NO;";
+ }
+ return "return nil;";
}
/**
@@ -2703,10 +3006,19 @@
* @param tfunction Function definition
* @return String of rendered function definition
*/
-string t_cocoa_generator::function_signature(t_function* tfunction) {
+string t_cocoa_generator::function_signature(t_function* tfunction, bool include_error) {
t_type* ttype = tfunction->get_returntype();
- std::string result = "(" + type_name(ttype) + ") " + tfunction->get_name()
- + argument_list(tfunction->get_arglist());
+ string result;
+ if (ttype->is_void()) {
+ result = "(BOOL)";
+ }
+ else if (type_can_be_null(ttype)) {
+ result = "(" + type_name(ttype) + ")";
+ }
+ else {
+ result = "(NSNumber *)";
+ }
+ result += " " + tfunction->get_name() + argument_list(tfunction->get_arglist(), "", include_error);
return result;
}
@@ -2717,26 +3029,35 @@
* @param tfunction Function definition
* @return String of rendered function definition
*/
-string t_cocoa_generator::async_function_signature(t_function* tfunction) {
+string t_cocoa_generator::async_function_signature(t_function* tfunction, bool include_error) {
t_type* ttype = tfunction->get_returntype();
t_struct* targlist = tfunction->get_arglist();
- std::string response_param = "dispatch_block_t";
- if (!ttype->is_void()) {
- response_param = "void (^)(" + type_name(ttype) + ")";
- }
- std::string result = "(void) " + tfunction->get_name() + argument_list(tfunction->get_arglist())
- + (targlist->get_members().size() ? " response" : "") + ": ("
- + response_param + ") responseBlock "
- + "failure : (TAsyncFailureBlock) failureBlock";
+ string response_param = "void (^)(" + ((ttype->is_void()) ? "" : type_name(ttype)) + ")";
+ std::string result = "(void) " + tfunction->get_name() + argument_list(tfunction->get_arglist(), "", include_error)
+ + (targlist->get_members().size() ? " response" : "") + ": ("
+ + response_param + ") responseBlock "
+ + "failure : (TAsyncFailureBlock) failureBlock";
return result;
}
/**
+ * Renders a function signature that returns a promise instead of
+ * literally returning.
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_cocoa_generator::promise_function_signature(t_function* tfunction) {
+ return "(AnyPromise *) " + tfunction->get_name() + argument_list(tfunction->get_arglist(), "", false);
+}
+
+/**
* Renders a colon separated list of types and names, suitable for an
* objective-c parameter list
*/
-string t_cocoa_generator::argument_list(t_struct* tstruct) {
+string t_cocoa_generator::argument_list(t_struct* tstruct, string protocol_name, bool include_error) {
string result = "";
+ bool include_protocol = !protocol_name.empty();
const vector<t_field*>& fields = tstruct->get_members();
vector<t_field*>::const_iterator f_iter;
@@ -2751,6 +3072,20 @@
}
result += argPrefix + ": (" + type_name((*f_iter)->get_type()) + ") " + (*f_iter)->get_name();
}
+ if (include_protocol) {
+ if (!first) {
+ result += " protocol";
+ }
+ result += ": (id<TProtocol>) " + protocol_name;
+ first = false;
+ }
+ if (include_error) {
+ if (!first) {
+ result += " error";
+ }
+ result += ": (NSError *__autoreleasing *)__thriftError";
+ first = false;
+ }
return result;
}
@@ -2766,30 +3101,30 @@
case t_base_type::TYPE_VOID:
throw "NO T_VOID CONSTRUCT";
case t_base_type::TYPE_STRING:
- return "TType_STRING";
+ return "TTypeSTRING";
case t_base_type::TYPE_BOOL:
- return "TType_BOOL";
+ return "TTypeBOOL";
case t_base_type::TYPE_BYTE:
- return "TType_BYTE";
+ return "TTypeBYTE";
case t_base_type::TYPE_I16:
- return "TType_I16";
+ return "TTypeI16";
case t_base_type::TYPE_I32:
- return "TType_I32";
+ return "TTypeI32";
case t_base_type::TYPE_I64:
- return "TType_I64";
+ return "TTypeI64";
case t_base_type::TYPE_DOUBLE:
- return "TType_DOUBLE";
+ return "TTypeDOUBLE";
}
} else if (type->is_enum()) {
- return "TType_I32";
+ return "TTypeI32";
} else if (type->is_struct() || type->is_xception()) {
- return "TType_STRUCT";
+ return "TTypeSTRUCT";
} else if (type->is_map()) {
- return "TType_MAP";
+ return "TTypeMAP";
} else if (type->is_set()) {
- return "TType_SET";
+ return "TTypeSET";
} else if (type->is_list()) {
- return "TType_LIST";
+ return "TTypeLIST";
}
throw "INVALID TYPE IN type_to_enum: " + type->get_name();
@@ -2837,6 +3172,47 @@
}
/**
+ * Returns a format cast for the supplied parse type.
+ */
+string t_cocoa_generator::format_cast_for_type(t_type* type) {
+ type = get_true_type(type);
+
+ if (type->is_base_type()) {
+ t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
+ switch (tbase) {
+ case t_base_type::TYPE_VOID:
+ throw "NO T_VOID CONSTRUCT";
+ case t_base_type::TYPE_STRING:
+ return ""; // "\\\"%@\\\"";
+ case t_base_type::TYPE_BOOL:
+ return ""; // "%i";
+ case t_base_type::TYPE_BYTE:
+ return ""; // "%i";
+ case t_base_type::TYPE_I16:
+ return ""; // "%hi";
+ case t_base_type::TYPE_I32:
+ return "(int)"; // "%i";
+ case t_base_type::TYPE_I64:
+ return ""; // "%qi";
+ case t_base_type::TYPE_DOUBLE:
+ return ""; // "%f";
+ }
+ } else if (type->is_enum()) {
+ return "(int)"; // "%i";
+ } else if (type->is_struct() || type->is_xception()) {
+ return ""; // "%@";
+ } else if (type->is_map()) {
+ return ""; // "%@";
+ } else if (type->is_set()) {
+ return ""; // "%@";
+ } else if (type->is_list()) {
+ return ""; // "%@";
+ }
+
+ throw "INVALID TYPE IN format_cast_for_type: " + type->get_name();
+}
+
+/**
* Generate a call to a field's setter.
*
* @param tfield Field the setter is being called on
@@ -2844,7 +3220,7 @@
*/
string t_cocoa_generator::call_field_setter(t_field* tfield, string fieldName) {
- return "[self set" + capitalize(tfield->get_name()) + ": " + fieldName + "];";
+ return "self." + tfield->get_name() + " = " + fieldName + ";";
}
THRIFT_REGISTER_GENERATOR(
@@ -2853,4 +3229,6 @@
" log_unexpected: Log every time an unexpected field ID or type is encountered.\n"
" validate_required:\n"
" Throws exception if any required field is not set.\n"
- " async_clients: Generate clients which invoke asynchronously via block syntax.\n")
+ " async_clients: Generate clients which invoke asynchronously via block syntax.\n"
+ " pods: Generate imports in Cocopods framework format.\n"
+ " promise_kit: Generate clients which invoke asynchronously via promises.\n")
diff --git a/compiler/cpp/src/generate/t_swift_generator.cc b/compiler/cpp/src/generate/t_swift_generator.cc
new file mode 100644
index 0000000..80f1c07
--- /dev/null
+++ b/compiler/cpp/src/generate/t_swift_generator.cc
@@ -0,0 +1,2145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <string>
+#include <fstream>
+#include <iostream>
+#include <vector>
+
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sstream>
+#include "t_oop_generator.h"
+#include "platform.h"
+
+using std::map;
+using std::ostream;
+using std::ofstream;
+using std::ostringstream;
+using std::string;
+using std::stringstream;
+using std::vector;
+
+static const string endl = "\n"; // avoid ostream << std::endl flushes
+
+/**
+ * Swift code generator.
+ *
+ * Designed from the Objective-C (aka Cocoa) generator.
+ */
+class t_swift_generator : public t_oop_generator {
+public:
+ t_swift_generator(t_program* program,
+ const map<string, string>& parsed_options,
+ const string& option_string)
+ : t_oop_generator(program) {
+ (void)option_string;
+ map<string, string>::const_iterator iter;
+
+ iter = parsed_options.find("log_unexpected");
+ log_unexpected_ = (iter != parsed_options.end());
+
+ iter = parsed_options.find("async_clients");
+ async_clients_ = (iter != parsed_options.end());
+
+ iter = parsed_options.find("promise_kit");
+ promise_kit_ = (iter != parsed_options.end());
+
+ iter = parsed_options.find("debug_descriptions");
+ debug_descriptions_ = (iter != parsed_options.end());
+
+ out_dir_base_ = "gen-swift";
+ }
+
+ /**
+ * Init and close methods
+ */
+
+ void init_generator();
+ void close_generator();
+
+ void generate_consts(vector<t_const*> consts);
+
+ /**
+ * Program-level generation functions
+ */
+
+ void generate_typedef(t_typedef* ttypedef);
+ void generate_enum(t_enum* tenum);
+ void generate_struct(t_struct* tstruct);
+ void generate_xception(t_struct* txception);
+ void generate_service(t_service* tservice);
+
+ void print_const_value(ostream& out,
+ string name,
+ t_type* type,
+ t_const_value* value,
+ bool defval = false,
+ bool is_property = false);
+ void render_const_value(ostream& out,
+ t_type* type,
+ t_const_value* value);
+
+ void generate_swift_struct(ofstream& out,
+ t_struct* tstruct,
+ bool is_private);
+ void generate_swift_struct_init(ofstream& out,
+ t_struct* tstruct,
+ bool all,
+ bool is_private);
+
+ void generate_swift_struct_implementation(ofstream& out,
+ t_struct* tstruct,
+ bool is_result,
+ bool is_private);
+ void generate_swift_struct_hashable_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_private);
+ void generate_swift_struct_equatable_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_private);
+ void generate_swift_struct_thrift_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_result,
+ bool is_private);
+ void generate_swift_struct_reader(ofstream& out, t_struct* tstruct, bool is_private);
+ void generate_swift_struct_writer(ofstream& out,t_struct* tstruct, bool is_private);
+ void generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct);
+ void generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct);
+
+ string function_result_helper_struct_type(t_service *tservice, t_function* tfunction);
+ string function_args_helper_struct_type(t_service* tservice, t_function* tfunction);
+ void generate_function_helpers(t_service *tservice, t_function* tfunction);
+
+ /**
+ * Service-level generation functions
+ */
+
+ void generate_swift_service_protocol(ofstream& out, t_service* tservice);
+ void generate_swift_service_protocol_async(ofstream& out, t_service* tservice);
+
+ void generate_swift_service_client(ofstream& out, t_service* tservice);
+ void generate_swift_service_client_async(ofstream& out, t_service* tservice);
+
+ void generate_swift_service_client_send_function_implementation(ofstream& out,
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol);
+ void generate_swift_service_client_send_function_invocation(ofstream& out, t_function* tfunction);
+ void generate_swift_service_client_send_async_function_invocation(ofstream& out,
+ t_function* tfunction);
+ void generate_swift_service_client_recv_function_implementation(ofstream& out,
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol);
+ void generate_swift_service_client_implementation(ofstream& out, t_service* tservice);
+ void generate_swift_service_client_async_implementation(ofstream& out, t_service* tservice);
+
+ void generate_swift_service_server(ofstream& out, t_service* tservice);
+ void generate_swift_service_server_implementation(ofstream& out, t_service* tservice);
+ void generate_swift_service_helpers(t_service* tservice);
+
+ /**
+ * Helper rendering functions
+ */
+
+ string swift_imports();
+ string swift_thrift_imports();
+ string type_name(t_type* ttype, bool is_optional=false, bool is_forced=false);
+ string base_type_name(t_base_type* tbase);
+ string declare_property(t_field* tfield, bool is_private);
+ string function_signature(t_function* tfunction);
+ string async_function_signature(t_function* tfunction);
+ string promise_function_signature(t_function* tfunction);
+ string function_name(t_function* tfunction);
+ string argument_list(t_struct* tstruct, string protocol_name, bool is_internal);
+ string type_to_enum(t_type* ttype, bool qualified=false);
+
+private:
+
+ void block_open(ostream& out) {
+ out << " {" << endl;
+ indent_up();
+ }
+
+ void block_close(ostream& out, bool end_line=true) {
+ indent_down();
+ indent(out) << "}";
+ if (end_line) out << endl;
+ }
+
+
+ bool field_is_optional(t_field* tfield) {
+ return tfield->get_req() == t_field::T_OPTIONAL;
+ }
+
+ bool struct_has_required_fields(t_struct* tstruct) {
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ if (!field_is_optional(*m_iter)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ bool struct_has_optional_fields(t_struct* tstruct) {
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ if (field_is_optional(*m_iter)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ string constants_declarations_;
+
+ /**
+ * File streams
+ */
+
+ ofstream f_decl_;
+ ofstream f_impl_;
+
+ bool log_unexpected_;
+ bool async_clients_;
+ bool promise_kit_;
+ bool debug_descriptions_;
+};
+
+/**
+ * Prepares for file generation by opening up the necessary file output
+ * streams.
+ */
+void t_swift_generator::init_generator() {
+ // Make output directory
+ MKDIR(get_out_dir().c_str());
+
+ // we have a .swift declarations file...
+ string f_decl_name = capitalize(program_name_) + ".swift";
+ string f_decl_fullname = get_out_dir() + f_decl_name;
+ f_decl_.open(f_decl_fullname.c_str());
+
+ f_decl_ << autogen_comment() << endl;
+
+ f_decl_ << swift_imports() << swift_thrift_imports() << endl;
+
+ // ...and a .swift implementation extensions file
+ string f_impl_name = capitalize(program_name_) + "+Exts.swift";
+ string f_impl_fullname = get_out_dir() + f_impl_name;
+ f_impl_.open(f_impl_fullname.c_str());
+
+ f_impl_ << autogen_comment() << endl;
+
+ f_impl_ << swift_imports() << swift_thrift_imports() << endl;
+
+}
+
+/**
+ * Prints standard Cocoa imports
+ *
+ * @return List of imports for Cocoa libraries
+ */
+string t_swift_generator::swift_imports() {
+
+ vector<string> includes_list;
+ includes_list.push_back("Foundation");
+
+ ostringstream includes;
+
+ vector<string>::const_iterator i_iter;
+ for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+ includes << "import " << *i_iter << endl;
+ }
+
+ includes << endl;
+
+ return includes.str();
+}
+
+/**
+ * Prints Thrift runtime imports
+ *
+ * @return List of imports necessary for Thrift runtime
+ */
+string t_swift_generator::swift_thrift_imports() {
+
+ vector<string> includes_list;
+ includes_list.push_back("Thrift");
+
+ if (promise_kit_) {
+ includes_list.push_back("PromiseKit");
+ }
+
+ ostringstream includes;
+
+ vector<string>::const_iterator i_iter;
+ for (i_iter=includes_list.begin(); i_iter!=includes_list.end(); ++i_iter) {
+ includes << "import " << *i_iter << endl;
+ }
+
+ includes << endl;
+
+ return includes.str();
+}
+
+/**
+ * Finish up generation.
+ */
+void t_swift_generator::close_generator() {
+ // stick our constants declarations at the end of the header file
+ // since they refer to things we are defining.
+ f_decl_ << constants_declarations_ << endl;
+}
+
+/**
+ * Generates a typedef. This is just a simple 1-liner in Swift
+ *
+ * @param ttypedef The type definition
+ */
+void t_swift_generator::generate_typedef(t_typedef* ttypedef) {
+ f_decl_ << indent() << "public typealias " << ttypedef->get_symbolic()
+ << " = " << type_name(ttypedef->get_type()) << endl;
+ f_decl_ << endl;
+}
+
+/**
+ * Generates code for an enumerated type. In Swift, this is
+ * essentially the same as the thrift definition itself, using
+ * Swift syntax.
+ *
+ * @param tenum The enumeration
+ */
+void t_swift_generator::generate_enum(t_enum* tenum) {
+ f_decl_ << indent() << "public enum " << tenum->get_name() << " : Int32";
+ block_open(f_decl_);
+
+ vector<t_enum_value*> constants = tenum->get_constants();
+ vector<t_enum_value*>::iterator c_iter;
+
+ for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
+ f_decl_ << indent() << "case " << (*c_iter)->get_name()
+ << " = " << (*c_iter)->get_value() << endl;
+ }
+
+ f_decl_ << endl;
+ f_decl_ << indent() << "public init() { self.init(rawValue: " << constants.front()->get_value() << ")! }" << endl;
+
+ block_close(f_decl_);
+ f_decl_ << endl;
+
+ f_impl_ << indent() << "extension " << tenum->get_name() << " : TEnum";
+ block_open(f_impl_);
+
+ f_impl_ << endl;
+
+ f_impl_ << indent() << "public static func readValueFromProtocol(proto: TProtocol) throws -> " << tenum->get_name();
+ block_open(f_impl_);
+ f_impl_ << indent() << "var raw = Int32()" << endl
+ << indent() << "try proto.readI32(&raw)" << endl
+ << indent() << "return " << tenum->get_name() << "(rawValue: raw)!" << endl;
+ block_close(f_impl_);
+ f_impl_ << endl;
+
+ f_impl_ << indent() << "public static func writeValue(value: " << tenum->get_name() << ", toProtocol proto: TProtocol) throws";
+ block_open(f_impl_);
+ f_impl_ << indent() << "try proto.writeI32(value.rawValue)" << endl;
+ block_close(f_impl_);
+ f_impl_ << endl;
+
+ block_close(f_impl_);
+ f_impl_ << endl;
+}
+
+/**
+ * Generates public constants for all Thrift constants.
+ *
+ * @param consts Constants to generate
+ */
+void t_swift_generator::generate_consts(vector<t_const*> consts) {
+
+ ostringstream const_interface;
+
+ // Public constants for base types & strings
+ vector<t_const*>::iterator c_iter;
+ for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
+ t_type* type = (*c_iter)->get_type();
+ const_interface << "public let " << capitalize((*c_iter)->get_name()) << " : " << type_name(type) << " = ";
+ render_const_value(const_interface, type, (*c_iter)->get_value());
+ const_interface << endl << endl;
+ }
+
+ // this gets spit into the header file in ::close_generator
+ constants_declarations_ = const_interface.str();
+
+}
+
+/**
+ * Generates a struct definition for a thrift data type. This is a struct
+ * with public members. Optional types are used for optional properties to
+ * allow them to be tested for availability. Separate inits are included for
+ * required properties & all properties.
+ *
+ * Generates extensions to provide conformance to TStruct, TSerializable,
+ * Hashable & Equatable
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_struct(t_struct* tstruct) {
+ generate_swift_struct(f_decl_, tstruct, false);
+ generate_swift_struct_implementation(f_impl_, tstruct, false, false);
+}
+
+/**
+ * Exceptions are structs, but they conform to ErrorType
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_xception(t_struct* txception) {
+ generate_swift_struct(f_decl_, txception, false);
+ generate_swift_struct_implementation(f_impl_, txception, false, false);
+}
+
+/**
+ * Generate the interface for a struct. Only properties and
+ * init methods are included.
+ *
+ * @param tstruct The struct definition
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct(ofstream& out,
+ t_struct* tstruct,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ out << indent() << visibility << " struct " << tstruct->get_name();
+
+ if (tstruct->is_xception()) {
+ out << " : ErrorType";
+ }
+
+ block_open(out);
+
+ // properties
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ out << endl;
+ out << indent() << declare_property(*m_iter, is_private) << endl;
+ }
+
+ out << endl;
+
+ // init
+
+ indent(out) << visibility << " init()";
+ block_open(out);
+ block_close(out);
+
+ out << endl;
+
+ if (struct_has_required_fields(tstruct)) {
+ generate_swift_struct_init(out, tstruct, false, is_private);
+ }
+ if (struct_has_optional_fields(tstruct)) {
+ generate_swift_struct_init(out, tstruct, true, is_private);
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generate struct init for properties
+ *
+ * @param tstruct The structure definition
+ * @param all Generate init with all or just required properties
+ * @param is_private
+ * Is the initializer public or private
+ */
+void t_swift_generator::generate_swift_struct_init(ofstream& out,
+ t_struct* tstruct,
+ bool all,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ indent(out) << visibility << " init(";
+
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ bool first=true;
+ for (m_iter = members.begin(); m_iter != members.end();) {
+ if (all || !field_is_optional(*m_iter)) {
+ if (first) {
+ first = false;
+ }
+ else {
+ out << ", ";
+ }
+ out << (*m_iter)->get_name() << ": " << type_name((*m_iter)->get_type(), field_is_optional(*m_iter));
+ }
+ ++m_iter;
+ }
+ out << ")";
+
+ block_open(out);
+
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ if (all || (*m_iter)->get_req() == t_field::T_REQUIRED || (*m_iter)->get_req() == t_field::T_OPT_IN_REQ_OUT) {
+ out << indent() << "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
+ }
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generate the hashable protocol implmentation
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_hashable_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ indent(out) << "extension " << tstruct->get_name() << " : Hashable";
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << visibility << " var hashValue : Int";
+
+ block_open(out);
+
+
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ if (!members.empty()) {
+ indent(out) << "let prime = 31" << endl;
+ indent(out) << "var result = 1" << endl;
+
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ t_field* tfield = *m_iter;
+ string accessor = field_is_optional(tfield) ? "?." : ".";
+ string defaultor = field_is_optional(tfield) ? " ?? 0" : "";
+ indent(out) << "result = prime * result + (" << tfield->get_name() << accessor << "hashValue" << defaultor << ")" << endl;
+ }
+
+ indent(out) << "return result" << endl;
+ }
+ else {
+ indent(out) << "return 31" << endl;
+ }
+
+ block_close(out);
+
+ out << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generate the equatable protocol implementation
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_equatable_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ indent(out) << visibility << " func ==(lhs: " << type_name(tstruct) << ", rhs: " << type_name(tstruct) << ") -> Bool";
+
+ block_open(out);
+
+ indent(out) << "return";
+
+ const vector<t_field*>& members = tstruct->get_members();
+ vector<t_field*>::const_iterator m_iter;
+
+ if (members.size()) {
+
+ out << endl;
+
+ indent_up();
+
+ for (m_iter = members.begin(); m_iter != members.end();) {
+ t_field* tfield = *m_iter;
+ indent(out) << "(lhs." << tfield->get_name() << " ?== rhs." << tfield->get_name() << ")";
+ if (++m_iter != members.end()) {
+ out << " &&";
+ }
+ out << endl;
+ }
+
+ indent_down();
+
+ }
+ else {
+ out << " true" << endl;
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generate struct implementation. Produces extensions that
+ * fulfill the requisite protocols to complete the value.
+ *
+ * @param tstruct The struct definition
+ * @param is_result
+ * If this is a result it needs a different writer
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_implementation(ofstream& out,
+ t_struct* tstruct,
+ bool is_result,
+ bool is_private) {
+
+ generate_swift_struct_equatable_extension(out, tstruct, is_private);
+
+ if (!is_private && !is_result) {
+ generate_swift_struct_printable_extension(out, tstruct);
+ }
+
+ generate_swift_struct_hashable_extension(out, tstruct, is_private);
+ generate_swift_struct_thrift_extension(out, tstruct, is_result, is_private);
+
+ out << endl << endl;
+}
+
+/**
+ * Generate the TStruct protocol implementation.
+ *
+ * @param tstruct The structure definition
+ * @param is_result
+ * Is the struct a result value
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_thrift_extension(ofstream& out,
+ t_struct* tstruct,
+ bool is_result,
+ bool is_private) {
+
+ indent(out) << "extension " << tstruct->get_name() << " : TStruct";
+
+ block_open(out);
+
+ out << endl;
+
+ generate_swift_struct_reader(out, tstruct, is_private);
+
+ if (is_result) {
+ generate_swift_struct_result_writer(out, tstruct);
+ }
+ else {
+ generate_swift_struct_writer(out, tstruct, is_private);
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a function to read a struct from
+ * from a protocol. (TStruct compliance)
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_reader(ofstream& out,
+ t_struct* tstruct,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ indent(out) << visibility << " static func readValueFromProtocol(__proto: TProtocol) throws -> "
+ << tstruct->get_name();
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "try __proto.readStructBegin()" << endl << endl;
+
+ const vector<t_field*>& fields = tstruct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ bool optional = field_is_optional(*f_iter);
+ indent(out) << "var " << (*f_iter)->get_name() << " : "
+ << type_name((*f_iter)->get_type(), optional, !optional) << endl;
+ }
+
+ out << endl;
+
+ // Loop over reading in fields
+ indent(out) << "fields: while true";
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "let (_, fieldType, fieldID) = try __proto.readFieldBegin()" << endl << endl;
+ indent(out) << "switch (fieldID, fieldType)";
+
+ block_open(out);
+
+ indent(out) << "case (_, .STOP):" << endl;
+ indent_up();
+ indent(out) << "break fields" << endl << endl;
+ indent_down();
+
+ // Generate deserialization code for known cases
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+
+ indent(out) << "case (" << (*f_iter)->get_key() << ", " << type_to_enum((*f_iter)->get_type()) << "):" << endl;
+ indent_up();
+ indent(out) << (*f_iter)->get_name() << " = try __proto.readValue() as " << type_name((*f_iter)->get_type()) << endl << endl;
+ indent_down();
+
+ }
+
+ indent(out) << "case let (_, unknownType):" << endl;
+ indent_up();
+ indent(out) << "try __proto.skipType(unknownType)" << endl;
+ indent_down();
+
+ block_close(out);
+
+ out << endl;
+
+ // Read field end marker
+ indent(out) << "try __proto.readFieldEnd()" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ indent(out) << "try __proto.readStructEnd()" << endl;
+
+ out << endl;
+
+ if (struct_has_required_fields(tstruct)) {
+ // performs various checks (e.g. check that all required fields are set)
+ indent(out) << "// Required fields" << endl;
+
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ if (field_is_optional(*f_iter)) {
+ continue;
+ }
+ indent(out) << "try __proto.validateValue(" << (*f_iter)->get_name() << ", "
+ << "named: \"" << (*f_iter)->get_name() << "\")" << endl;
+ }
+ }
+
+ out << endl;
+
+ indent(out) << "return " << tstruct->get_name() << "(";
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ out << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ }
+ out << ")" << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a function to write a struct to
+ * a protocol. (TStruct compliance)
+ *
+ * @param tstruct The structure definition
+ * @param is_private
+ * Is the struct public or private
+ */
+void t_swift_generator::generate_swift_struct_writer(ofstream& out,
+ t_struct* tstruct,
+ bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ indent(out) << visibility << " static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws";
+
+ block_open(out);
+
+ out << endl;
+
+ string name = tstruct->get_name();
+ const vector<t_field*>& fields = tstruct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl;
+
+ out << endl;
+
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ t_field *tfield = *f_iter;
+
+ bool optional = field_is_optional(tfield);
+ if (optional) {
+ indent(out) << "if let " << tfield->get_name() << " = __value." << tfield->get_name();
+ block_open(out);
+ }
+
+ indent(out) << "try __proto.writeFieldValue("
+ << (optional ? "" : "__value.") << tfield->get_name() << ", "
+ << "name: \"" << tfield->get_name() << "\", "
+ << "type: " << type_to_enum(tfield->get_type()) << ", "
+ << "id: " << tfield->get_key() << ")" << endl;
+
+ if (optional) {
+ block_close(out);
+ }
+
+ out << endl;
+ }
+
+ indent(out) << "try __proto.writeFieldStop()" << endl << endl;
+
+ indent(out) << "try __proto.writeStructEnd()" << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a function to read a struct from
+ * from a protocol. (TStruct compliance)
+ *
+ * This is specifically a function result. Only
+ * the first available field is written.
+ *
+ * @param tstruct The structure definition
+ */
+void t_swift_generator::generate_swift_struct_result_writer(ofstream& out, t_struct* tstruct) {
+
+ indent(out) << "private static func writeValue(__value: " << tstruct->get_name() << ", toProtocol __proto: TProtocol) throws";
+
+ block_open(out);
+
+ out << endl;
+
+ string name = tstruct->get_name();
+ const vector<t_field*>& fields = tstruct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ indent(out) << "try __proto.writeStructBeginWithName(\"" << name << "\")" << endl;
+
+ out << endl;
+
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ t_field *tfield = *f_iter;
+
+ indent(out) << "if let result = __value." << (*f_iter)->get_name();
+
+ block_open(out);
+
+ indent(out) << "try __proto.writeFieldValue(result, "
+ << "name: \"" << tfield->get_name() << "\", "
+ << "type: " << type_to_enum(tfield->get_type()) << ", "
+ << "id: " << tfield->get_key() << ")" << endl;
+
+ block_close(out);
+ }
+ // Write the struct map
+ indent(out) << "try __proto.writeFieldStop()" << endl << endl;
+
+ indent(out) << "try __proto.writeStructEnd()" << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a description method for the given struct
+ *
+ * @param tstruct The struct definition
+ */
+void t_swift_generator::generate_swift_struct_printable_extension(ofstream& out, t_struct* tstruct) {
+
+ // Allow use of debugDescription so the app can add description via a cateogory/extension
+
+ indent(out) << "extension " << tstruct->get_name() << " : "
+ << (debug_descriptions_ ? "CustomDebugStringConvertible" : "CustomStringConvertible");
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "public var description : String";
+
+ block_open(out);
+
+ indent(out) << "var desc = \"" << tstruct->get_name() << "(\"" << endl;
+
+ const vector<t_field*>& fields = tstruct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ indent(out) << "desc += \"" << (*f_iter)->get_name() << "=\\(self." << (*f_iter)->get_name() << ")";
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ out << "\"" << endl;
+ }
+ indent(out) << "desc += \")\"" << endl;
+ indent(out) << "return desc" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a thrift service. In Swift this consists of a
+ * protocol definition and a client (with it's implementation
+ * separated into exts file).
+ *
+ * @param tservice The service definition
+ */
+void t_swift_generator::generate_service(t_service* tservice) {
+
+ generate_swift_service_protocol(f_decl_, tservice);
+ generate_swift_service_client(f_decl_, tservice);
+ if (async_clients_) {
+ generate_swift_service_protocol_async(f_decl_, tservice);
+ generate_swift_service_client_async(f_decl_, tservice);
+ }
+ generate_swift_service_server(f_decl_, tservice);
+
+ generate_swift_service_helpers(tservice);
+
+ generate_swift_service_client_implementation(f_impl_, tservice);
+ if (async_clients_) {
+ generate_swift_service_client_async_implementation(f_impl_, tservice);
+ }
+ generate_swift_service_server_implementation(f_impl_, tservice);
+}
+
+/**
+ * Generates structs for all the service return types
+ *
+ * @param tservice The service
+ */
+void t_swift_generator::generate_swift_service_helpers(t_service* tservice) {
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::iterator f_iter;
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+ t_struct* ts = (*f_iter)->get_arglist();
+
+ string qname = function_args_helper_struct_type(tservice, *f_iter);
+
+ t_struct qname_ts = t_struct(ts->get_program(), qname);
+
+ const vector<t_field*>& members = ts->get_members();
+ vector<t_field*>::const_iterator m_iter;
+ for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
+ qname_ts.append(*m_iter);
+ }
+
+ generate_swift_struct(f_impl_, &qname_ts, true);
+ generate_swift_struct_implementation(f_impl_, &qname_ts, false, true);
+ generate_function_helpers(tservice, *f_iter);
+ }
+}
+
+string t_swift_generator::function_result_helper_struct_type(t_service *tservice, t_function* tfunction) {
+ if (tfunction->is_oneway()) {
+ return tservice->get_name() + "_" + tfunction->get_name();
+ } else {
+ return tservice->get_name() + "_" + tfunction->get_name() + "_result";
+ }
+}
+
+string t_swift_generator::function_args_helper_struct_type(t_service *tservice, t_function* tfunction) {
+ return tservice->get_name() + "_" + tfunction->get_name() + "_args";
+}
+
+/**
+ * Generates a struct and helpers for a function.
+ *
+ * @param tfunction The function
+ */
+void t_swift_generator::generate_function_helpers(t_service *tservice, t_function* tfunction) {
+ if (tfunction->is_oneway()) {
+ return;
+ }
+
+ // create a result struct with a success field of the return type,
+ // and a field for each type of exception thrown
+ t_struct result(program_, function_result_helper_struct_type(tservice, tfunction));
+ if (!tfunction->get_returntype()->is_void()) {
+ t_field* success = new t_field(tfunction->get_returntype(), "success", 0);
+ success->set_req(t_field::T_OPTIONAL);
+ result.append(success);
+ }
+
+ t_struct* xs = tfunction->get_xceptions();
+ const vector<t_field*>& fields = xs->get_members();
+ vector<t_field*>::const_iterator f_iter;
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ t_field *x = *f_iter;
+ t_field *ox = new t_field(x->get_type(), x->get_name(), x->get_key());
+ ox->set_req(t_field::T_OPTIONAL);
+ result.append(ox);
+ }
+
+ // generate the result struct
+ generate_swift_struct(f_impl_, &result, true);
+ generate_swift_struct_implementation(f_impl_, &result, true, true);
+
+ for (f_iter = result.get_members().begin(); f_iter != result.get_members().end(); ++f_iter) {
+ delete *f_iter;
+ }
+}
+
+/**
+ * Generates a service protocol definition.
+ *
+ * @param tservice The service to generate a protocol definition for
+ */
+void t_swift_generator::generate_swift_service_protocol(ofstream& out, t_service* tservice) {
+
+ indent(out) << "public protocol " << tservice->get_name();
+
+ block_open(out);
+
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::iterator f_iter;
+
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+ out << endl;
+ indent(out) << function_signature(*f_iter) << " // exceptions: ";
+ t_struct* xs = (*f_iter)->get_xceptions();
+ const vector<t_field*>& xceptions = xs->get_members();
+ vector<t_field*>::const_iterator x_iter;
+ for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
+ out << type_name((*x_iter)->get_type()) + ", ";
+ }
+ out << endl;
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates an asynchronous service protocol definition.
+ *
+ * @param tservice The service to generate a protocol definition for
+ */
+void t_swift_generator::generate_swift_service_protocol_async(ofstream& out, t_service* tservice) {
+
+ indent(out) << "public protocol " << tservice->get_name() << "Async";
+
+ block_open(out);
+
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::iterator f_iter;
+
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+ out << endl;
+ indent(out) << async_function_signature(*f_iter) << endl;
+ if (promise_kit_) {
+ indent(out) << promise_function_signature(*f_iter) << endl;
+ }
+ out << endl;
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a service client interface definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_client(ofstream& out,
+ t_service* tservice) {
+
+ indent(out) << "public class " << tservice->get_name() << "Client /* : " << tservice->get_name() << " */";
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "let __inProtocol : TProtocol" << endl << endl;
+
+ indent(out) << "let __outProtocol : TProtocol" << endl << endl;
+
+ indent(out) << "public init(inoutProtocol: TProtocol)";
+
+ block_open(out);
+
+ indent(out) << "__inProtocol = inoutProtocol" << endl;
+
+ indent(out) << "__outProtocol = inoutProtocol" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ indent(out) << "public init(inProtocol: TProtocol, outProtocol: TProtocol)";
+
+ block_open(out);
+
+ indent(out) << "__inProtocol = inProtocol" << endl;
+
+ indent(out) << "__outProtocol = outProtocol" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a service client interface definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_client_async(ofstream& out,
+ t_service* tservice) {
+
+ indent(out) << "public class " << tservice->get_name() << "AsyncClient /* : " << tservice->get_name() << " */";
+
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "let __protocolFactory : TProtocolFactory" << endl << endl;
+
+ indent(out) << "let __transportFactory : TAsyncTransportFactory" << endl << endl;
+
+ indent(out) << "public init(protocolFactory: TProtocolFactory, transportFactory: TAsyncTransportFactory)";
+
+ block_open(out);
+
+ indent(out) << "__protocolFactory = protocolFactory" << endl;
+
+ indent(out) << "__transportFactory = transportFactory" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a service server interface definition. In other words,
+ * the TProcess implementation for the service definition.
+ *
+ * @param tservice The service to generate a client interface definition for
+ */
+void t_swift_generator::generate_swift_service_server(ofstream& out,
+ t_service* tservice) {
+
+ indent(out) << "public class " << tservice->get_name() << "Processor : NSObject /* " << tservice->get_name() << " */";
+
+ block_open(out);
+
+ out << endl;
+
+ out << indent() << "typealias ProcessorHandlerDictionary = "
+ << "[String: (Int, TProtocol, TProtocol, " << tservice->get_name() << ") throws -> Void]" << endl
+ << endl
+ << indent() << "let service : " << tservice->get_name() << endl
+ << endl
+ << indent() << "public init(service: " << tservice->get_name() << ")";
+ block_open(out);
+ indent(out) << "self.service = service" << endl;
+ block_close(out);
+
+ out << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a function that will send the arguments
+ * for a service function via a protocol.
+ *
+ * @param tservice The service to generate
+ * @param tfunction The function to generate
+ * @param needs_protocol
+ * Wether the first parameter must be a protocol or if
+ * the protocol is to be assumed
+ */
+void t_swift_generator::generate_swift_service_client_send_function_implementation(ofstream& out,
+ t_service *tservice,
+ t_function* tfunction,
+ bool needs_protocol) {
+
+ string funname = tfunction->get_name();
+
+ t_function send_function(g_type_bool,
+ "send_" + tfunction->get_name(),
+ tfunction->get_arglist());
+
+ string argsname = function_args_helper_struct_type(tservice, tfunction);
+ t_struct* arg_struct = tfunction->get_arglist();
+
+ // Open function
+ indent(out) << "private func " << send_function.get_name() << "(" << argument_list(tfunction->get_arglist(), needs_protocol ? "__outProtocol" : "", true) << ") throws";
+ block_open(out);
+
+ out << endl;
+
+ // Serialize the request
+ indent(out) << "try __outProtocol.writeMessageBeginWithName(\"" << funname << "\", "
+ << "type: " << (tfunction->is_oneway() ? ".ONEWAY" : ".CALL") << ", "
+ << "sequenceID: 0)" << endl;
+
+ out << endl;
+
+ indent(out) << "let __args = " << argsname << "(";
+
+ // write out function parameters
+
+ const vector<t_field*>& fields = arg_struct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ t_field *tfield = (*f_iter);
+ out << tfield->get_name() << ": " << tfield->get_name();
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ }
+ out << ")" << endl;
+ indent(out) << "try " << argsname << ".writeValue(__args, toProtocol: __outProtocol)" << endl << endl;
+
+ indent(out) << "try __outProtocol.writeMessageEnd()" << endl;
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a function that will recv the result for a
+ * service function via a protocol.
+ *
+ * @param tservice The service to generate
+ * @param tfunction The function to generate
+ * @param needs_protocol
+ * Wether the first parameter must be a protocol or if
+ * the protocol is to be assumed
+ */
+void t_swift_generator::generate_swift_service_client_recv_function_implementation(ofstream& out,
+ t_service* tservice,
+ t_function* tfunction,
+ bool needs_protocol) {
+
+ // Open function
+ indent(out) << "private func recv_" << tfunction->get_name() << "(";
+
+ if (needs_protocol) {
+ out << "__inProtocol: TProtocol";
+ }
+
+ out << ") throws";
+
+ if (!tfunction->get_returntype()->is_void()) {
+ out << " -> " << type_name(tfunction->get_returntype());
+ }
+
+ block_open(out);
+
+ // check for an exception
+
+ out << endl;
+
+ indent(out) << "try __inProtocol.readResultMessageBegin() " << endl << endl;
+
+ string resultname = function_result_helper_struct_type(tservice, tfunction);
+ indent(out);
+ if (!tfunction->get_returntype()->is_void() || !tfunction->get_xceptions()->get_members().empty()) {
+ out << "let __result = ";
+ }
+ out << "try " << resultname << ".readValueFromProtocol(__inProtocol)" << endl << endl;
+
+ indent(out) << "try __inProtocol.readMessageEnd()" << endl << endl;
+
+ // Careful, only return _result if not a void function
+ if (!tfunction->get_returntype()->is_void()) {
+ indent(out) << "if let __success = __result.success";
+ block_open(out);
+ indent(out) << "return __success" << endl;
+ block_close(out);
+ }
+
+ t_struct* xs = tfunction->get_xceptions();
+ const vector<t_field*>& xceptions = xs->get_members();
+ vector<t_field*>::const_iterator x_iter;
+
+ for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
+ indent(out) << "if let " << (*x_iter)->get_name() << " = __result." << (*x_iter)->get_name();
+ block_open(out);
+ indent(out) << "throw " << (*x_iter)->get_name() << endl;
+ block_close(out);
+ }
+
+ // If you get here it's an exception, unless a void function
+ if (!tfunction->get_returntype()->is_void()) {
+ indent(out) << "throw NSError(" << endl;
+ indent_up();
+ indent(out) << "domain: TApplicationErrorDomain, " << endl;
+ indent(out) << "code: Int(TApplicationError.MissingResult.rawValue)," << endl;
+ indent(out) << "userInfo: [TApplicationErrorMethodKey: \"" << tfunction->get_name() << "\"])" << endl;
+ indent_down();
+ }
+
+ // Close function
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates an invocation of a given the send function for the
+ * service function.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_send_function_invocation(ofstream& out,
+ t_function* tfunction) {
+
+ indent(out) << "try send_" << tfunction->get_name() << "(";
+
+ t_struct* arg_struct = tfunction->get_arglist();
+
+ const vector<t_field*>& fields = arg_struct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ out << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ }
+
+ out << ")" << endl;
+}
+
+/**
+ * Generates an invocation of a given the send function for the
+ * service function. This is for asynchronous protocols.
+ *
+ * @param tfunction The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_send_async_function_invocation(ofstream& out,
+ t_function* tfunction) {
+
+ t_struct* arg_struct = tfunction->get_arglist();
+ const vector<t_field*>& fields = arg_struct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ indent(out) << "try send_" << tfunction->get_name() << "(__protocol";
+
+ for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
+ out << ", " << (*f_iter)->get_name() << ": " << (*f_iter)->get_name();
+ }
+
+ out << ")" << endl;
+}
+
+/**
+ * Generates a service client protocol implementation via extension.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_implementation(ofstream& out,
+ t_service* tservice) {
+
+ string name = tservice->get_name() + "Client";
+
+ indent(out) << "extension " << name << " : " << tservice->get_name();
+
+ block_open(out);
+
+ out << endl;
+
+ // generate client method implementations
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::const_iterator f_iter;
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+ generate_swift_service_client_send_function_implementation(out, tservice, *f_iter, false);
+
+ if (!(*f_iter)->is_oneway()) {
+ generate_swift_service_client_recv_function_implementation(out, tservice, *f_iter, false);
+ }
+
+ // Open function
+ indent(out) << "public " << function_signature(*f_iter);
+
+ block_open(out);
+
+ out << endl;
+
+ generate_swift_service_client_send_function_invocation(out, *f_iter);
+
+ out << endl;
+
+ indent(out) << "try __outProtocol.transport().flush()" << endl << endl;
+
+ if (!(*f_iter)->is_oneway()) {
+ if ((*f_iter)->get_returntype()->is_void()) {
+ indent(out) << "try recv_" << (*f_iter)->get_name() << "()" << endl;
+ } else {
+ indent(out) << "return try recv_" << (*f_iter)->get_name() << "()" << endl;
+ }
+ }
+
+ block_close(out);
+
+ out << endl;
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a service asynchronous client protocol implementation via extension.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_client_async_implementation(ofstream& out,
+ t_service* tservice) {
+
+ string name = tservice->get_name() + "AsyncClient";
+ string protocol_name = tservice->get_name() + "Async";
+
+ indent(out) << "extension " << name << " : " << protocol_name;
+
+ block_open(out);
+
+ out << endl;
+
+ // generate client method implementations
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::const_iterator f_iter;
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+ generate_swift_service_client_send_function_implementation(out, tservice, *f_iter, true);
+
+ if (!(*f_iter)->is_oneway()) {
+ generate_swift_service_client_recv_function_implementation(out, tservice, *f_iter, true);
+ }
+
+ indent(out) << "public " << async_function_signature(*f_iter);
+ block_open(out);
+
+ out << endl;
+
+ out << indent() << "let __transport = __transportFactory.newTransport()" << endl
+ << indent() << "let __protocol = __protocolFactory.newProtocolOnTransport(__transport)" << endl
+ << endl;
+
+ generate_swift_service_client_send_async_function_invocation(out, *f_iter);
+
+ out << endl;
+
+ indent(out) << "__transport.flushWithCompletion(";
+
+ if ((*f_iter)->is_oneway()) {
+ out << "success, failure: failure)" << endl;
+ }
+ else {
+ block_open(out);
+ indent(out) << "do";
+ block_open(out);
+
+ indent(out);
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << "let result = ";
+ }
+ out << "try self.recv_" << (*f_iter)->get_name() << "(__protocol)" << endl;
+
+ out << indent() << "success(";
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << "result";
+ }
+ out << ")" << endl;
+
+ block_close(out);
+ indent(out) << "catch let error";
+ block_open(out);
+ indent(out) << "failure(error as NSError)" << endl;
+ block_close(out);
+ block_close(out);
+ indent(out) << ", failure: failure)" << endl;
+ }
+
+
+ block_close(out);
+
+ out << endl;
+
+ // Promise function
+ if (promise_kit_) {
+
+ indent(out) << "public " << promise_function_signature(*f_iter);
+ block_open(out);
+
+ out << indent() << "let (__promise, __fulfill, __reject) = Promise<" << type_name((*f_iter)->get_returntype()) << ">.pendingPromise()" << endl << endl
+ << indent() << "let __transport = __transportFactory.newTransport()" << endl
+ << indent() << "let __protocol = __protocolFactory.newProtocolOnTransport(__transport)" << endl
+ << endl;
+
+ generate_swift_service_client_send_async_function_invocation(out, *f_iter);
+
+ out << endl;
+
+ indent(out) << "__transport.flushWithCompletion(";
+
+ if ((*f_iter)->is_oneway()) {
+ out << "{ __fulfill() }, failure: { __reject($0) })" << endl;
+ }
+ else {
+ block_open(out);
+ indent(out) << "do";
+ block_open(out);
+
+ indent(out);
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << "let result = ";
+ }
+ out << "try self.recv_" << (*f_iter)->get_name() << "(__protocol)" << endl;
+
+ out << indent() << "__fulfill(";
+ if (!(*f_iter)->get_returntype()->is_void()) {
+ out << "result";
+ }
+ out << ")" << endl;
+
+ block_close(out);
+ indent(out) << "catch let error";
+ block_open(out);
+ indent(out) << "__reject(error)" << endl;
+ block_close(out);
+ block_close(out);
+
+ indent(out) << ", failure: { error in " << endl;
+ indent_up();
+ indent(out) << "__reject(error)" << endl;
+ indent_down();
+ indent(out) << "})" << endl;
+ }
+
+ indent(out) << "return __promise" << endl;
+
+ block_close(out);
+
+ out << endl;
+
+ }
+
+ }
+
+ block_close(out);
+
+ out << endl;
+}
+
+/**
+ * Generates a service server implementation.
+ *
+ * Implemented by generating a block for each service function that
+ * handles the processing of that function. The blocks are stored in
+ * a map and looked up via function/message name.
+ *
+ * @param tservice The service to generate an implementation for
+ */
+void t_swift_generator::generate_swift_service_server_implementation(ofstream& out,
+ t_service* tservice) {
+
+ string name = tservice->get_name() + "Processor";
+
+ indent(out) << "extension " << name << " : TProcessor";
+ block_open(out);
+
+ out << endl;
+
+ indent(out) << "static let processorHandlers : ProcessorHandlerDictionary =";
+ block_open(out);
+
+ out << endl;
+
+ out << indent() << "var processorHandlers = ProcessorHandlerDictionary()" << endl << endl;
+
+ // generate method map for routing incoming calls
+ vector<t_function*> functions = tservice->get_functions();
+ vector<t_function*>::const_iterator f_iter;
+ for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
+
+ t_function* tfunction = *f_iter;
+
+ string args_type = function_args_helper_struct_type(tservice, *f_iter);
+
+ out << indent() << "processorHandlers[\"" << tfunction->get_name() << "\"] = { sequenceID, inProtocol, outProtocol, handler in" << endl
+ << endl;
+
+ indent_up();
+ out << indent() << "let args = try " << args_type << ".readValueFromProtocol(inProtocol)" << endl
+ << endl
+ << indent() << "try inProtocol.readMessageEnd()" << endl
+ << endl;
+
+ if (!tfunction->is_oneway() ) {
+ string result_type = function_result_helper_struct_type(tservice, tfunction);
+ indent(out) << "var result = " << result_type << "()" << endl;
+
+ indent(out) << "do";
+ block_open(out);
+
+ indent(out);
+ if (!tfunction->get_returntype()->is_void()) {
+ out << "result.success = ";
+ }
+ out << "try handler." << function_name(tfunction) << "(";
+
+ t_struct* arg_struct = tfunction->get_arglist();
+ const vector<t_field*>& fields = arg_struct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ string fieldName = (*f_iter)->get_name();
+ if (f_iter != fields.begin()) {
+ out << fieldName << ": ";
+ }
+ out << "args." << fieldName;
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ }
+
+ out << ")" << endl;
+
+ block_close(out);
+
+ t_struct* xs = tfunction->get_xceptions();
+ const vector<t_field*>& xfields = xs->get_members();
+ vector<t_field*>::const_iterator x_iter;
+
+ for (x_iter = xfields.begin(); x_iter != xfields.end(); ++x_iter) {
+ indent(out) << "catch let error as " << (*x_iter)->get_type()->get_name();
+ block_open(out);
+ indent(out) << "result." << (*x_iter)->get_name() << " = error" << endl;
+ block_close(out);
+ }
+
+ indent(out) << "catch let error";
+ block_open(out);
+ out << indent() << "throw error" << endl;
+ block_close(out);
+
+ out << endl;
+
+ if (!tfunction->is_oneway()) {
+ out << indent() << "try outProtocol.writeMessageBeginWithName(\"" << tfunction->get_name() << "\", type: .REPLY, sequenceID: sequenceID)" << endl
+ << indent() << "try " << result_type << ".writeValue(result, toProtocol: outProtocol)" << endl
+ << indent() << "try outProtocol.writeMessageEnd()" << endl;
+ }
+ }
+ block_close(out);
+
+ }
+
+ indent(out) << "return processorHandlers" << endl;
+
+ block_close(out,false);
+ out << "()" << endl;
+
+ out << endl;
+
+ indent(out) << "public func processOnInputProtocol(inProtocol: TProtocol, outputProtocol outProtocol: TProtocol) throws";
+ block_open(out);
+
+ out << endl;
+
+ out << indent() << "let (messageName, _, sequenceID) = try inProtocol.readMessageBegin()" << endl
+ << endl
+ << indent() << "if let processorHandler = " << name << ".processorHandlers[messageName]";
+ block_open(out);
+ out << indent() << "do";
+ block_open(out);
+ out << indent() << "try processorHandler(sequenceID, inProtocol, outProtocol, service)" << endl;
+ block_close(out);
+ out << indent() << "catch let error as NSError";
+ block_open(out);
+ out << indent() << "try outProtocol.writeExceptionForMessageName(messageName, sequenceID: sequenceID, ex: error)" << endl;
+ block_close(out);
+ block_close(out);
+ out << indent() << "else";
+ block_open(out);
+ out << indent() << "try inProtocol.skipType(.STRUCT)" << endl
+ << indent() << "try inProtocol.readMessageEnd()" << endl
+ << indent() << "try outProtocol.writeExceptionForMessageName(messageName," << endl;
+ indent_up();
+ out << indent() << "sequenceID: sequenceID," << endl
+ << indent() << "ex: NSError(" << endl;
+ indent_up();
+ out << indent() << "domain: TApplicationErrorDomain, " << endl
+ << indent() << "code: Int(TApplicationError.UnknownMethod.rawValue), " << endl
+ << indent() << "userInfo: [TApplicationErrorMethodKey: messageName]))" << endl;
+ indent_down();
+ indent_down();
+ block_close(out);
+
+ block_close(out);
+
+ block_close(out);
+ out << endl;
+}
+
+/**
+ * Returns an Swift name
+ *
+ * @param ttype The type
+ * @param class_ref Do we want a Class reference istead of a type reference?
+ * @return Swift type name, i.e. Dictionary<Key,Value>
+ */
+string t_swift_generator::type_name(t_type* ttype, bool is_optional, bool is_forced) {
+ string result;
+ if (ttype->is_base_type()) {
+ result = base_type_name((t_base_type*)ttype);
+ } else if (ttype->is_map()) {
+ t_map *map = (t_map *)ttype;
+ result = "TMap<" + type_name(map->get_key_type()) + ", " + type_name(map->get_val_type()) + ">";
+ } else if (ttype->is_set()) {
+ t_set *set = (t_set *)ttype;
+ result = "TSet<" + type_name(set->get_elem_type()) + ">";
+ } else if (ttype->is_list()) {
+ t_list *list = (t_list *)ttype;
+ result = "TList<" + type_name(list->get_elem_type()) + ">";
+ }
+ else {
+ result = ttype->get_name();
+ }
+
+ if (is_optional) {
+ result += "?";
+ }
+
+ if (is_forced) {
+ result += "!";
+ }
+
+ return result;
+}
+
+/**
+ * Returns the Swift type that corresponds to the thrift type.
+ *
+ * @param tbase The base type
+ */
+string t_swift_generator::base_type_name(t_base_type* type) {
+ t_base_type::t_base tbase = type->get_base();
+
+ switch (tbase) {
+ case t_base_type::TYPE_VOID:
+ return "Void";
+ case t_base_type::TYPE_STRING:
+ if (type->is_binary()) {
+ return "TBinary";
+ } else {
+ return "String";
+ }
+ case t_base_type::TYPE_BOOL:
+ return "Bool";
+ case t_base_type::TYPE_BYTE:
+ return "Int8";
+ case t_base_type::TYPE_I16:
+ return "Int16";
+ case t_base_type::TYPE_I32:
+ return "Int32";
+ case t_base_type::TYPE_I64:
+ return "Int64";
+ case t_base_type::TYPE_DOUBLE:
+ return "Double";
+ default:
+ throw "compiler error: no Swift name for base type " + t_base_type::t_base_name(tbase);
+ }
+}
+
+/**
+ * Renders full constant value (as would be seen after an '=')
+ *
+ */
+void t_swift_generator::render_const_value(ostream& out,
+ t_type* type,
+ t_const_value* value) {
+ type = get_true_type(type);
+
+ if (type->is_base_type()) {
+ t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
+ switch (tbase) {
+ case t_base_type::TYPE_STRING:
+ out << "\"" << get_escaped_string(value) << "\"";
+ break;
+ case t_base_type::TYPE_BOOL:
+ out << ((value->get_integer() > 0) ? "true" : "false");
+ break;
+ case t_base_type::TYPE_BYTE:
+ case t_base_type::TYPE_I16:
+ case t_base_type::TYPE_I32:
+ case t_base_type::TYPE_I64:
+ out << type_name(type) << "(" << value->get_integer() << ")";
+ break;
+ case t_base_type::TYPE_DOUBLE:
+ out << type_name(type) << "(";
+ if (value->get_type() == t_const_value::CV_INTEGER) {
+ out << value->get_integer();
+ } else {
+ out << value->get_double();
+ }
+ out << ")";
+ break;
+ default:
+ throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
+ }
+ } else if (type->is_enum()) {
+ out << value->get_identifier();
+ } else if (type->is_struct() || type->is_xception()) {
+
+ out << type_name(type) << "(";
+
+ const vector<t_field*>& fields = ((t_struct*)type)->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ const map<t_const_value*, t_const_value*>& val = value->get_map();
+ map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ t_field* tfield = *f_iter;
+ t_const_value* value = NULL;
+ for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
+ if (tfield->get_name() == v_iter->first->get_string()) {
+ value = v_iter->second;
+ }
+ }
+
+ if (value) {
+ out << tfield->get_name() << ": ";
+ render_const_value(out, tfield->get_type(), value);
+ }
+ else if (!field_is_optional(tfield)) {
+ throw "constant error: required field " + type->get_name() + "." + tfield->get_name() + " has no value";
+ }
+
+ if (++f_iter != fields.end()) {
+ out << ", ";
+ }
+ }
+
+ out << ")";
+
+ } else if (type->is_map()) {
+
+ out << "[";
+
+ t_type* ktype = ((t_map*)type)->get_key_type();
+ t_type* vtype = ((t_map*)type)->get_val_type();
+
+ const map<t_const_value*, t_const_value*>& val = value->get_map();
+ map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+ for (v_iter = val.begin(); v_iter != val.end();) {
+
+ render_const_value(out, ktype, v_iter->first);
+ out << ": ";
+ render_const_value(out, vtype, v_iter->second);
+
+ if (++v_iter != val.end()) {
+ out << ", ";
+ }
+ }
+
+ out << "]";
+
+ } else if (type->is_list()) {
+
+ out << "[";
+
+ t_type* etype = ((t_list*)type)->get_elem_type();
+
+ const map<t_const_value*, t_const_value*>& val = value->get_map();
+ map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+ for (v_iter = val.begin(); v_iter != val.end();) {
+
+ render_const_value(out, etype, v_iter->first);
+
+ if (++v_iter != val.end()) {
+ out << ", ";
+ }
+ }
+
+ out << "]";
+
+ } else if (type->is_set()) {
+
+ out << "[";
+
+ t_type* etype = ((t_set*)type)->get_elem_type();
+
+ const map<t_const_value*, t_const_value*>& val = value->get_map();
+ map<t_const_value*, t_const_value*>::const_iterator v_iter;
+
+ for (v_iter = val.begin(); v_iter != val.end();) {
+
+ render_const_value(out, etype, v_iter->first);
+
+ if (++v_iter != val.end()) {
+ out << ", ";
+ }
+ }
+
+ out << "]";
+
+ } else {
+ throw "compiler error: no const of type " + type->get_name();
+ }
+
+}
+
+/**
+ * Declares an Swift property.
+ *
+ * @param tfield The field to declare a property for
+ */
+string t_swift_generator::declare_property(t_field* tfield, bool is_private) {
+
+ string visibility = is_private ? "private" : "public";
+
+ ostringstream render;
+
+ render << visibility << " var " << tfield->get_name();
+
+ if (field_is_optional(tfield)) {
+ render << " : " << type_name(tfield->get_type(), true);
+ }
+ else {
+ render << " = " << type_name(tfield->get_type(), false) << "()";
+ }
+
+ return render.str();
+}
+
+/**
+ * Renders a function signature
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::function_signature(t_function* tfunction) {
+
+ string result = "func " + function_name(tfunction);
+
+ result += "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws";
+
+ t_type* ttype = tfunction->get_returntype();
+ if (!ttype->is_void()) {
+ result += " -> " + type_name(ttype);
+ }
+
+ return result;
+}
+
+/**
+ * Renders a function signature that returns asynchronously via blocks.
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::async_function_signature(t_function* tfunction) {
+ t_type* ttype = tfunction->get_returntype();
+ t_struct* targlist = tfunction->get_arglist();
+ string response_param = "(" + ((ttype->is_void()) ? "" : type_name(ttype)) + ") -> Void";
+ string result = "func " + function_name(tfunction);
+ result += "(" + argument_list(tfunction->get_arglist(), "", false)
+ + (targlist->get_members().size() ? ", " : "")
+ + "success: " + response_param + ", "
+ + "failure: (NSError) -> Void) throws";
+ return result;
+}
+
+/**
+ * Renders a function signature that returns asynchronously via promises.
+ *
+ * @param tfunction Function definition
+ * @return String of rendered function definition
+ */
+string t_swift_generator::promise_function_signature(t_function* tfunction) {
+ return "func " + function_name(tfunction) + "(" + argument_list(tfunction->get_arglist(), "", false) + ") throws "
+ + "-> Promise<" + type_name(tfunction->get_returntype()) + ">";
+}
+
+/**
+ * Renders a verbose function name suitable for a Swift method
+ */
+string t_swift_generator::function_name(t_function* tfunction) {
+ string name = tfunction->get_name();
+ if (!tfunction->get_arglist()->get_members().empty()) {
+ string first_arg = tfunction->get_arglist()->get_members().front()->get_name();
+ if (name.size() < first_arg.size() ||
+ lowercase(name.substr(name.size()-first_arg.size())) != lowercase(first_arg)) {
+ name += "With" + capitalize(tfunction->get_arglist()->get_members()[0]->get_name());
+ }
+ }
+ return name;
+}
+
+/**
+ * Renders a Swift method argument list
+ */
+string t_swift_generator::argument_list(t_struct* tstruct, string protocol_name, bool is_internal) {
+ string result = "";
+ bool include_protocol = !protocol_name.empty();
+
+ const vector<t_field*>& fields = tstruct->get_members();
+ vector<t_field*>::const_iterator f_iter;
+
+ if (include_protocol) {
+ result += protocol_name + ": TProtocol";
+ if (!fields.empty()) {
+ result += ", ";
+ }
+ }
+ else if (!fields.empty() && is_internal) {
+ // Force first argument to be named
+ result += fields.front()->get_name() + " ";
+ }
+
+ for (f_iter = fields.begin(); f_iter != fields.end();) {
+ t_field* arg = *f_iter;
+ result += arg->get_name() + ": " + type_name(arg->get_type());
+
+ if (++f_iter != fields.end()) {
+ result += ", ";
+ }
+ }
+ return result;
+}
+
+/**
+ * Converts the parse type to a Swift TType enumeration.
+ */
+string t_swift_generator::type_to_enum(t_type* type, bool qualified) {
+ type = get_true_type(type);
+
+ string result = qualified ? "TType." : ".";
+
+ if (type->is_base_type()) {
+ t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
+ switch (tbase) {
+ case t_base_type::TYPE_VOID:
+ throw "NO T_VOID CONSTRUCT";
+ case t_base_type::TYPE_STRING:
+ return result + "STRING";
+ case t_base_type::TYPE_BOOL:
+ return result + "BOOL";
+ case t_base_type::TYPE_BYTE:
+ return result + "BYTE";
+ case t_base_type::TYPE_I16:
+ return result + "I16";
+ case t_base_type::TYPE_I32:
+ return result + "I32";
+ case t_base_type::TYPE_I64:
+ return result + "I64";
+ case t_base_type::TYPE_DOUBLE:
+ return result + "DOUBLE";
+ }
+ } else if (type->is_enum()) {
+ return result + "I32";
+ } else if (type->is_struct() || type->is_xception()) {
+ return result + "STRUCT";
+ } else if (type->is_map()) {
+ return result + "MAP";
+ } else if (type->is_set()) {
+ return result + "SET";
+ } else if (type->is_list()) {
+ return result + "LIST";
+ }
+
+ throw "INVALID TYPE IN type_to_enum: " + type->get_name();
+}
+
+
+THRIFT_REGISTER_GENERATOR(
+ swift,
+ "Swift",
+ " log_unexpected: Log every time an unexpected field ID or type is encountered.\n"
+ " async_clients: Generate clients which invoke asynchronously via block syntax.\n"
+ " promise_kit: Generate clients which invoke asynchronously via promises.\n")