-
Notifications
You must be signed in to change notification settings - Fork 611
/
t_py_generator.cc
3887 lines (3475 loc) · 131 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed 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 <stdlib.h>
#include <sys/types.h>
#include <stdexcept>
#include <algorithm>
#include <cassert>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
#include <thrift/compiler/ast/t_typedef.h>
#include <thrift/compiler/detail/system.h>
#include <thrift/compiler/generate/common.h>
#include <thrift/compiler/generate/t_concat_generator.h>
#include <thrift/compiler/generate/t_generator.h>
#include <thrift/compiler/lib/py3/util.h>
using namespace std;
namespace apache {
namespace thrift {
namespace compiler {
namespace {
const std::string* get_py_adapter(const t_type* type) {
if (!type->get_true_type()->is_struct()) {
return nullptr;
}
return t_typedef::get_first_annotation_or_null(type, {"py.adapter"});
}
void mark_file_executable(const std::filesystem::path& path) {
namespace fs = std::filesystem;
fs::permissions(
path,
fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec,
fs::perm_options::add);
}
string prefix_temporary(const string& name) {
return "_fbthrift_" + name;
}
} // namespace
/**
* Python code generator.
*/
class t_py_generator : public t_concat_generator {
public:
using t_concat_generator::t_concat_generator;
void process_options(
const std::map<std::string, std::string>& options) override {
gen_json_ = options.find("json") != options.end();
gen_slots_ = options.find("slots") != options.end();
gen_asyncio_ = options.find("asyncio") != options.end();
gen_future_ = options.find("future") != options.end();
gen_utf8strings_ = options.find("utf8strings") != options.end();
gen_cpp_transport_ = options.find("cpp_transport") != options.end();
if (gen_cpp_transport_ && gen_asyncio_) {
throw std::runtime_error(
"compiler error: can't use cpp transport together with asyncio yet");
}
sort_keys_ = options.find("sort_keys") != options.end();
auto iter = options.find("thrift_port");
if (iter != options.end()) {
default_port_ = iter->second;
} else {
default_port_ = "9090";
}
compare_t_fields_only_ =
options.find("compare_t_fields_only") != options.end();
out_dir_base_ = "gen-py";
}
/**
* Init and close methods
*/
void init_generator() override;
void close_generator() override;
/**
* Program-level generation functions
*/
void generate_typedef(const t_typedef* ttypedef) override;
void generate_enum(const t_enum* tenum) override;
void generate_const(const t_const* tconst) override;
void generate_struct(const t_structured* tstruct) override;
void generate_forward_declaration(const t_structured* tstruct) override;
void generate_xception(const t_structured* txception) override;
void generate_service(const t_service* tservice) override;
std::string render_const_value(
const t_type* type, const t_const_value* value);
/**
* Struct generation code
*/
void generate_py_struct(const t_structured* tstruct, bool is_exception);
void generate_py_thrift_spec(
std::ofstream& out, const t_structured* tstruct, bool is_exception);
void generate_py_annotation_dict(
std::ofstream& out, const deprecated_annotation_map& fields);
void generate_py_annotations(std::ofstream& out, const t_structured* tstruct);
void generate_py_union(std::ofstream& out, const t_structured* tstruct);
void generate_py_struct_definition(
std::ofstream& out,
const t_structured* tstruct,
bool is_exception = false,
bool is_result = false);
void generate_py_struct_reader(
std::ofstream& out, const t_structured* tstruct);
void generate_py_struct_writer(
std::ofstream& out, const t_structured* tstruct);
void generate_py_function_helpers(const t_function* tfunction);
void generate_py_converter_helpers(
std::ofstream& out, const t_structured* tstruct);
/**
* Service-level generation functions
*/
void generate_service_helpers(const t_service* tservice);
void generate_service_interface(const t_service* tservice, bool with_context);
void generate_service_client(const t_service* tservice);
void generate_service_remote(const t_service* tservice);
void generate_service_fuzzer(const t_service* tservice);
void generate_service_server(const t_service* tservice, bool with_context);
void generate_process_function(
const t_service* tservice,
const t_function* tfunction,
bool with_context,
bool future);
/**
* Serialization constructs
*/
void generate_deserialize_field(
std::ofstream& out,
const t_field* tfield,
std::string prefix = "",
bool inclass = false,
std::string actual_type = "");
void generate_deserialize_struct(
std::ofstream& out, const t_struct* tstruct, std::string prefix = "");
void generate_deserialize_container(
std::ofstream& out, const t_type* ttype, std::string prefix = "");
void generate_deserialize_set_element(
std::ofstream& out, const t_set* tset, std::string prefix = "");
void generate_deserialize_map_element(
std::ofstream& out,
const t_map* tmap,
std::string prefix = "",
std::string key_actual_type = "",
std::string value_actual_type = "");
void generate_deserialize_list_element(
std::ofstream& out, const t_list* tlist, std::string prefix = "");
void generate_serialize_field(
std::ofstream& out, const t_field* tfield, std::string prefix = "");
void generate_serialize_struct(
std::ofstream& out, const t_struct* tstruct, std::string prefix = "");
void generate_serialize_container(
std::ofstream& out, const t_type* ttype, std::string prefix = "");
void generate_serialize_map_element(
std::ofstream& out,
const t_map* tmap,
std::string kiter,
std::string viter);
void generate_serialize_set_element(
std::ofstream& out, const t_set* tmap, std::string iter);
void generate_serialize_list_element(
std::ofstream& out, const t_list* tlist, std::string iter);
void generate_json_enum(
std::ofstream& out,
const t_enum* tenum,
const string& prefix_thrift,
const string& prefix_json);
void generate_json_struct(
std::ofstream& out,
const t_struct* tstruct,
const string& prefix_thrift,
const string& prefix_json);
void generate_json_field(
std::ofstream& out,
const t_field* tfield,
const string& prefix_thrift = "",
const string& suffix_thrift = "",
const string& prefix_json = "",
bool generate_assignment = true);
void generate_json_container(
std::ofstream& out,
const t_type* ttype,
const string& prefix_thrift = "",
const string& prefix_json = "");
void generate_json_collection_element(
ofstream& out,
const t_type* type,
const string& collection,
const string& elem,
const string& action_prefix,
const string& action_suffix,
const string& prefix_json);
void generate_json_map_key(
ofstream& out,
const t_type* type,
const string& parsed_key,
const string& string_key);
void generate_json_reader(std::ofstream& out, const t_structured* tstruct);
void generate_fastproto_read(std::ofstream& out, const t_structured* tstruct);
void generate_fastproto_write(
std::ofstream& out, const t_structured* tstruct);
/**
* Helper rendering functions
*/
std::string py_autogen_comment();
std::string py_par_warning(string service_tool_name);
std::string py_imports();
std::string rename_reserved_keywords(const std::string& value);
std::string render_includes();
std::string render_fastproto_includes();
std::string declare_argument(
const t_structured* tstruct, const t_field* tfield);
std::string render_field_default_value(const t_field* tfield);
std::string type_name(const t_type* ttype);
std::string function_signature(
const t_function* tfunction, std::string prefix = "");
std::string function_signature_if(
const t_function* tfunction, bool with_context, std::string prefix = "");
std::string argument_list(const t_paramlist& tparamlist);
std::string type_to_enum(const t_type* ttype);
std::string type_to_spec_args(const t_type* ttype);
std::string get_real_py_module(const t_program* program);
std::string render_string(const std::string& value);
std::string render_ttype_declarations(const char* delimiter);
std::string get_priority(
const t_named* obj, const std::string& def = "NORMAL");
const std::vector<t_function*>& get_functions(const t_service* tservice);
private:
/**
* True iff we should generate a function parse json to thrift object.
*/
bool gen_json_;
/**
* True iff we should generate __slots__ for thrift structs.
*/
bool gen_slots_;
/**
* True iff we should generate code for asyncio server in Python 3.
*/
bool gen_asyncio_;
/**
* True iff we should generate services supporting concurrent.futures.
*/
bool gen_future_;
/**
* True iff strings should be encoded using utf-8.
*/
bool gen_utf8strings_;
/**
* True if we should generate new clients using C++ transport.
*/
bool gen_cpp_transport_;
/**
* True iff we serialize maps sorted by key and sets by value
*/
bool sort_keys_;
/**
* True iff we compare thrift classes using their spec fields only
*/
bool compare_t_fields_only_;
/**
* Default port to use.
*/
std::string default_port_;
/**
* File streams
*/
std::ofstream f_types_;
std::ofstream f_consts_;
std::ofstream f_service_;
std::filesystem::path package_dir_;
std::map<std::string, const std::vector<t_function*>> func_map_;
void generate_json_reader_fn_signature(ofstream& out);
static int32_t get_thrift_spec_key(const t_structured*, const t_field*);
void generate_python_docstring(
std::ofstream& out, const t_structured* tstruct);
void generate_python_docstring(
std::ofstream& out, const t_function* tfunction);
void generate_python_docstring(
std::ofstream& out,
const t_named* named_node,
const t_structured* tstruct,
const char* subheader);
void generate_python_docstring(std::ofstream& out, const t_named* named_node);
};
std::string t_py_generator::get_real_py_module(const t_program* program) {
if (gen_asyncio_) {
std::string asyncio_module = program->get_namespace("py.asyncio");
if (!asyncio_module.empty()) {
return asyncio_module;
}
}
std::string real_module = program->get_namespace("py");
if (real_module.empty()) {
return program->name();
}
return real_module;
}
void t_py_generator::generate_json_field(
ofstream& out,
const t_field* tfield,
const string& prefix_thrift,
const string& suffix_thrift,
const string& prefix_json,
bool generate_assignment) {
const t_type* type = tfield->get_type()->get_true_type();
if (type->is_void()) {
throw std::runtime_error(
"CANNOT READ JSON FIELD WITH void TYPE: " + prefix_thrift +
tfield->get_name());
}
string name = prefix_thrift + rename_reserved_keywords(tfield->get_name()) +
suffix_thrift;
if (type->is_struct() || type->is_exception()) {
generate_json_struct(out, (t_struct*)type, name, prefix_json);
} else if (type->is_container()) {
generate_json_container(out, (t_container*)type, name, prefix_json);
} else if (type->is_enum()) {
generate_json_enum(out, (t_enum*)type, name, prefix_json);
} else if (type->is_primitive_type()) {
string conversion_function = "";
t_primitive_type::t_primitive tbase =
((t_primitive_type*)type)->primitive_type();
string number_limit = "";
string number_negative_limit = "";
switch (tbase) {
case t_primitive_type::TYPE_VOID:
case t_primitive_type::TYPE_STRING:
case t_primitive_type::TYPE_BINARY:
case t_primitive_type::TYPE_BOOL:
break;
case t_primitive_type::TYPE_BYTE:
number_limit = "0x7f";
number_negative_limit = "-0x80";
break;
case t_primitive_type::TYPE_I16:
number_limit = "0x7fff";
number_negative_limit = "-0x8000";
break;
case t_primitive_type::TYPE_I32:
number_limit = "0x7fffffff";
number_negative_limit = "-0x80000000";
break;
case t_primitive_type::TYPE_I64:
conversion_function = "long";
break;
case t_primitive_type::TYPE_DOUBLE:
case t_primitive_type::TYPE_FLOAT:
conversion_function = "float";
break;
default:
throw std::runtime_error(
"compiler error: no python reader for base type " +
t_primitive_type::t_primitive_name(tbase) + name);
}
string value = prefix_json;
if (!conversion_function.empty()) {
value = conversion_function + "(" + value + ")";
}
if (generate_assignment) {
indent(out) << name << " = " << value << endl;
}
if (!number_limit.empty()) {
indent(out) << "if " << name << " > " << number_limit << " or " << name
<< " < " << number_negative_limit << ":" << endl;
indent_up();
indent(out) << "raise TProtocolException(TProtocolException.INVALID_DATA,"
<< " 'number exceeds limit in field')" << endl;
indent_down();
}
} else {
throw std::runtime_error("Compiler did not generate_json_field reader");
}
}
void t_py_generator::generate_json_struct(
ofstream& out,
const t_struct* tstruct,
const string& prefix_thrift,
const string& prefix_json) {
indent(out) << prefix_thrift << " = " << type_name(tstruct) << "()" << endl;
indent(out) << prefix_thrift << ".readFromJson(" << prefix_json
<< ", is_text=False, **kwargs)" << endl;
}
void t_py_generator::generate_json_enum(
ofstream& out,
const t_enum* tenum,
const string& prefix_thrift,
const string& prefix_json) {
indent(out) << prefix_thrift << " = " << prefix_json << endl;
indent(out) << "if not " << prefix_thrift << " in " << type_name(tenum)
<< "._VALUES_TO_NAMES:" << endl;
indent_up();
indent(out)
<< "msg = 'Integer value ''%s'' is not a recognized value of enum type "
<< type_name(tenum) << "' % " << prefix_thrift << endl;
indent(out) << "if relax_enum_validation:" << endl;
indent(out) << " warnings.warn(msg)" << endl;
indent(out) << "else:" << endl;
indent(out) << " raise TProtocolException("
<< "TProtocolException.INVALID_DATA, msg)" << endl;
indent_down();
indent(out) << "if wrap_enum_constants:" << endl;
indent_up();
indent(out) << prefix_thrift << " = ThriftEnumWrapper(" << type_name(tenum)
<< ", " << prefix_thrift << ")" << endl;
indent_down();
}
void t_py_generator::generate_json_container(
ofstream& out,
const t_type* ttype,
const string& prefix_thrift,
const string& prefix_json) {
if (ttype->is_list()) {
string e = tmp("_tmp_e");
indent(out) << prefix_thrift << " = []" << endl;
indent(out) << "for " << e << " in " << prefix_json << ":" << endl;
indent_up();
generate_json_collection_element(
out,
((t_list*)ttype)->get_elem_type(),
prefix_thrift,
e,
".append(",
")",
prefix_json);
indent_down();
} else if (ttype->is_set()) {
string e = tmp("_tmp_e");
indent(out) << prefix_thrift << " = set_cls()" << endl;
indent(out) << "for " << e << " in " << prefix_json << ":" << endl;
indent_up();
generate_json_collection_element(
out,
((t_set*)ttype)->get_elem_type(),
prefix_thrift,
e,
".add(",
")",
prefix_json);
indent_down();
} else if (ttype->is_map()) {
string k = tmp("_tmp_k");
string v = tmp("_tmp_v");
string kp = tmp("_tmp_kp");
indent(out) << prefix_thrift << " = dict_cls()" << endl;
indent(out) << "for " << k << ", " << v << " in " << prefix_json
<< ".items():" << endl;
indent_up();
generate_json_map_key(out, ((t_map*)ttype)->get_key_type(), kp, k);
generate_json_collection_element(
out,
((t_map*)ttype)->get_val_type(),
prefix_thrift,
v,
"[" + kp + "] = ",
"",
prefix_json + "[" + kp + "]");
indent_down();
}
}
void t_py_generator::generate_json_collection_element(
ofstream& out,
const t_type* type,
const string& collection,
const string& elem,
const string& action_prefix,
const string& action_suffix,
const string& prefix_json) {
string to_act_on = elem;
string to_parse = prefix_json;
type = type->get_true_type();
if (type->is_primitive_type()) {
t_primitive_type::t_primitive tbase =
((t_primitive_type*)type)->primitive_type();
switch (tbase) {
// Explicitly cast into float because there is an asymetry
// between serializing and deserializing NaN.
case t_primitive_type::TYPE_DOUBLE:
case t_primitive_type::TYPE_FLOAT:
to_act_on = "float(" + to_act_on + ")";
break;
default:
break;
}
} else if (type->is_enum()) {
to_parse = elem;
to_act_on = tmp("_enum");
} else if (type->is_list()) {
to_parse = elem;
to_act_on = tmp("_list");
} else if (type->is_map()) {
to_parse = elem;
to_act_on = tmp("_map");
} else if (type->is_set()) {
to_parse = elem;
to_act_on = tmp("_set");
} else if (type->is_struct()) {
to_parse = elem;
to_act_on = tmp("_struct");
}
t_field felem(type, to_act_on);
generate_json_field(out, &felem, "", "", to_parse, false);
indent(out) << collection << action_prefix << to_act_on << action_suffix
<< endl;
}
void t_py_generator::generate_json_map_key(
ofstream& out,
const t_type* type,
const string& parsed_key,
const string& raw_key) {
type = type->get_true_type();
if (type->is_enum()) {
indent(out) << parsed_key << " = int(" << raw_key << ")" << endl;
indent(out) << "if wrap_enum_constants:" << endl;
indent_up();
indent(out) << parsed_key << " = ThriftEnumWrapper(" << type_name(type)
<< ", " << parsed_key << ")" << endl;
indent_down();
} else if (type->is_primitive_type()) {
t_primitive_type::t_primitive tbase =
((t_primitive_type*)type)->primitive_type();
string conversion_function = "";
string number_limit = "";
string number_negative_limit = "";
bool generate_assignment = true;
switch (tbase) {
case t_primitive_type::TYPE_STRING:
case t_primitive_type::TYPE_BINARY:
break;
case t_primitive_type::TYPE_BOOL:
indent(out) << "if " << raw_key << " == 'true':" << endl;
indent_up();
indent(out) << parsed_key << " = True" << endl;
indent_down();
indent(out) << "elif " << raw_key << " == 'false':" << endl;
indent_up();
indent(out) << parsed_key << " = False" << endl;
indent_down();
indent(out) << "else:" << endl;
indent_up();
indent(out) << "raise TProtocolException(TProtocolException."
<< "INVALID_DATA, 'invalid boolean value' + " << raw_key
<< ")" << endl;
indent_down();
generate_assignment = false;
break;
case t_primitive_type::TYPE_BYTE:
conversion_function = "int";
number_limit = "0x7f";
number_negative_limit = "-0x80";
break;
case t_primitive_type::TYPE_I16:
conversion_function = "int";
number_limit = "0x7fff";
number_negative_limit = "-0x8000";
break;
case t_primitive_type::TYPE_I32:
conversion_function = "int";
number_limit = "0x7fffffff";
number_negative_limit = "-0x80000000";
break;
case t_primitive_type::TYPE_I64:
conversion_function = "long";
break;
case t_primitive_type::TYPE_DOUBLE:
case t_primitive_type::TYPE_FLOAT:
conversion_function = "float";
break;
default:
throw std::runtime_error(
"compiler error: no C++ reader for base type " +
t_primitive_type::t_primitive_name(tbase));
}
string value = raw_key;
if (!conversion_function.empty()) {
value = conversion_function + "(" + value + ")";
}
if (generate_assignment) {
indent(out) << parsed_key << " = " << value << endl;
}
if (!number_limit.empty()) {
indent(out) << "if " << parsed_key << " > " << number_limit << " or "
<< parsed_key << " < " << number_negative_limit << ":"
<< endl;
indent_up();
indent(out) << "raise TProtocolException(TProtocolException.INVALID_DATA,"
<< " 'number exceeds the limit in key ' + " << raw_key << ")"
<< endl;
indent_down();
}
} else {
throw string("compiler error: invalid key type");
}
}
void t_py_generator::generate_json_reader_fn_signature(ofstream& out) {
indent(out) << "def readFromJson(self, json, is_text=True, **kwargs):"
<< endl;
indent_up();
indent(out) << "kwargs_copy = dict(kwargs)" << endl;
indent(out) << "relax_enum_validation = "
"bool(kwargs_copy.pop('relax_enum_validation', False))"
<< endl;
indent(out) << "set_cls = kwargs_copy.pop('custom_set_cls', set)" << endl;
indent(out) << "dict_cls = kwargs_copy.pop('custom_dict_cls', dict)" << endl;
indent(out)
<< "wrap_enum_constants = kwargs_copy.pop('wrap_enum_constants', False)"
<< endl;
indent(out) << "if wrap_enum_constants and relax_enum_validation:" << endl;
indent(out) << " raise ValueError(" << endl;
indent(out)
<< " 'wrap_enum_constants cannot be used together with relax_enum_validation'"
<< endl;
indent(out) << " )" << endl;
indent(out) << "if kwargs_copy:" << endl;
indent(out) << " extra_kwargs = ', '.join(kwargs_copy.keys())" << endl;
indent(out) << " raise ValueError(" << endl;
indent(out) << " 'Unexpected keyword arguments: ' + extra_kwargs"
<< endl;
indent(out) << " )" << endl;
}
void t_py_generator::generate_json_reader(
ofstream& out, const t_structured* tstruct) {
if (!gen_json_) {
return;
}
const vector<t_field*>& fields = tstruct->get_members();
vector<t_field*>::const_iterator f_iter;
generate_json_reader_fn_signature(out);
indent(out) << "json_obj = json" << endl;
indent(out) << "if is_text:" << endl;
indent_up();
indent(out) << "json_obj = loads(json)" << endl;
indent_down();
for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
string field = (*f_iter)->get_name();
indent(out) << "if '" << field << "' in json_obj " << "and json_obj['"
<< field << "'] is not None:" << endl;
indent_up();
generate_json_field(
out, *f_iter, "self.", "", "json_obj['" + (*f_iter)->get_name() + "']");
indent_down();
}
indent_down();
out << endl;
}
/**
* 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 structure
string module = get_real_py_module(program_);
package_dir_ =
add_gen_dir() ? detail::format_abs_path(get_out_dir()) : get_out_path();
std::filesystem::create_directory(package_dir_);
while (true) {
std::filesystem::create_directory(package_dir_);
std::ofstream init_py(package_dir_ / "__init__.py");
init_py << py_autogen_comment();
init_py.close();
if (module.empty()) {
break;
}
string::size_type pos = module.find('.');
if (pos == string::npos) {
package_dir_ /= module;
module.clear();
} else {
package_dir_ /= module.substr(0, pos);
module.erase(0, pos + 1);
}
}
// Make output file
auto f_types_path = package_dir_ / "ttypes.py";
f_types_.open(f_types_path);
record_genfile(f_types_path);
auto f_consts_path = package_dir_ / "constants.py";
f_consts_.open(f_consts_path);
record_genfile(f_consts_path);
auto f_init_path = package_dir_ / "__init__.py";
std::ofstream f_init;
f_init.open(f_init_path);
record_genfile(f_init_path);
f_init << py_autogen_comment() << "__all__ = ['ttypes', 'constants'";
for (const auto* tservice : program_->services()) {
f_init << ", '" << tservice->get_name() << "'";
}
f_init << "]" << endl;
f_init.close();
// Print header
f_types_ << py_autogen_comment() << endl
<< py_imports() << endl
<< render_includes() << endl
<< render_fastproto_includes() << "all_structs = []" << endl
<< "UTF8STRINGS = bool(" << gen_utf8strings_ << ") or "
<< "sys.version_info.major >= 3" << endl
<< endl;
// Define __all__ for ttypes
f_types_ << "__all__ = [" << render_ttype_declarations("'") << "]" << endl
<< endl;
f_consts_ << py_autogen_comment() << endl
<< py_imports() << endl
<< render_includes() << endl
<< "from .ttypes import " << render_ttype_declarations("") << endl
<< endl;
}
string t_py_generator::render_ttype_declarations(const char* delimiter) {
std::ostringstream out;
out << delimiter << "UTF8STRINGS" << delimiter;
for (const auto& en : program_->enums()) {
out << ", " << delimiter << rename_reserved_keywords(en->get_name())
<< delimiter;
}
for (const t_structured* object : program_->structured_definitions()) {
out << ", " << delimiter << rename_reserved_keywords(object->get_name())
<< delimiter;
}
for (const auto& td : program_->typedefs()) {
out << ", " << delimiter << rename_reserved_keywords(td->name())
<< delimiter;
}
return out.str();
}
/**
* Ensures the string is not a reserved Python keyword.
*/
string t_py_generator::rename_reserved_keywords(const string& value) {
const auto& reserved_keywords = get_python_reserved_names();
if (reserved_keywords.find(value) != reserved_keywords.end()) {
return value + "_PY_RESERVED_KEYWORD";
} else {
return value;
}
}
/**
* Renders all the imports necessary for including another Thrift program
*/
string t_py_generator::render_includes() {
const vector<t_program*>& includes = program_->get_includes_for_codegen();
string result = "";
for (size_t i = 0; i < includes.size(); ++i) {
result += "import " + get_real_py_module(includes[i]) + ".ttypes\n";
}
if (includes.size() > 0) {
result += "\n";
}
set<string> modules;
for (const auto* strct : program_->structs_and_unions()) {
for (const auto* t : collect_types(strct)) {
if (const auto* adapter = get_py_adapter(t)) {
modules.emplace(adapter->substr(0, adapter->find_last_of('.')));
}
}
}
for (const auto* type : program_->typedefs()) {
if (const auto* adapter = get_py_adapter(type)) {
modules.emplace(adapter->substr(0, adapter->find_last_of('.')));
}
}
for (const auto& module : modules) {
result += "import " + module + "\n";
}
if (modules.size() > 0) {
result += "\n";
}
return result;
}
/**
* Renders all the imports necessary to use fastproto.
*/
string t_py_generator::render_fastproto_includes() {
return "import pprint\n"
"import warnings\n"
"from thrift import Thrift\n"
"from thrift.transport import TTransport\n"
"from thrift.protocol import TBinaryProtocol\n"
"from thrift.protocol import TCompactProtocol\n"
"from thrift.protocol import THeaderProtocol\n"
"fastproto = None\n"
"try:\n"
" from thrift.protocol import fastproto\n"
"except ImportError:\n"
" pass\n"
"\n"
/*
Given a sparse thrift_spec generate a full thrift_spec as expected by
fastproto. The old form is a tuple where every position is the same as the
thrift field id. The new form is just a tuple of the used field ids without
all the None padding, but its cheaper bytecode wise. There is a bug in
python 3.10 that causes large tuples to use more memory and generate larger
.pyc than <=3.9. See: https://github.com/python/cpython/issues/109036
*/
"def __EXPAND_THRIFT_SPEC(spec):\n"
" next_id = 0\n"
" for item in spec:\n"
" if next_id >= 0 and item[0] < 0:\n"
" next_id = item[0]\n"
" if item[0] != next_id:\n"
" for _ in range(next_id, item[0]):\n"
" yield None\n"
" yield item\n"
" next_id = item[0] + 1\n\n"
"class ThriftEnumWrapper(int):\n"
" def __new__(cls, enum_class, value):\n"
" return super().__new__(cls, value)\n"
" def __init__(self, enum_class, value):"
" self.enum_class = enum_class\n"
" def __repr__(self):\n"
" return self.enum_class.__name__ + '.' + self.enum_class._VALUES_TO_NAMES[self]\n\n";
}
/**
* Autogen'd comment
*/
string t_py_generator::py_autogen_comment() {
return std::string("#\n") + "# Autogenerated by Thrift\n" + "#\n" +
"# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE "
"DOING\n" +
"# @"
"generated\n" +
"#\n";
}
/**
* Print out warning message in the case a *.py is running instead of *.par
*/
string t_py_generator::py_par_warning(string service_tool_name) {
return "if (not sys.argv[0].endswith(\"par\") and\n"
" not sys.argv[0].endswith(\"xar\") and\n"
" os.getenv('PAR_UNPACK_TMP') == None):\n"
"\n"
" f = open(sys.argv[0], \"r\")\n"
"\n"
" f.readline() # This will be #!/bin/bash\n"
" line = f.readline()\n"
" f.close()\n"
"\n"
" # The par generator tool always has '# This par was made' as "
"the\n"
" # second line. See fbcode/tools/make_par/make_par.py\n"
" if (not line.startswith('# This par was made')):\n"
" print(\"\"\"WARNING\n"
" You are trying to run *-" +
service_tool_name +
".py which is\n"
" incorrect as the paths are not set up correctly.\n"
" Instead, you should generate your thrift file with\n"
" thrift_library and then run the resulting\n"
" *-" +
service_tool_name +
".par.\n"
" For more information, please read\n"
" http://fburl.com/python-remotes\"\"\")\n"
" exit()\n";
}
/**
* Prints standard thrift imports
*/
string t_py_generator::py_imports() {
string imports = "from __future__ import absolute_import\n";
imports += "import sys\n";
imports += "from thrift.util.Recursive import fix_spec\n";
imports += "from thrift.Thrift import TType, TMessageType, TPriority";
imports += ", TRequestContext, TProcessorEventHandler, TServerInterface";
imports +=
", TProcessor, TException, TApplicationException, UnimplementedTypedef\n";
imports += "from thrift.protocol.TProtocol import TProtocolException\n";
if (compare_t_fields_only_) {
imports += "from thrift.util import parse_struct_spec\n\n";
} else {
imports += "\n";
}
if (gen_json_) {
imports += "from json import loads\n";