-
Notifications
You must be signed in to change notification settings - Fork 4k
/
t_py_generator.cc
2437 lines (2114 loc) · 83.1 KB
/
t_py_generator.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 <sys/types.h>
#include <sstream>
#include <algorithm>
#include "t_generator.h"
#include "platform.h"
#include "version.h"
using std::map;
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
/**
* Python code generator.
*
*/
class t_py_generator : public t_generator {
public:
t_py_generator(t_program* program,
const std::map<std::string, std::string>& parsed_options,
const std::string& option_string)
: t_generator(program) {
(void)option_string;
std::map<std::string, std::string>::const_iterator iter;
iter = parsed_options.find("new_style");
gen_newstyle_ = (iter != parsed_options.end());
iter = parsed_options.find("slots");
gen_slots_ = (iter != parsed_options.end());
iter = parsed_options.find("dynamic");
gen_dynamic_ = (iter != parsed_options.end());
if (gen_dynamic_) {
gen_newstyle_ = 0; // dynamic is newstyle
gen_dynbaseclass_ = "TBase";
gen_dynbaseclass_exc_ = "TExceptionBase";
import_dynbase_ = "from thrift.protocol.TBase import TBase, TExceptionBase\n";
}
iter = parsed_options.find("dynbase");
if (iter != parsed_options.end()) {
gen_dynbase_ = true;
gen_dynbaseclass_ = (iter->second);
}
iter = parsed_options.find("dynexc");
if (iter != parsed_options.end()) {
gen_dynbaseclass_exc_ = (iter->second);
}
iter = parsed_options.find("dynimport");
if (iter != parsed_options.end()) {
gen_dynbase_ = true;
import_dynbase_ = (iter->second);
}
iter = parsed_options.find("twisted");
gen_twisted_ = (iter != parsed_options.end());
iter = parsed_options.find("tornado");
gen_tornado_ = (iter != parsed_options.end());
if (gen_twisted_ && gen_tornado_) {
throw "at most one of 'twisted' and 'tornado' are allowed";
}
iter = parsed_options.find("utf8strings");
gen_utf8strings_ = (iter != parsed_options.end());
copy_options_ = option_string;
if (gen_twisted_) {
out_dir_base_ = "gen-py.twisted";
} else if (gen_tornado_) {
out_dir_base_ = "gen-py.tornado";
} else {
out_dir_base_ = "gen-py";
}
}
/**
* Init and close methods
*/
void init_generator();
void close_generator();
/**
* Program-level generation functions
*/
void generate_typedef(t_typedef* ttypedef);
void generate_enum(t_enum* tenum);
void generate_const(t_const* tconst);
void generate_struct(t_struct* tstruct);
void generate_xception(t_struct* txception);
void generate_service(t_service* tservice);
std::string render_const_value(t_type* type, t_const_value* value);
/**
* Struct generation code
*/
void generate_py_struct(t_struct* tstruct, bool is_exception);
void generate_py_struct_definition(std::ofstream& out,
t_struct* tstruct,
bool is_xception = false,
bool is_result = false);
void generate_py_struct_reader(std::ofstream& out, t_struct* tstruct);
void generate_py_struct_writer(std::ofstream& out, t_struct* tstruct);
void generate_py_struct_required_validator(std::ofstream& out, t_struct* tstruct);
void generate_py_function_helpers(t_function* tfunction);
/**
* Service-level generation functions
*/
void generate_service_helpers(t_service* tservice);
void generate_service_interface(t_service* tservice);
void generate_service_client(t_service* tservice);
void generate_service_remote(t_service* tservice);
void generate_service_server(t_service* tservice);
void generate_process_function(t_service* tservice, t_function* tfunction);
/**
* Serialization constructs
*/
void generate_deserialize_field(std::ofstream& out,
t_field* tfield,
std::string prefix = "",
bool inclass = false);
void generate_deserialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = "");
void generate_deserialize_container(std::ofstream& out, t_type* ttype, std::string prefix = "");
void generate_deserialize_set_element(std::ofstream& out, t_set* tset, std::string prefix = "");
void generate_deserialize_map_element(std::ofstream& out, t_map* tmap, std::string prefix = "");
void generate_deserialize_list_element(std::ofstream& out,
t_list* tlist,
std::string prefix = "");
void generate_serialize_field(std::ofstream& out, t_field* tfield, std::string prefix = "");
void generate_serialize_struct(std::ofstream& out, t_struct* tstruct, std::string prefix = "");
void generate_serialize_container(std::ofstream& out, t_type* ttype, std::string prefix = "");
void generate_serialize_map_element(std::ofstream& out,
t_map* tmap,
std::string kiter,
std::string viter);
void generate_serialize_set_element(std::ofstream& out, t_set* tmap, std::string iter);
void generate_serialize_list_element(std::ofstream& out, t_list* tlist, std::string iter);
void generate_python_docstring(std::ofstream& out, t_struct* tstruct);
void generate_python_docstring(std::ofstream& out, t_function* tfunction);
void generate_python_docstring(std::ofstream& out,
t_doc* tdoc,
t_struct* tstruct,
const char* subheader);
void generate_python_docstring(std::ofstream& out, t_doc* tdoc);
/**
* Helper rendering functions
*/
std::string py_autogen_comment();
std::string py_imports();
std::string render_includes();
std::string render_fastbinary_includes();
std::string declare_argument(t_field* tfield);
std::string render_field_default_value(t_field* tfield);
std::string type_name(t_type* ttype);
std::string function_signature(t_function* tfunction, bool interface = false);
std::string argument_list(t_struct* tstruct,
std::vector<std::string>* pre = NULL,
std::vector<std::string>* post = NULL);
std::string type_to_enum(t_type* ttype);
std::string type_to_spec_args(t_type* ttype);
static bool is_valid_namespace(const std::string& sub_namespace) {
return sub_namespace == "twisted";
}
static std::string get_real_py_module(const t_program* program, bool gen_twisted) {
if (gen_twisted) {
std::string twisted_module = program->get_namespace("py.twisted");
if (!twisted_module.empty()) {
return twisted_module;
}
}
std::string real_module = program->get_namespace("py");
if (real_module.empty()) {
return program->get_name();
}
return real_module;
}
private:
/**
* True if we should generate new-style classes.
*/
bool gen_newstyle_;
/**
* True if we should generate dynamic style classes.
*/
bool gen_dynamic_;
bool gen_dynbase_;
std::string gen_dynbaseclass_;
std::string gen_dynbaseclass_exc_;
std::string import_dynbase_;
bool gen_slots_;
std::string copy_options_;
/**
* True if we should generate Twisted-friendly RPC services.
*/
bool gen_twisted_;
/**
* True if we should generate code for use with Tornado
*/
bool gen_tornado_;
/**
* True if strings should be encoded using utf-8.
*/
bool gen_utf8strings_;
/**
* File streams
*/
std::ofstream f_types_;
std::ofstream f_consts_;
std::ofstream f_service_;
std::string package_dir_;
std::string module_;
};
/**
* Prepares for file generation by opening up the necessary file output
* streams.
*
* @param tprogram The program to generate
*/
void t_py_generator::init_generator() {
// Make output directory
string module = get_real_py_module(program_, gen_twisted_);
package_dir_ = get_out_dir();
module_ = module;
while (true) {
// TODO: Do better error checking here.
MKDIR(package_dir_.c_str());
std::ofstream init_py((package_dir_ + "/__init__.py").c_str(), std::ios_base::app);
init_py.close();
if (module.empty()) {
break;
}
string::size_type pos = module.find('.');
if (pos == string::npos) {
package_dir_ += "/";
package_dir_ += module;
module.clear();
} else {
package_dir_ += "/";
package_dir_ += module.substr(0, pos);
module.erase(0, pos + 1);
}
}
// Make output file
string f_types_name = package_dir_ + "/" + "ttypes.py";
f_types_.open(f_types_name.c_str());
string f_consts_name = package_dir_ + "/" + "constants.py";
f_consts_.open(f_consts_name.c_str());
string f_init_name = package_dir_ + "/__init__.py";
ofstream f_init;
f_init.open(f_init_name.c_str());
f_init << "__all__ = ['ttypes', 'constants'";
vector<t_service*> services = program_->get_services();
vector<t_service*>::iterator sv_iter;
for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) {
f_init << ", '" << (*sv_iter)->get_name() << "'";
}
f_init << "]" << endl;
f_init.close();
// Print header
f_types_ << py_autogen_comment() << endl << py_imports() << endl << render_includes() << endl
<< render_fastbinary_includes() << endl << endl;
f_consts_ << py_autogen_comment() << endl << py_imports() << endl << "from ttypes import *"
<< endl << endl;
}
/**
* Renders all the imports necessary for including another Thrift program
*/
string t_py_generator::render_includes() {
const vector<t_program*>& includes = program_->get_includes();
string result = "";
for (size_t i = 0; i < includes.size(); ++i) {
result += "import " + get_real_py_module(includes[i], gen_twisted_) + ".ttypes\n";
}
if (includes.size() > 0) {
result += "\n";
}
return result;
}
/**
* Renders all the imports necessary to use the accelerated TBinaryProtocol
*/
string t_py_generator::render_fastbinary_includes() {
string hdr = "";
if (gen_dynamic_) {
hdr += std::string(import_dynbase_);
} else {
hdr += "from thrift.transport import TTransport\n"
"from thrift.protocol import TBinaryProtocol, TProtocol\n"
"try:\n"
" from thrift.protocol import fastbinary\n"
"except:\n"
" fastbinary = None\n";
}
return hdr;
}
/**
* Autogen'd comment
*/
string t_py_generator::py_autogen_comment() {
return std::string("#\n") + "# Autogenerated by Thrift Compiler (" + THRIFT_VERSION + ")\n"
+ "#\n" + "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" + "#\n"
+ "# options string: " + copy_options_ + "\n" + "#\n";
}
/**
* Prints standard thrift imports
*/
string t_py_generator::py_imports() {
return string("from thrift.Thrift import TType, TMessageType, TException, TApplicationException");
}
/**
* Closes the type files
*/
void t_py_generator::close_generator() {
// Close types file
f_types_.close();
f_consts_.close();
}
/**
* Generates a typedef. This is not done in Python, types are all implicit.
*
* @param ttypedef The type definition
*/
void t_py_generator::generate_typedef(t_typedef* ttypedef) {
(void)ttypedef;
}
/**
* Generates code for an enumerated type. Done using a class to scope
* the values.
*
* @param tenum The enumeration
*/
void t_py_generator::generate_enum(t_enum* tenum) {
std::ostringstream to_string_mapping, from_string_mapping;
f_types_ << "class " << tenum->get_name() << (gen_newstyle_ ? "(object)" : "")
<< (gen_dynamic_ ? "(" + gen_dynbaseclass_ + ")" : "") << ":" << endl;
indent_up();
generate_python_docstring(f_types_, tenum);
to_string_mapping << indent() << "_VALUES_TO_NAMES = {" << endl;
from_string_mapping << indent() << "_NAMES_TO_VALUES = {" << endl;
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) {
int value = (*c_iter)->get_value();
indent(f_types_) << (*c_iter)->get_name() << " = " << value << endl;
// Dictionaries to/from string names of enums
to_string_mapping << indent() << indent() << value << ": \""
<< escape_string((*c_iter)->get_name()) << "\"," << endl;
from_string_mapping << indent() << indent() << '"' << escape_string((*c_iter)->get_name())
<< "\": " << value << ',' << endl;
}
to_string_mapping << indent() << "}" << endl;
from_string_mapping << indent() << "}" << endl;
indent_down();
f_types_ << endl;
f_types_ << to_string_mapping.str() << endl << from_string_mapping.str() << endl;
}
/**
* Generate a constant value
*/
void t_py_generator::generate_const(t_const* tconst) {
t_type* type = tconst->get_type();
string name = tconst->get_name();
t_const_value* value = tconst->get_value();
indent(f_consts_) << name << " = " << render_const_value(type, value);
f_consts_ << endl;
}
/**
* Prints the value of a constant with the given type. Note that type checking
* is NOT performed in this function as it is always run beforehand using the
* validate_types method in main.cc
*/
string t_py_generator::render_const_value(t_type* type, t_const_value* value) {
type = get_true_type(type);
std::ostringstream out;
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 << value->get_integer();
break;
case t_base_type::TYPE_DOUBLE:
if (value->get_type() == t_const_value::CV_INTEGER) {
out << value->get_integer();
} else {
out << value->get_double();
}
break;
default:
throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
}
} else if (type->is_enum()) {
indent(out) << value->get_integer();
} else if (type->is_struct() || type->is_xception()) {
out << type_name(type) << "(**{" << endl;
indent_up();
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 (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) {
if ((*f_iter)->get_name() == v_iter->first->get_string()) {
field_type = (*f_iter)->get_type();
}
}
if (field_type == NULL) {
throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
}
out << indent();
out << render_const_value(g_type_string, v_iter->first);
out << " : ";
out << render_const_value(field_type, v_iter->second);
out << "," << endl;
}
indent_down();
indent(out) << "})";
} else if (type->is_map()) {
t_type* ktype = ((t_map*)type)->get_key_type();
t_type* vtype = ((t_map*)type)->get_val_type();
out << "{" << endl;
indent_up();
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(); ++v_iter) {
out << indent();
out << render_const_value(ktype, v_iter->first);
out << " : ";
out << render_const_value(vtype, v_iter->second);
out << "," << endl;
}
indent_down();
indent(out) << "}";
} else if (type->is_list() || type->is_set()) {
t_type* etype;
if (type->is_list()) {
etype = ((t_list*)type)->get_elem_type();
} else {
etype = ((t_set*)type)->get_elem_type();
}
if (type->is_set()) {
out << "set(";
}
out << "[" << endl;
indent_up();
const vector<t_const_value*>& val = value->get_list();
vector<t_const_value*>::const_iterator v_iter;
for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
out << indent();
out << render_const_value(etype, *v_iter);
out << "," << endl;
}
indent_down();
indent(out) << "]";
if (type->is_set()) {
out << ")";
}
} else {
throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
}
return out.str();
}
/**
* Generates a python struct
*/
void t_py_generator::generate_struct(t_struct* tstruct) {
generate_py_struct(tstruct, false);
}
/**
* Generates a struct definition for a thrift exception. Basically the same
* as a struct but extends the Exception class.
*
* @param txception The struct definition
*/
void t_py_generator::generate_xception(t_struct* txception) {
generate_py_struct(txception, true);
}
/**
* Generates a python struct
*/
void t_py_generator::generate_py_struct(t_struct* tstruct, bool is_exception) {
generate_py_struct_definition(f_types_, tstruct, is_exception);
}
/**
* Generates a struct definition for a thrift data type.
*
* @param tstruct The struct definition
*/
void t_py_generator::generate_py_struct_definition(ofstream& out,
t_struct* tstruct,
bool is_exception,
bool is_result) {
(void)is_result;
const vector<t_field*>& members = tstruct->get_members();
const vector<t_field*>& sorted_members = tstruct->get_sorted_members();
vector<t_field*>::const_iterator m_iter;
out << std::endl << "class " << tstruct->get_name();
if (is_exception) {
if (gen_dynamic_) {
out << "(" << gen_dynbaseclass_exc_ << ")";
} else {
out << "(TException)";
}
} else {
if (gen_newstyle_) {
out << "(object)";
} else if (gen_dynamic_) {
out << "(" << gen_dynbaseclass_ << ")";
}
}
out << ":" << endl;
indent_up();
generate_python_docstring(out, tstruct);
out << endl;
/*
Here we generate the structure specification for the fastbinary codec.
These specifications have the following structure:
thrift_spec -> tuple of item_spec
item_spec -> None | (tag, type_enum, name, spec_args, default)
tag -> integer
type_enum -> TType.I32 | TType.STRING | TType.STRUCT | ...
name -> string_literal
default -> None # Handled by __init__
spec_args -> None # For simple types
| (type_enum, spec_args) # Value type for list/set
| (type_enum, spec_args, type_enum, spec_args)
# Key and value for map
| (class_name, spec_args_ptr) # For struct/exception
class_name -> identifier # Basically a pointer to the class
spec_args_ptr -> expression # just class_name.spec_args
TODO(dreiss): Consider making this work for structs with negative tags.
*/
if (gen_slots_) {
indent(out) << "__slots__ = [ " << endl;
indent_up();
for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
indent(out) << "'" << (*m_iter)->get_name() << "'," << endl;
}
indent_down();
indent(out) << " ]" << endl << endl;
}
// TODO(dreiss): Look into generating an empty tuple instead of None
// for structures with no members.
// TODO(dreiss): Test encoding of structs where some inner structs
// don't have thrift_spec.
if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
indent(out) << "thrift_spec = (" << endl;
indent_up();
int sorted_keys_pos = 0;
for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
indent(out) << "None, # " << sorted_keys_pos << endl;
}
indent(out) << "(" << (*m_iter)->get_key() << ", " << type_to_enum((*m_iter)->get_type())
<< ", "
<< "'" << (*m_iter)->get_name() << "'"
<< ", " << type_to_spec_args((*m_iter)->get_type()) << ", "
<< render_field_default_value(*m_iter) << ", "
<< "),"
<< " # " << sorted_keys_pos << endl;
sorted_keys_pos++;
}
indent_down();
indent(out) << ")" << endl << endl;
} else {
indent(out) << "thrift_spec = None" << endl;
}
if (members.size() > 0) {
out << indent() << "def __init__(self,";
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
// This fills in default values, as opposed to nulls
out << " " << declare_argument(*m_iter) << ",";
}
out << "):" << endl;
indent_up();
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
// Initialize fields
t_type* type = (*m_iter)->get_type();
if (!type->is_base_type() && !type->is_enum() && (*m_iter)->get_value() != NULL) {
indent(out) << "if " << (*m_iter)->get_name() << " is "
<< "self.thrift_spec[" << (*m_iter)->get_key() << "][4]:" << endl;
indent(out) << " " << (*m_iter)->get_name() << " = " << render_field_default_value(*m_iter)
<< endl;
}
indent(out) << "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
}
indent_down();
out << endl;
}
if (!gen_dynamic_) {
generate_py_struct_reader(out, tstruct);
generate_py_struct_writer(out, tstruct);
}
// For exceptions only, generate a __str__ method. This is
// because when raised exceptions are printed to the console, __repr__
// isn't used. See python bug #5882
if (is_exception) {
out << indent() << "def __str__(self):" << endl << indent() << " return repr(self)" << endl
<< endl;
}
out << indent() << "def __hash__(self):" << endl;
indent_up();
indent(out) << "value = 17" << endl; // PYTHONHASHSEED would be better, but requires Python 3.2.3
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
indent(out) << "value = (value * 31) ^ hash(self." << (*m_iter)->get_name() + ")" << endl;
}
indent(out) << "return value" << endl;
indent_down();
out << endl;
if (!gen_slots_) {
// Printing utilities so that on the command line thrift
// structs look pretty like dictionaries
out << indent() << "def __repr__(self):" << endl << indent() << " L = ['%s=%r' % (key, value)"
<< endl << indent() << " for key, value in self.__dict__.iteritems()]" << endl
<< indent() << " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl
<< endl;
// Equality and inequality methods that compare by value
out << indent() << "def __eq__(self, other):" << endl;
indent_up();
out << indent() << "return isinstance(other, self.__class__) and "
"self.__dict__ == other.__dict__" << endl;
indent_down();
out << endl;
out << indent() << "def __ne__(self, other):" << endl;
indent_up();
out << indent() << "return not (self == other)" << endl;
indent_down();
} else if (!gen_dynamic_) {
// no base class available to implement __eq__ and __repr__ and __ne__ for us
// so we must provide one that uses __slots__
out << indent() << "def __repr__(self):" << endl << indent()
<< " L = ['%s=%r' % (key, getattr(self, key))" << endl << indent()
<< " for key in self.__slots__]" << endl << indent()
<< " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl << endl;
// Equality method that compares each attribute by value and type, walking __slots__
out << indent() << "def __eq__(self, other):" << endl << indent()
<< " if not isinstance(other, self.__class__):" << endl << indent() << " return False"
<< endl << indent() << " for attr in self.__slots__:" << endl << indent()
<< " my_val = getattr(self, attr)" << endl << indent()
<< " other_val = getattr(other, attr)" << endl << indent()
<< " if my_val != other_val:" << endl << indent() << " return False" << endl
<< indent() << " return True" << endl << endl;
out << indent() << "def __ne__(self, other):" << endl << indent()
<< " return not (self == other)" << endl << endl;
}
indent_down();
}
/**
* Generates the read method for a struct
*/
void t_py_generator::generate_py_struct_reader(ofstream& out, t_struct* tstruct) {
const vector<t_field*>& fields = tstruct->get_members();
vector<t_field*>::const_iterator f_iter;
indent(out) << "def read(self, iprot):" << endl;
indent_up();
indent(out) << "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
"and isinstance(iprot.trans, TTransport.CReadableTransport) "
"and self.thrift_spec is not None "
"and fastbinary is not None:" << endl;
indent_up();
indent(out) << "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))"
<< endl;
indent(out) << "return" << endl;
indent_down();
indent(out) << "iprot.readStructBegin()" << endl;
// Loop over reading in fields
indent(out) << "while True:" << endl;
indent_up();
// Read beginning field marker
indent(out) << "(fname, ftype, fid) = iprot.readFieldBegin()" << endl;
// Check for field STOP marker and break
indent(out) << "if ftype == TType.STOP:" << endl;
indent_up();
indent(out) << "break" << endl;
indent_down();
// Switch statement on the field we are reading
bool first = true;
// Generate deserialization code for known cases
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
if (first) {
first = false;
out << indent() << "if ";
} else {
out << indent() << "elif ";
}
out << "fid == " << (*f_iter)->get_key() << ":" << endl;
indent_up();
indent(out) << "if ftype == " << type_to_enum((*f_iter)->get_type()) << ":" << endl;
indent_up();
generate_deserialize_field(out, *f_iter, "self.");
indent_down();
out << indent() << "else:" << endl << indent() << " iprot.skip(ftype)" << endl;
indent_down();
}
// In the default case we skip the field
out << indent() << "else:" << endl << indent() << " iprot.skip(ftype)" << endl;
// Read field end marker
indent(out) << "iprot.readFieldEnd()" << endl;
indent_down();
indent(out) << "iprot.readStructEnd()" << endl;
indent_down();
out << endl;
}
void t_py_generator::generate_py_struct_writer(ofstream& out, t_struct* tstruct) {
string name = tstruct->get_name();
const vector<t_field*>& fields = tstruct->get_sorted_members();
vector<t_field*>::const_iterator f_iter;
indent(out) << "def write(self, oprot):" << endl;
indent_up();
indent(out) << "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
"and self.thrift_spec is not None "
"and fastbinary is not None:" << endl;
indent_up();
indent(out)
<< "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))"
<< endl;
indent(out) << "return" << endl;
indent_down();
indent(out) << "oprot.writeStructBegin('" << name << "')" << endl;
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
// Write field header
indent(out) << "if self." << (*f_iter)->get_name() << " is not None:" << endl;
indent_up();
indent(out) << "oprot.writeFieldBegin("
<< "'" << (*f_iter)->get_name() << "', " << type_to_enum((*f_iter)->get_type())
<< ", " << (*f_iter)->get_key() << ")" << endl;
// Write field contents
generate_serialize_field(out, *f_iter, "self.");
// Write field closer
indent(out) << "oprot.writeFieldEnd()" << endl;
indent_down();
}
// Write the struct map
out << indent() << "oprot.writeFieldStop()" << endl << indent() << "oprot.writeStructEnd()"
<< endl;
out << endl;
indent_down();
generate_py_struct_required_validator(out, tstruct);
out << endl;
}
void t_py_generator::generate_py_struct_required_validator(ofstream& out, t_struct* tstruct) {
indent(out) << "def validate(self):" << endl;
indent_up();
const vector<t_field*>& fields = tstruct->get_members();
if (fields.size() > 0) {
vector<t_field*>::const_iterator f_iter;
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
t_field* field = (*f_iter);
if (field->get_req() == t_field::T_REQUIRED) {
indent(out) << "if self." << field->get_name() << " is None:" << endl;
indent(out) << " raise TProtocol.TProtocolException(message='Required field "
<< field->get_name() << " is unset!')" << endl;
}
}
}
indent(out) << "return" << endl << endl;
indent_down();
}
/**
* Generates a thrift service.
*
* @param tservice The service definition
*/
void t_py_generator::generate_service(t_service* tservice) {
string f_service_name = package_dir_ + "/" + service_name_ + ".py";
f_service_.open(f_service_name.c_str());
f_service_ << py_autogen_comment() << endl << py_imports() << endl;
if (tservice->get_extends() != NULL) {
f_service_ << "import "
<< get_real_py_module(tservice->get_extends()->get_program(), gen_twisted_) << "."
<< tservice->get_extends()->get_name() << endl;
}
f_service_ << "from ttypes import *" << endl << "from thrift.Thrift import TProcessor" << endl
<< render_fastbinary_includes() << endl;
if (gen_twisted_) {
f_service_ << "from zope.interface import Interface, implements" << endl
<< "from twisted.internet import defer" << endl
<< "from thrift.transport import TTwisted" << endl;
} else if (gen_tornado_) {
f_service_ << "from tornado import gen" << endl;
f_service_ << "from tornado import concurrent" << endl;
f_service_ << "from thrift.transport import TTransport" << endl;
}
f_service_ << endl;
// Generate the three main parts of the service
generate_service_interface(tservice);
generate_service_client(tservice);
generate_service_server(tservice);
generate_service_helpers(tservice);
generate_service_remote(tservice);
// Close service file
f_service_.close();
}
/**
* Generates helper functions for a service.
*
* @param tservice The service to generate a header definition for
*/
void t_py_generator::generate_service_helpers(t_service* tservice) {
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator f_iter;
f_service_ << "# HELPER FUNCTIONS AND STRUCTURES" << endl;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
t_struct* ts = (*f_iter)->get_arglist();
generate_py_struct_definition(f_service_, ts, false);
generate_py_function_helpers(*f_iter);
}
}
/**
* Generates a struct and helpers for a function.
*
* @param tfunction The function
*/
void t_py_generator::generate_py_function_helpers(t_function* tfunction) {
if (!tfunction->is_oneway()) {
t_struct result(program_, tfunction->get_name() + "_result");
t_field success(tfunction->get_returntype(), "success", 0);