-
Notifications
You must be signed in to change notification settings - Fork 42
/
t_py_generator.cc
4142 lines (3711 loc) · 130 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"
#ifdef SANDESH
#include <cassert>
#include "boost/tuple/tuple.hpp"
#endif
using namespace std;
/**
* 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("utf8strings");
gen_utf8strings_ = (iter != parsed_options.end());
copy_options_ = option_string;
if (gen_twisted_){
out_dir_base_ = "gen-py.twisted";
} 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);
#ifdef SANDESH
void generate_sandesh (t_sandesh* tsandesh);
#endif
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);
#ifdef SANDESH
void generate_py_struct_logger(std::ofstream& out, t_struct* tstruct);
void generate_py_struct_sizeof(std::ofstream& out, t_struct* tstruct);
#endif
/**
* Sandesh generation code
*/
#ifdef SANDESH
void generate_py_sandesh(t_sandesh *tsandesh);
void generate_py_sandesh_definition(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_reader(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_writer(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_compare(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_required_validator(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_http_request_handler(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_http_attr(ofstream& out,
t_type *ftype, const std::string& namel, const std::string& namer);
void generate_py_sandesh_skeleton_request(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_request_list(std::ofstream& out);
void generate_py_sandesh_http_request_list(std::ofstream& out, t_sandesh* tsandesh);
void generate_struct_log(std::ofstream& out, std::string prefix, std::string log_str);
void generate_container_log(std::ofstream& out, std::string prefix, t_type* ttype, string log_str);
void generate_field_log(std::ofstream& out, t_field *tfield, std::string log_str, std::string prefix);
void generate_py_sandesh_logger(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_hint(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_async(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_request(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_response(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_uve(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_uve_list(std::ofstream& out);
void generate_py_sandesh_alarm_list(std::ofstream& out);
void generate_py_sandesh_trace(std::ofstream& out, t_sandesh* tsandesh);
void generate_py_sandesh_sizeof(std::ofstream& out, t_sandesh* tsandesh);
#endif
#ifdef SANDESH
void generate_py_sizeof(std::ofstream& out, const vector<t_field*>& fields);
#endif
/**
* 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="");
#ifdef SANDESH
void generate_serialize_sandesh (std::ofstream &out,
t_sandesh* tsandesh,
std::string prefix="");
#endif
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();
#ifdef SANDESH
std::string py_autogen_sandesh_request_skeleton_comment();
void py_autogen_sandesh_http_request_open(std::ofstream& out);
void py_autogen_sandesh_http_request_close(std::ofstream& out);
#endif
std::string py_imports();
std::string render_includes();
std::string render_fastbinary_includes();
#ifdef SANDESH
std::string render_sandesh_includes();
#endif
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, std::string prefix="");
std::string function_signature_if(t_function* tfunction, std::string prefix="");
std::string argument_list(t_struct* tstruct);
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 strings should be encoded using utf-8.
*/
bool gen_utf8strings_;
#ifdef SANDESH
/**
* Sandesh Request List
*/
std::vector<std::string> sandesh_req_list_;
/**
* Sandesh UVE List
*/
std::vector<boost::tuple<std::string, std::string> > sandesh_uve_list_;
/**
* Sandesh Alarm List
*/
std::vector<boost::tuple<std::string, std::string> > sandesh_alarm_list_;
#endif
/**
* File streams
*/
std::ofstream f_types_;
std::ofstream f_consts_;
std::ofstream f_service_;
#ifdef SANDESH
std::ofstream f_request_impl_;
std::ofstream f_http_request_;
#endif
std::string package_dir_;
};
/**
* 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();
while (true) {
// TODO: Do better error checking here.
MKDIR(package_dir_.c_str());
std::ofstream init_py((package_dir_+"/__init__.py").c_str());
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() <<
render_sandesh_includes() <<
endl << endl;
f_consts_ <<
py_autogen_comment() << endl <<
py_imports() << endl <<
"from ttypes import *" << endl <<
endl;
#ifdef SANDESH
string f_request_impl_name = package_dir_+"/request_skeleton.py";
f_request_impl_.open(f_request_impl_name.c_str());
f_request_impl_ <<
py_autogen_comment() << endl;
f_request_impl_ <<
py_autogen_sandesh_request_skeleton_comment() << endl;
string f_http_request_name = package_dir_+"/http_request.py";
f_http_request_.open(f_http_request_name.c_str());
f_http_request_ <<
py_autogen_comment() << endl;
f_http_request_ <<
"import ttypes" << endl;
py_autogen_sandesh_http_request_open(f_http_request_);
#endif
}
/**
* 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 {
#ifdef SANDESH
hdr +=
"from pysandesh.transport import TTransport\n"
"from pysandesh.protocol import TBinaryProtocol, TProtocol\n"
"try:\n"
" from pysandesh.protocol import fastbinary\n"
"except:\n"
" fastbinary = None\n";
#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";
#endif
}
return hdr;
}
#ifdef SANDESH
string t_py_generator::render_sandesh_includes() {
std::string module = get_real_py_module(program_, gen_twisted_);
std::string sandesh_includes("\n");
sandesh_includes +=
"import cStringIO\n"
"import uuid\n"
"from sys import getsizeof\n"
"from itertools import chain\n";
if (module != "sandesh") {
sandesh_includes +=
"import bottle\n"
"from pysandesh import sandesh_base\n"
"from pysandesh.sandesh_http import SandeshHttp\n"
"from pysandesh.sandesh_uve import SandeshUVETypeMaps\n"
"from pysandesh.util import UTCTimestampUsec, UTCTimestampUsecToString\n"
"from pysandesh.gen_py.sandesh.constants import *\n"
"import collections\n";
}
return sandesh_includes;
}
#endif
/**
* Autogen'd comment
*/
string t_py_generator::py_autogen_comment() {
#ifdef SANDESH
return
std::string("#\n") +
"# Autogenerated by Sandesh Compiler (" + SANDESH_VERSION + ")\n" +
"#\n" +
"# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
"#\n" +
"# options string: " + copy_options_ + "\n" +
"# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n" +
"#\n";
#else
return
std::string("#\n") +
"# Autogenerated by Thrift Compiler \n" +
"#\n" +
"# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
"#\n" +
"# options string: " + copy_options_ + "\n" +
"#\n";
#endif
}
/**
* Prints standard thrift imports
*/
string t_py_generator::py_imports() {
#ifdef SANDESH
return
string("from pysandesh.Thrift import TType, TMessageType, TException");
#else
return
string("from thrift.Thrift import TType, TMessageType, TException");
#endif
}
/**
* Closes the type files
*/
void t_py_generator::close_generator() {
#ifdef SANDESH
generate_py_sandesh_request_list(f_types_);
generate_py_sandesh_uve_list(f_types_);
generate_py_sandesh_alarm_list(f_types_);
#endif
// Close types file
f_types_.close();
f_consts_.close();
#ifdef SANDESH
f_request_impl_.close();
py_autogen_sandesh_http_request_close(f_http_request_);
f_http_request_.close();
#endif
}
/**
* 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:
#ifdef SANDESH
case t_base_type::TYPE_STATIC_CONST_STRING:
case t_base_type::TYPE_XML:
#endif
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:
#ifdef SANDESH
case t_base_type::TYPE_U16:
case t_base_type::TYPE_U32:
case t_base_type::TYPE_U64:
case t_base_type::TYPE_IPV4:
#endif
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;
#ifdef SANDESH
case t_base_type::TYPE_UUID:
out << "uuid.UUID('{" << get_escaped_string(value) <<"}')";
break;
#endif
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->get_name() << "(**{" << 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);
}
void t_py_generator::generate_sandesh(t_sandesh* tsandesh) {
generate_py_sandesh(tsandesh);
}
/**
* 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) {
#ifdef SANDESH
// skip const string
t_type* type = get_true_type((*m_iter)->get_type());
if (type->is_static_const_string()) {
continue;
}
#endif
// 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;
#ifdef SANDESH
} else if (type->is_static_const_string()) {
indent(out) <<
"self." << (*m_iter)->get_name() << " = " <<
render_const_value(type, (*m_iter)->get_value()) << endl;
} else {
#else
}
#endif
indent(out) <<
"self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
#ifdef SANDESH
}
#endif
}
#ifdef SANDESH
for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
if ((*m_iter)->get_name() == "name") {
std::map<std::string, std::string>::iterator it;
it = (*m_iter)->annotations_.find("key");
if (it != (*m_iter)->annotations_.end()) {
indent(out) << "self._table = '" << it->second << "'" << endl;
}
break;
}
}
#endif
indent_down();
out << endl;
}
if (!gen_dynamic_) {
generate_py_struct_reader(out, tstruct);
generate_py_struct_writer(out, tstruct);
}
#ifdef SANDESH
generate_py_struct_logger(out, tstruct);
generate_py_struct_sizeof(out, tstruct);
#endif
// 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;
}
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 <<