OpenSDN source code
t_py_generator.cc
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  *
19  * Modifications Copyright (c) Juniper Networks, Inc.
20  * Copyright Contributors to the OpenSDN project
21  */
22 
23 #include <string>
24 #include <fstream>
25 #include <iostream>
26 #include <vector>
27 
28 #include <stdlib.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sstream>
32 #include <algorithm>
33 #include "t_generator.h"
34 #include "platform.h"
35 #include "version.h"
36 
37 #ifdef SANDESH
38 #include <cassert>
39 #include "boost/tuple/tuple.hpp"
40 #endif
41 using namespace std;
42 
43 
48 class t_py_generator : public t_generator {
49  public:
51  t_program* program,
52  const std::map<std::string, std::string>& parsed_options,
53  const std::string& option_string)
54  : t_generator(program)
55  {
56  (void) option_string;
57  std::map<std::string, std::string>::const_iterator iter;
58 
59  iter = parsed_options.find("new_style");
60  gen_newstyle_ = (iter != parsed_options.end());
61 
62  iter = parsed_options.find("slots");
63  gen_slots_ = (iter != parsed_options.end());
64 
65  iter = parsed_options.find("dynamic");
66  gen_dynamic_ = (iter != parsed_options.end());
67 
68  if (gen_dynamic_) {
69  gen_newstyle_ = 0; // dynamic is newstyle
70  gen_dynbaseclass_ = "TBase";
71  gen_dynbaseclass_exc_ = "TExceptionBase";
72  import_dynbase_ = "from thrift.protocol.TBase import TBase, TExceptionBase\n";
73  }
74 
75  iter = parsed_options.find("dynbase");
76  if (iter != parsed_options.end()) {
77  gen_dynbase_ = true;
78  gen_dynbaseclass_ = (iter->second);
79  }
80 
81  iter = parsed_options.find("dynexc");
82  if (iter != parsed_options.end()) {
83  gen_dynbaseclass_exc_ = (iter->second);
84  }
85 
86  iter = parsed_options.find("dynimport");
87  if (iter != parsed_options.end()) {
88  gen_dynbase_ = true;
89  import_dynbase_ = (iter->second);
90  }
91 
92  iter = parsed_options.find("twisted");
93  gen_twisted_ = (iter != parsed_options.end());
94 
95  iter = parsed_options.find("utf8strings");
96  gen_utf8strings_ = (iter != parsed_options.end());
97 
98  copy_options_ = option_string;
99 
100  if (gen_twisted_){
101  out_dir_base_ = "gen-py.twisted";
102  } else {
103  out_dir_base_ = "gen-py";
104  }
105  }
106 
111  void init_generator();
112  void close_generator();
113 
118  void generate_typedef (t_typedef* ttypedef);
119  void generate_enum (t_enum* tenum);
120  void generate_const (t_const* tconst);
121  void generate_struct (t_struct* tstruct);
122  void generate_xception (t_struct* txception);
123  void generate_service (t_service* tservice);
124 #ifdef SANDESH
125  void generate_sandesh (t_sandesh* tsandesh);
126 #endif
127  std::string render_const_value(t_type* type, t_const_value* value);
128 
133  void generate_py_struct(t_struct* tstruct, bool is_exception);
134  void generate_py_struct_definition(std::ofstream& out, t_struct* tstruct, bool is_xception=false, bool is_result=false);
135  void generate_py_struct_reader(std::ofstream& out, t_struct* tstruct);
136  void generate_py_struct_writer(std::ofstream& out, t_struct* tstruct);
137  void generate_py_struct_required_validator(std::ofstream& out, t_struct* tstruct);
138  void generate_py_function_helpers(t_function* tfunction);
139 #ifdef SANDESH
140  void generate_py_struct_logger(std::ofstream& out, t_struct* tstruct);
141  void generate_py_struct_sizeof(std::ofstream& out, t_struct* tstruct);
142 #endif
143 
147 #ifdef SANDESH
148  void generate_py_sandesh(t_sandesh *tsandesh);
149  void generate_py_sandesh_definition(std::ofstream& out, t_sandesh* tsandesh);
150  void generate_py_sandesh_reader(std::ofstream& out, t_sandesh* tsandesh);
151  void generate_py_sandesh_writer(std::ofstream& out, t_sandesh* tsandesh);
152  void generate_py_sandesh_compare(std::ofstream& out, t_sandesh* tsandesh);
153  void generate_py_sandesh_required_validator(std::ofstream& out, t_sandesh* tsandesh);
154  void generate_py_sandesh_http_request_handler(std::ofstream& out, t_sandesh* tsandesh);
155  void generate_py_sandesh_http_attr(ofstream& out,
156  t_type *ftype, const std::string& namel, const std::string& namer);
157  void generate_py_sandesh_skeleton_request(std::ofstream& out, t_sandesh* tsandesh);
158  void generate_py_sandesh_request_list(std::ofstream& out);
159  void generate_py_sandesh_http_request_list(std::ofstream& out, t_sandesh* tsandesh);
160  void generate_struct_log(std::ofstream& out, std::string prefix, std::string log_str);
161  void generate_container_log(std::ofstream& out, std::string prefix, t_type* ttype, string log_str);
162  void generate_field_log(std::ofstream& out, t_field *tfield, std::string log_str, std::string prefix);
163  void generate_py_sandesh_logger(std::ofstream& out, t_sandesh* tsandesh);
164  void generate_py_sandesh_hint(std::ofstream& out, t_sandesh* tsandesh);
165  void generate_py_sandesh_async(std::ofstream& out, t_sandesh* tsandesh);
166  void generate_py_sandesh_request(std::ofstream& out, t_sandesh* tsandesh);
167  void generate_py_sandesh_response(std::ofstream& out, t_sandesh* tsandesh);
168  void generate_py_sandesh_uve(std::ofstream& out, t_sandesh* tsandesh, bool update);
169  void generate_py_sandesh_uve_list(std::ofstream& out);
170  void generate_py_sandesh_alarm_list(std::ofstream& out);
171  void generate_py_sandesh_trace(std::ofstream& out, t_sandesh* tsandesh);
172  void generate_py_sandesh_sizeof(std::ofstream& out, t_sandesh* tsandesh);
173 #endif
174 
175 #ifdef SANDESH
176  void generate_py_sizeof(std::ofstream& out, const vector<t_field*>& fields);
177 #endif
178 
183  void generate_service_helpers (t_service* tservice);
184  void generate_service_interface (t_service* tservice);
185  void generate_service_client (t_service* tservice);
186  void generate_service_remote (t_service* tservice);
187  void generate_service_server (t_service* tservice);
188  void generate_process_function (t_service* tservice, t_function* tfunction);
189 
194  void generate_deserialize_field (std::ofstream &out,
195  t_field* tfield,
196  std::string prefix="",
197  bool inclass=false);
198 
199  void generate_deserialize_struct (std::ofstream &out,
200  t_struct* tstruct,
201  std::string prefix="");
202 
203  void generate_deserialize_container (std::ofstream &out,
204  t_type* ttype,
205  std::string prefix="");
206 
207  void generate_deserialize_set_element (std::ofstream &out,
208  t_set* tset,
209  std::string prefix="");
210 
211  void generate_deserialize_map_element (std::ofstream &out,
212  t_map* tmap,
213  std::string prefix="");
214 
215  void generate_deserialize_list_element (std::ofstream &out,
216  t_list* tlist,
217  std::string prefix="");
218 
219  void generate_serialize_field (std::ofstream &out,
220  t_field* tfield,
221  std::string prefix="");
222 
223  void generate_serialize_struct (std::ofstream &out,
224  t_struct* tstruct,
225  std::string prefix="");
226 
227 #ifdef SANDESH
228  void generate_serialize_sandesh (std::ofstream &out,
229  t_sandesh* tsandesh,
230  std::string prefix="");
231 #endif
232 
233  void generate_serialize_container (std::ofstream &out,
234  t_type* ttype,
235  std::string prefix="");
236 
237  void generate_serialize_map_element (std::ofstream &out,
238  t_map* tmap,
239  std::string kiter,
240  std::string viter);
241 
242  void generate_serialize_set_element (std::ofstream &out,
243  t_set* tmap,
244  std::string iter);
245 
246  void generate_serialize_list_element (std::ofstream &out,
247  t_list* tlist,
248  std::string iter);
249 
250  void generate_python_docstring (std::ofstream& out,
251  t_struct* tstruct);
252 
253  void generate_python_docstring (std::ofstream& out,
254  t_function* tfunction);
255 
256  void generate_python_docstring (std::ofstream& out,
257  t_doc* tdoc,
258  t_struct* tstruct,
259  const char* subheader);
260 
261  void generate_python_docstring (std::ofstream& out,
262  t_doc* tdoc);
263 
268  std::string py_autogen_comment();
269  std::string future_imports();
270 #ifdef SANDESH
271  std::string py_autogen_sandesh_request_skeleton_comment();
272  void py_autogen_sandesh_http_request_open(std::ofstream& out);
273  void py_autogen_sandesh_http_request_close(std::ofstream& out);
274 #endif
275  std::string py_imports();
276  std::string render_includes();
277  std::string render_fastbinary_includes();
278 #ifdef SANDESH
279  std::string render_sandesh_includes();
280 #endif
281  std::string declare_argument(t_field* tfield);
282  std::string render_field_default_value(t_field* tfield);
283  std::string type_name(t_type* ttype);
284  std::string function_signature(t_function* tfunction, std::string prefix="");
285  std::string function_signature_if(t_function* tfunction, std::string prefix="");
286  std::string argument_list(t_struct* tstruct);
287  std::string type_to_enum(t_type* ttype);
288  std::string type_to_spec_args(t_type* ttype);
289 
290  static bool is_valid_namespace(const std::string& sub_namespace) {
291  return sub_namespace == "twisted";
292  }
293 
294  static std::string get_real_py_module(const t_program* program, bool gen_twisted) {
295  if(gen_twisted) {
296  std::string twisted_module = program->get_namespace("py.twisted");
297  if(!twisted_module.empty()){
298  return twisted_module;
299  }
300  }
301 
302  std::string real_module = program->get_namespace("py");
303  if (real_module.empty()) {
304  return program->get_name();
305  }
306  return real_module;
307  }
308 
309  private:
310 
315 
320 
322  std::string gen_dynbaseclass_;
324 
325  std::string import_dynbase_;
326 
328 
329  std::string copy_options_;
330 
335 
340 
341 #ifdef SANDESH
345  std::vector<std::string> sandesh_req_list_;
346 
350  std::vector<boost::tuple<std::string, std::string> > sandesh_uve_list_;
351 
355  std::vector<boost::tuple<std::string, std::string> > sandesh_alarm_list_;
356 #endif
357 
362  std::ofstream f_types_;
363  std::ofstream f_consts_;
364  std::ofstream f_service_;
365 #ifdef SANDESH
366  std::ofstream f_request_impl_;
367  std::ofstream f_http_request_;
368 #endif
369 
370  std::string package_dir_;
371 
372 };
373 
374 
382  // Make output directory
383  string module = get_real_py_module(program_, gen_twisted_);
384  package_dir_ = get_out_dir();
385  while (true) {
386  // TODO: Do better error checking here.
387  MKDIR(package_dir_.c_str());
388  std::ofstream init_py((package_dir_+"/__init__.py").c_str());
389  init_py.close();
390  if (module.empty()) {
391  break;
392  }
393  string::size_type pos = module.find('.');
394  if (pos == string::npos) {
395  package_dir_ += "/";
396  package_dir_ += module;
397  module.clear();
398  } else {
399  package_dir_ += "/";
400  package_dir_ += module.substr(0, pos);
401  module.erase(0, pos+1);
402  }
403  }
404 
405  // Make output file
406  string f_types_name = package_dir_+"/"+"ttypes.py";
407  f_types_.open(f_types_name.c_str());
408 
409  string f_consts_name = package_dir_+"/"+"constants.py";
410  f_consts_.open(f_consts_name.c_str());
411 
412  string f_init_name = package_dir_+"/__init__.py";
413  ofstream f_init;
414  f_init.open(f_init_name.c_str());
415  f_init <<
416  "__all__ = ['ttypes', 'constants'";
417  vector<t_service*> services = program_->get_services();
418  vector<t_service*>::iterator sv_iter;
419  for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) {
420  f_init << ", '" << (*sv_iter)->get_name() << "'";
421  }
422  f_init << "]" << endl;
423  f_init.close();
424 
425  // Print header
426  f_types_ <<
427  py_autogen_comment() << endl <<
428  py_imports() << endl <<
429  future_imports() << endl <<
430  render_includes() << endl <<
431  render_fastbinary_includes() <<
432  render_sandesh_includes() <<
433  endl << endl;
434 
435  f_consts_ <<
436  py_autogen_comment() << endl <<
437  py_imports() << endl <<
438  "from .ttypes import *" << endl <<
439  endl;
440 #ifdef SANDESH
441  string f_request_impl_name = package_dir_+"/request_skeleton.py";
442  f_request_impl_.open(f_request_impl_name.c_str());
443  f_request_impl_ <<
444  py_autogen_comment() << endl;
445  f_request_impl_ <<
446  py_autogen_sandesh_request_skeleton_comment() << endl;
447 
448  string f_http_request_name = package_dir_+"/http_request.py";
449  f_http_request_.open(f_http_request_name.c_str());
450  f_http_request_ <<
451  py_autogen_comment() << endl;
452  f_http_request_ <<
453  "from . import ttypes" << endl;
454  py_autogen_sandesh_http_request_open(f_http_request_);
455 #endif
456 }
457 
462  const vector<t_program*>& includes = program_->get_includes();
463  string result = "";
464  for (size_t i = 0; i < includes.size(); ++i) {
465  result += "from ." + get_real_py_module(includes[i], gen_twisted_) +
466  " import ttypes as " + get_real_py_module(includes[i], gen_twisted_) + "_ttypes\n";
467  }
468  if (includes.size() > 0) {
469  result += "\n";
470  }
471  return result;
472 }
473 
478  string hdr = "";
479  if (gen_dynamic_) {
480  hdr += std::string(import_dynbase_);
481  } else {
482 #ifdef SANDESH
483  hdr +=
484  "from pysandesh.transport import TTransport\n"
485  "from pysandesh.protocol import TBinaryProtocol, TProtocol\n"
486  "try:\n"
487  " from pysandesh.protocol import fastbinary\n"
488  "except:\n"
489  " fastbinary = None\n";
490 #else
491  hdr +=
492  "from thrift.transport import TTransport\n"
493  "from thrift.protocol import TBinaryProtocol, TProtocol\n"
494  "try:\n"
495  " from thrift.protocol import fastbinary\n"
496  "except:\n"
497  " fastbinary = None\n";
498 #endif
499  }
500  return hdr;
501 }
502 
503 #ifdef SANDESH
504 string t_py_generator::render_sandesh_includes() {
505  std::string module = get_real_py_module(program_, gen_twisted_);
506  std::string sandesh_includes("\n");
507  sandesh_includes +=
508  "from io import StringIO\n"
509  "import uuid\n"
510  "import netaddr\n"
511  "from sys import getsizeof\n"
512  "from itertools import chain\n";
513  if (module != "sandesh") {
514  sandesh_includes +=
515  "import bottle\n"
516  "from pysandesh import sandesh_base\n"
517  "from pysandesh.sandesh_http import SandeshHttp\n"
518  "from pysandesh.sandesh_uve import SandeshUVETypeMaps\n"
519  "from pysandesh.util import UTCTimestampUsec, UTCTimestampUsecToString\n"
520  "from pysandesh import util\n"
521  "from pysandesh.gen_py.sandesh.constants import *\n";
522  }
523  return sandesh_includes;
524 }
525 #endif
526 
531 #ifdef SANDESH
532  return
533  std::string("#\n") +
534  "# Autogenerated by Sandesh Compiler (" + SANDESH_VERSION + ")\n" +
535  "#\n" +
536  "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
537  "#\n" +
538  "# options string: " + copy_options_ + "\n" +
539  "# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n" +
540  "#\n";
541 #else
542  return
543  std::string("#\n") +
544  "# Autogenerated by Thrift Compiler \n" +
545  "#\n" +
546  "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
547  "#\n" +
548  "# options string: " + copy_options_ + "\n" +
549  "#\n";
550 #endif
551 }
552 
557 #ifdef SANDESH
558  return
559  string("from pysandesh.Thrift import TType, TMessageType, TException");
560 #else
561  return
562  string("from thrift.Thrift import TType, TMessageType, TException");
563 #endif
564 }
565 
570  std::string future_imports("\n");
571  return future_imports;
572 }
573 
578 #ifdef SANDESH
579  generate_py_sandesh_request_list(f_types_);
580  generate_py_sandesh_uve_list(f_types_);
581  generate_py_sandesh_alarm_list(f_types_);
582 #endif
583  // Close types file
584  f_types_.close();
585  f_consts_.close();
586 #ifdef SANDESH
587  f_request_impl_.close();
588  py_autogen_sandesh_http_request_close(f_http_request_);
589  f_http_request_.close();
590 #endif
591 }
592 
599  (void) ttypedef;
600 }
601 
609  std::ostringstream to_string_mapping, from_string_mapping;
610 
611  f_types_ <<
612  "class " << tenum->get_name() <<
613  (gen_newstyle_ ? "(object)" : "") <<
614  (gen_dynamic_ ? "(" + gen_dynbaseclass_ + ")" : "") <<
615  ":" << endl;
616  indent_up();
617  generate_python_docstring(f_types_, tenum);
618 
619  to_string_mapping << indent() << "_VALUES_TO_NAMES = {" << endl;
620  from_string_mapping << indent() << "_NAMES_TO_VALUES = {" << endl;
621 
622  vector<t_enum_value*> constants = tenum->get_constants();
623  vector<t_enum_value*>::iterator c_iter;
624  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
625  int value = (*c_iter)->get_value();
626  indent(f_types_) << (*c_iter)->get_name() << " = " << value << endl;
627 
628  // Dictionaries to/from string names of enums
629  to_string_mapping <<
630  indent() << indent() << value << ": \"" <<
631  escape_string((*c_iter)->get_name()) << "\"," << endl;
632  from_string_mapping <<
633  indent() << indent() << '"' << escape_string((*c_iter)->get_name()) <<
634  "\": " << value << ',' << endl;
635  }
636  to_string_mapping << indent() << "}" << endl;
637  from_string_mapping << indent() << "}" << endl;
638 
639  indent_down();
640  f_types_ << endl;
641  f_types_ << to_string_mapping.str() << endl << from_string_mapping.str() << endl;
642 }
643 
648  t_type* type = tconst->get_type();
649  string name = tconst->get_name();
650  t_const_value* value = tconst->get_value();
651 
652  indent(f_consts_) << name << " = " << render_const_value(type, value);
653  f_consts_ << endl;
654 }
655 
662  type = get_true_type(type);
663  std::ostringstream out;
664 
665  if (type->is_base_type()) {
666  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
667  switch (tbase) {
669 #ifdef SANDESH
670  case t_base_type::TYPE_STATIC_CONST_STRING:
671  case t_base_type::TYPE_XML:
672 #endif
673  out << '"' << get_escaped_string(value) << '"';
674  break;
676  out << (value->get_integer() > 0 ? "True" : "False");
677  break;
682 #ifdef SANDESH
683  case t_base_type::TYPE_U16:
684  case t_base_type::TYPE_U32:
685  case t_base_type::TYPE_U64:
686  case t_base_type::TYPE_IPV4:
687 #endif
688  out << value->get_integer();
689  break;
691  if (value->get_type() == t_const_value::CV_INTEGER) {
692  out << value->get_integer();
693  } else {
694  out << value->get_double();
695  }
696  break;
697 #ifdef SANDESH
698  case t_base_type::TYPE_UUID:
699  out << "uuid.UUID('{" << get_escaped_string(value) <<"}')";
700  break;
701  case t_base_type::TYPE_IPADDR:
702  out << "netaddr.IPAddress('" << value->get_string() << "')";
703  break;
704 #endif
705  default:
706  throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
707  }
708  } else if (type->is_enum()) {
709  indent(out) << value->get_integer();
710  } else if (type->is_struct() || type->is_xception()) {
711  out << type->get_name() << "(**{" << endl;
712  indent_up();
713  const vector<t_field*>& fields = ((t_struct*)type)->get_members();
714  vector<t_field*>::const_iterator f_iter;
715  const map<t_const_value*, t_const_value*>& val = value->get_map();
716  map<t_const_value*, t_const_value*>::const_iterator v_iter;
717  for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
718  t_type* field_type = NULL;
719  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
720  if ((*f_iter)->get_name() == v_iter->first->get_string()) {
721  field_type = (*f_iter)->get_type();
722  }
723  }
724  if (field_type == NULL) {
725  throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
726  }
727  out << indent();
728  out << render_const_value(g_type_string, v_iter->first);
729  out << " : ";
730  out << render_const_value(field_type, v_iter->second);
731  out << "," << endl;
732  }
733  indent_down();
734  indent(out) << "})";
735  } else if (type->is_map()) {
736  t_type* ktype = ((t_map*)type)->get_key_type();
737  t_type* vtype = ((t_map*)type)->get_val_type();
738  out << "{" << endl;
739  indent_up();
740  const map<t_const_value*, t_const_value*>& val = value->get_map();
741  map<t_const_value*, t_const_value*>::const_iterator v_iter;
742  for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
743  out << indent();
744  out << render_const_value(ktype, v_iter->first);
745  out << " : ";
746  out << render_const_value(vtype, v_iter->second);
747  out << "," << endl;
748  }
749  indent_down();
750  indent(out) << "}";
751  } else if (type->is_list() || type->is_set()) {
752  t_type* etype;
753  if (type->is_list()) {
754  etype = ((t_list*)type)->get_elem_type();
755  } else {
756  etype = ((t_set*)type)->get_elem_type();
757  }
758  if (type->is_set()) {
759  out << "set(";
760  }
761  out << "[" << endl;
762  indent_up();
763  const vector<t_const_value*>& val = value->get_list();
764  vector<t_const_value*>::const_iterator v_iter;
765  for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
766  out << indent();
767  out << render_const_value(etype, *v_iter);
768  out << "," << endl;
769  }
770  indent_down();
771  indent(out) << "]";
772  if (type->is_set()) {
773  out << ")";
774  }
775  } else {
776  throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
777  }
778 
779  return out.str();
780 }
781 
786  generate_py_struct(tstruct, false);
787 }
788 
796  generate_py_struct(txception, true);
797 }
798 
799 void t_py_generator::generate_sandesh(t_sandesh* tsandesh) {
800  generate_py_sandesh(tsandesh);
801 }
802 
807  bool is_exception) {
808  generate_py_struct_definition(f_types_, tstruct, is_exception);
809 }
810 
817  t_struct* tstruct,
818  bool is_exception,
819  bool is_result) {
820  (void) is_result;
821  const vector<t_field*>& members = tstruct->get_members();
822  const vector<t_field*>& sorted_members = tstruct->get_sorted_members();
823  vector<t_field*>::const_iterator m_iter;
824 
825  out << std::endl <<
826  "class " << tstruct->get_name();
827  if (is_exception) {
828  if (gen_dynamic_) {
829  out << "(" << gen_dynbaseclass_exc_ << ")";
830  } else {
831  out << "(TException)";
832  }
833  } else {
834  if (gen_newstyle_) {
835  out << "(object)";
836  } else if (gen_dynamic_) {
837  out << "(" << gen_dynbaseclass_ << ")";
838  }
839  }
840  out << ":" << endl;
841  indent_up();
842  generate_python_docstring(out, tstruct);
843 
844  out << endl;
845 
846  /*
847  Here we generate the structure specification for the fastbinary codec.
848  These specifications have the following structure:
849  thrift_spec -> tuple of item_spec
850  item_spec -> None | (tag, type_enum, name, spec_args, default)
851  tag -> integer
852  type_enum -> TType.I32 | TType.STRING | TType.STRUCT | ...
853  name -> string_literal
854  default -> None # Handled by __init__
855  spec_args -> None # For simple types
856  | (type_enum, spec_args) # Value type for list/set
857  | (type_enum, spec_args, type_enum, spec_args)
858  # Key and value for map
859  | (class_name, spec_args_ptr) # For struct/exception
860  class_name -> identifier # Basically a pointer to the class
861  spec_args_ptr -> expression # just class_name.spec_args
862 
863  TODO(dreiss): Consider making this work for structs with negative tags.
864  */
865 
866  if (gen_slots_) {
867  indent(out) << "__slots__ = [ " << endl;
868  indent_up();
869  for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
870  indent(out) << "'" << (*m_iter)->get_name() << "'," << endl;
871  }
872  indent_down();
873  indent(out) << " ]" << endl << endl;
874 
875  }
876 
877  // TODO(dreiss): Look into generating an empty tuple instead of None
878  // for structures with no members.
879  // TODO(dreiss): Test encoding of structs where some inner structs
880  // don't have thrift_spec.
881  if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
882  indent(out) << "thrift_spec = (" << endl;
883  indent_up();
884 
885  int sorted_keys_pos = 0;
886  for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
887 
888  for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
889  indent(out) << "None, # " << sorted_keys_pos << endl;
890  }
891 
892  indent(out) << "(" << (*m_iter)->get_key() << ", "
893  << type_to_enum((*m_iter)->get_type()) << ", "
894  << "'" << (*m_iter)->get_name() << "'" << ", "
895  << type_to_spec_args((*m_iter)->get_type()) << ", "
896  << render_field_default_value(*m_iter) << ", "
897  << "),"
898  << " # " << sorted_keys_pos
899  << endl;
900 
901  sorted_keys_pos ++;
902  }
903 
904  indent_down();
905  indent(out) << ")" << endl << endl;
906  } else {
907  indent(out) << "thrift_spec = None" << endl;
908  }
909 
910 
911  if (members.size() > 0) {
912  out <<
913  indent() << "def __init__(self,";
914 
915  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
916 #ifdef SANDESH
917  // skip const string
918  t_type* type = get_true_type((*m_iter)->get_type());
919  if (type->is_static_const_string()) {
920  continue;
921  }
922 #endif
923  // This fills in default values, as opposed to nulls
924  out << " " << declare_argument(*m_iter) << ",";
925  }
926 
927  out << "):" << endl;
928 
929  indent_up();
930 
931  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
932  // Initialize fields
933  t_type* type = (*m_iter)->get_type();
934  if (!type->is_base_type() && !type->is_enum() && (*m_iter)->get_value() != NULL) {
935  indent(out) <<
936  "if " << (*m_iter)->get_name() << " is " << "self.thrift_spec[" <<
937  (*m_iter)->get_key() << "][4]:" << endl;
938  indent(out) << " " << (*m_iter)->get_name() << " = " <<
939  render_field_default_value(*m_iter) << endl;
940 #ifdef SANDESH
941  } else if (type->is_static_const_string()) {
942  indent(out) <<
943  "self." << (*m_iter)->get_name() << " = " <<
944  render_const_value(type, (*m_iter)->get_value()) << endl;
945  } else {
946 #else
947  }
948 #endif
949  indent(out) <<
950  "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
951 #ifdef SANDESH
952  }
953 #endif
954  }
955 
956 #ifdef SANDESH
957  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
958  if ((*m_iter)->get_name() == "name") {
959  std::map<std::string, std::string>::iterator it;
960  it = (*m_iter)->annotations_.find("key");
961  if (it != (*m_iter)->annotations_.end()) {
962  indent(out) << "self._table = '" << it->second << "'" << endl;
963  }
964  break;
965  }
966  }
967 #endif
968 
969  indent_down();
970 
971  out << endl;
972  }
973 
974  if (!gen_dynamic_) {
975  generate_py_struct_reader(out, tstruct);
976  generate_py_struct_writer(out, tstruct);
977  }
978 
979 #ifdef SANDESH
980  generate_py_struct_logger(out, tstruct);
981  generate_py_struct_sizeof(out, tstruct);
982 #endif
983 
984  // For exceptions only, generate a __str__ method. This is
985  // because when raised exceptions are printed to the console, __repr__
986  // isn't used. See python bug #5882
987  if (is_exception) {
988  out <<
989  indent() << "def __str__(self):" << endl <<
990  indent() << " return repr(self)" << endl <<
991  endl;
992  }
993 
994  if (!gen_slots_) {
995  // Printing utilities so that on the command line thrift
996  // structs look pretty like dictionaries
997  out <<
998  indent() << "def __repr__(self):" << endl <<
999  indent() << " L = ['%s=%r' % (key, value)" << endl <<
1000  indent() << " for key, value in self.__dict__.items()]" << endl <<
1001  indent() << " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1002  endl;
1003 
1004  // Equality and inequality methods that compare by value
1005  out <<
1006  indent() << "def __eq__(self, other):" << endl;
1007  indent_up();
1008  out <<
1009  indent() << "return isinstance(other, self.__class__) and "
1010  "self.__dict__ == other.__dict__" << endl;
1011  indent_down();
1012  out << endl;
1013 
1014  out <<
1015  indent() << "def __ne__(self, other):" << endl;
1016  indent_up();
1017 
1018  out <<
1019  indent() << "return not (self == other)" << endl;
1020  indent_down();
1021  out << endl;
1022 
1023  // In python2 __hash__ function is implicit for user-defined objects
1024  // For python3, return id of object as hash which is status quo in python2.
1025  out <<
1026  indent() << "def __hash__(self):" << endl;
1027  indent_up();
1028 
1029  out <<
1030  indent() << "return id(self)" << endl;
1031  indent_down();
1032  } else if (!gen_dynamic_) {
1033  // no base class available to implement __eq__ and __repr__ and __ne__ for us
1034  // so we must provide one that uses __slots__
1035  out <<
1036  indent() << "def __repr__(self):" << endl <<
1037  indent() << " L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1038  indent() << " for key in self.__slots__]" << endl <<
1039  indent() << " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1040  endl;
1041 
1042  // Equality method that compares each attribute by value and type, walking __slots__
1043  out <<
1044  indent() << "def __eq__(self, other):" << endl <<
1045  indent() << " if not isinstance(other, self.__class__):" << endl <<
1046  indent() << " return False" << endl <<
1047  indent() << " for attr in self.__slots__:" << endl <<
1048  indent() << " my_val = getattr(self, attr)" << endl <<
1049  indent() << " other_val = getattr(other, attr)" << endl <<
1050  indent() << " if my_val != other_val:" << endl <<
1051  indent() << " return False" << endl <<
1052  indent() << " return True" << endl <<
1053  endl;
1054 
1055  out <<
1056  indent() << "def __ne__(self, other):" << endl <<
1057  indent() << " return not (self == other)" << endl <<
1058  endl;
1059  }
1060  indent_down();
1061 }
1062 
1067  t_struct* tstruct) {
1068  const vector<t_field*>& fields = tstruct->get_members();
1069  vector<t_field*>::const_iterator f_iter;
1070 
1071  indent(out) <<
1072  "def read(self, iprot):" << endl;
1073  indent_up();
1074 
1075  indent(out) <<
1076  "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1077  "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1078  "and self.thrift_spec is not None "
1079  "and fastbinary is not None:" << endl;
1080  indent_up();
1081 
1082  indent(out) <<
1083  "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1084 #ifdef SANDESH
1085  indent(out) <<
1086  "return 0" << endl;
1087 #else
1088  indent(out) <<
1089  "return" << endl;
1090 #endif
1091  indent_down();
1092 
1093 #ifdef SANDESH
1094  indent(out) <<
1095  "read_cnt = 0" << endl;
1096 #endif
1097 
1098 #ifdef SANDESH
1099  indent(out) <<
1100  "length = iprot.readStructBegin()" << endl;
1101  indent(out) <<
1102  "if length < 0: return -1" << endl;
1103  indent(out) <<
1104  "read_cnt += length" << endl;
1105 #else
1106  indent(out) <<
1107  "iprot.readStructBegin()" << endl;
1108 #endif
1109 
1110  // Loop over reading in fields
1111  indent(out) <<
1112  "while True:" << endl;
1113  indent_up();
1114 
1115  // Read beginning field marker
1116 #ifdef SANDESH
1117  indent(out) <<
1118  "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1119  indent(out) <<
1120  "if length < 0: return -1" << endl;
1121  indent(out) <<
1122  "read_cnt += length" << endl;
1123 #else
1124  indent(out) <<
1125  "(fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1126 #endif
1127 
1128  // Check for field STOP marker and break
1129  indent(out) <<
1130  "if ftype == TType.STOP:" << endl;
1131  indent_up();
1132  indent(out) <<
1133  "break" << endl;
1134  indent_down();
1135 
1136  // Switch statement on the field we are reading
1137  bool first = true;
1138 
1139  // Generate deserialization code for known cases
1140  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1141  if (first) {
1142  first = false;
1143  out <<
1144  indent() << "if ";
1145  } else {
1146  out <<
1147  indent() << "elif ";
1148  }
1149  out << "fid == " << (*f_iter)->get_key() << ":" << endl;
1150  indent_up();
1151  indent(out) << "if ftype == " << type_to_enum((*f_iter)->get_type()) << ":" << endl;
1152  indent_up();
1153  generate_deserialize_field(out, *f_iter, "self.");
1154  indent_down();
1155  out <<
1156  indent() << "else:" << endl <<
1157  indent() << " iprot.skip(ftype)" << endl;
1158  indent_down();
1159  }
1160 
1161  // In the default case we skip the field
1162  out <<
1163  indent() << "else:" << endl <<
1164  indent() << " iprot.skip(ftype)" << endl;
1165 
1166  // Read field end marker
1167 #ifdef SANDESH
1168  indent(out) <<
1169  "length = iprot.readFieldEnd()" << endl;
1170  indent(out) <<
1171  "if length < 0: return -1" << endl;
1172  indent(out) <<
1173  "read_cnt += length" << endl;
1174 #else
1175  indent(out) <<
1176  "iprot.readFieldEnd()" << endl;
1177 #endif
1178 
1179  indent_down();
1180 
1181 #ifdef SANDESH
1182  indent(out) <<
1183  "length = iprot.readStructEnd()" << endl;
1184  indent(out) <<
1185  "if length < 0: return -1" << endl;
1186  indent(out) <<
1187  "read_cnt += length" << endl;
1188 #else
1189  indent(out) <<
1190  "iprot.readStructEnd()" << endl;
1191 #endif
1192 
1193 #ifdef SANDESH
1194  indent(out) <<
1195  "return read_cnt" << endl;
1196 #endif
1197 
1198  indent_down();
1199  out << endl;
1200 }
1201 
1203  t_struct* tstruct) {
1204  string name = tstruct->get_name();
1205  const vector<t_field*>& fields = tstruct->get_sorted_members();
1206  vector<t_field*>::const_iterator f_iter;
1207 
1208  indent(out) <<
1209  "def write(self, oprot):" << endl;
1210  indent_up();
1211 
1212  indent(out) <<
1213  "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1214  "and self.thrift_spec is not None "
1215  "and fastbinary is not None:" << endl;
1216  indent_up();
1217 
1218  indent(out) <<
1219  "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1220 #ifdef SANDESH
1221  indent(out) <<
1222  "return 0" << endl;
1223 #else
1224  indent(out) <<
1225  "return" << endl;
1226 #endif
1227  indent_down();
1228 
1229 #ifdef SANDESH
1230  indent(out) <<
1231  "if oprot.writeStructBegin(self.__class__.__name__) < 0: return -1" << endl;
1232 #else
1233  indent(out) <<
1234  "oprot.writeStructBegin('" << name << "')" << endl;
1235 #endif
1236 
1237  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1238  // Write field header
1239 #ifdef SANDESH
1240  indent(out) <<
1241  "if self." << (*f_iter)->get_name() << " is not None:" << endl;
1242  indent_up();
1243  indent(out) <<
1244  "annotations = {}" << endl;
1245  if (!((*f_iter)->annotations_.empty())) {
1246  std::map<std::string, std::string>::iterator it;
1247  for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1248  if (((*f_iter)->get_name() == "name") && (it->first == "key")) {
1249  indent(out) << "if self._table is None or self._table == '': return -1" << endl;
1250  indent(out) << "annotations['key'] = " << "self._table" << endl;
1251  } else {
1252  indent(out) << "annotations['" << (*it).first << "'] = '" <<
1253  (*it).second << "'" << endl;
1254  }
1255  }
1256  }
1257  indent(out) <<
1258  "if oprot.writeFieldBegin(" <<
1259  "'" << (*f_iter)->get_name() << "', " <<
1260  type_to_enum((*f_iter)->get_type()) << ", " <<
1261  (*f_iter)->get_key() << ", annotations) < 0: return -1" << endl;
1262 #else
1263  indent(out) <<
1264  "if self." << (*f_iter)->get_name() << " is not None:" << endl;
1265  indent_up();
1266  indent(out) <<
1267  "oprot.writeFieldBegin(" <<
1268  "'" << (*f_iter)->get_name() << "', " <<
1269  type_to_enum((*f_iter)->get_type()) << ", " <<
1270  (*f_iter)->get_key() << ")" << endl;
1271 #endif
1272 
1273  // Write field contents
1274  generate_serialize_field(out, *f_iter, "self.");
1275 
1276  // Write field closer
1277 #ifdef SANDESH
1278  indent(out) <<
1279  "if oprot.writeFieldEnd() < 0: return -1" << endl;
1280 #else
1281  indent(out) <<
1282  "oprot.writeFieldEnd()" << endl;
1283 #endif
1284  indent_down();
1285  }
1286 
1287  // Write the struct map
1288 #ifdef SANDESH
1289  out <<
1290  indent() << "if oprot.writeFieldStop() < 0: return -1" << endl <<
1291  indent() << "if oprot.writeStructEnd() < 0: return -1" << endl <<
1292  indent() << "return 0" << endl;
1293 #else
1294  out <<
1295  indent() << "oprot.writeFieldStop()" << endl <<
1296  indent() << "oprot.writeStructEnd()" << endl;
1297 #endif
1298  out << endl;
1299  indent_down();
1301  out <<
1302  endl;
1303 }
1304 
1306  t_struct* tstruct) {
1307  indent(out) << "def validate(self):" << endl;
1308  indent_up();
1309 
1310  const vector<t_field*>& fields = tstruct->get_members();
1311 
1312  if (fields.size() > 0) {
1313  vector<t_field*>::const_iterator f_iter;
1314 
1315  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1316  t_field* field = (*f_iter);
1317  if (field->get_req() == t_field::T_REQUIRED) {
1318  indent(out) << "if self." << field->get_name() << " is None:" << endl;
1319  indent(out) << " raise TProtocol.TProtocolException(message='Required field " <<
1320  field->get_name() << " is unset!')" << endl;
1321  }
1322  }
1323  }
1324 
1325  indent(out) << "return" << endl << endl;
1326  indent_down();
1327 }
1328 
1329 #ifdef SANDESH
1330 void t_py_generator::generate_py_sandesh(t_sandesh *tsandesh) {
1331  generate_py_sandesh_definition(f_types_, tsandesh);
1332 }
1333 
1334 void t_py_generator::generate_py_sandesh_definition(ofstream& out,
1335  t_sandesh* tsandesh) {
1336  const vector<t_field*>& members = tsandesh->get_members();
1337  const vector<t_field*>& sorted_members = tsandesh->get_sorted_members();
1338  vector<t_field*>::const_iterator m_iter;
1339  const t_base_type *sandesh_type = (t_base_type *)tsandesh->get_type();
1340 
1341  std::string base_class;
1342  if (sandesh_type->is_sandesh_system()) {
1343  base_class = "sandesh_base.SandeshSystem";
1344  } else if (sandesh_type->is_sandesh_object()) {
1345  base_class = "sandesh_base.SandeshObject";
1346  } else if (sandesh_type->is_sandesh_flow()) {
1347  if (sandesh_type->is_sandesh_session()) {
1348  base_class = "sandesh_base.SandeshFlowSession";
1349  } else {
1350  base_class = "sandesh_base.SandeshFlow";
1351  }
1352  } else if (sandesh_type->is_sandesh_request()) {
1353  base_class = "sandesh_base.SandeshRequest";
1354  } else if (sandesh_type->is_sandesh_response()) {
1355  base_class = "sandesh_base.SandeshResponse";
1356  } else if (sandesh_type->is_sandesh_uve()) {
1357  base_class = "sandesh_base.SandeshUVE";
1358  } else if (sandesh_type->is_sandesh_dynamic_uve()) {
1359  base_class = "sandesh_base.SandeshDynamicUVE";
1360  } else if (sandesh_type->is_sandesh_alarm()) {
1361  base_class = "sandesh_base.SandeshAlarm";
1362  } else if (sandesh_type->is_sandesh_trace() ||
1363  sandesh_type->is_sandesh_trace_object()) {
1364  base_class = "sandesh_base.SandeshTrace";
1365  } else {
1366  throw "compiler error: unsupported sandesh type " +
1367  t_base_type::t_base_name(sandesh_type->get_base());
1368  }
1369 
1370  out << std::endl <<
1371  "class " << tsandesh->get_name();
1372  out << "(" << base_class << "):" << endl;
1373  indent_up();
1374  // generate_python_docstring(out, tstruct);
1375 
1376  out << endl;
1377 
1378  /*
1379  Here we generate the structure specification for the fastbinary codec.
1380  These specifications have the following structure:
1381  thrift_spec -> tuple of item_spec
1382  item_spec -> None | (tag, type_enum, name, spec_args, default)
1383  tag -> integer
1384  type_enum -> TType.I32 | TType.STRING | TType.STRUCT | ...
1385  name -> string_literal
1386  default -> None # Handled by __init__
1387  spec_args -> None # For simple types
1388  | (type_enum, spec_args) # Value type for list/set
1389  | (type_enum, spec_args, type_enum, spec_args)
1390  # Key and value for map
1391  | (class_name, spec_args_ptr) # For struct/exception
1392  class_name -> identifier # Basically a pointer to the class
1393  spec_args_ptr -> expression # just class_name.spec_args
1394 
1395  TODO(dreiss): Consider making this work for structs with negative tags.
1396  */
1397 
1398  if (gen_slots_) {
1399  indent(out) << "__slots__ = [ " << endl;
1400  indent_up();
1401  for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1402  indent(out) << "'" << (*m_iter)->get_name() << "'," << endl;
1403  }
1404  indent_down();
1405  indent(out) << " ]" << endl << endl;
1406 
1407  }
1408 
1409  // TODO(dreiss): Look into generating an empty tuple instead of None
1410  // for class with no members.
1411  // TODO(dreiss): Test encoding of class where some inner class
1412  // don't have thrift_spec.
1413  if (sorted_members.empty() || (sorted_members[0]->get_key() >= 0)) {
1414  indent(out) << "thrift_spec = (" << endl;
1415  indent_up();
1416 
1417  int sorted_keys_pos = 0;
1418  for (m_iter = sorted_members.begin(); m_iter != sorted_members.end(); ++m_iter) {
1419 
1420  for (; sorted_keys_pos != (*m_iter)->get_key(); sorted_keys_pos++) {
1421  indent(out) << "None, # " << sorted_keys_pos << endl;
1422  }
1423 
1424  indent(out) << "(" << (*m_iter)->get_key() << ", "
1425  << type_to_enum((*m_iter)->get_type()) << ", "
1426  << "'" << (*m_iter)->get_name() << "'" << ", "
1427  << type_to_spec_args((*m_iter)->get_type()) << ", "
1428  << render_field_default_value(*m_iter) << ", "
1429  << "),"
1430  << " # " << sorted_keys_pos
1431  << endl;
1432 
1433  sorted_keys_pos ++;
1434  }
1435 
1436  indent_down();
1437  indent(out) << ")" << endl << endl;
1438  } else {
1439  indent(out) << "thrift_spec = None" << endl << endl;
1440  }
1441 
1442  if (sandesh_type->is_sandesh_system()) {
1443  indent(out) << "rate_limit_buffer = util.deque(maxlen=sandesh_base."
1444  "SandeshSystem._DEFAULT_SEND_RATELIMIT)" << endl << endl;
1445  indent(out) << "do_rate_limit_drop_log = True" << endl << endl;
1446  }
1447 
1448  {
1449  out <<
1450  indent() << "def __init__(self";
1451 
1452  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1453  // skip const string
1454  t_type* type = get_true_type((*m_iter)->get_type());
1455  if (type->is_static_const_string()) {
1456  continue;
1457  }
1458  // This fills in default values, as opposed to nulls
1459  out << ", " << declare_argument(*m_iter);
1460  }
1461 
1462  if (sandesh_type->is_sandesh_system() ||
1463  sandesh_type->is_sandesh_object() ||
1464  sandesh_type->is_sandesh_flow()) {
1465  out << ", category='" << "__default__" <<
1466  "', level=SandeshLevel.SYS_INFO";
1467  }
1468  if (sandesh_type->is_sandesh_uve() ||
1469  sandesh_type->is_sandesh_dynamic_uve() ||
1470  sandesh_type->is_sandesh_alarm()) {
1471  out << ", table=None";
1472  }
1473  out << ", sandesh=sandesh_base.sandesh_global):" << endl;
1474 
1475  indent_up();
1476  if (sandesh_type->is_sandesh_trace()) {
1477  indent(out) << base_class <<
1478  ".__init__(self, type=SandeshType.TRACE)" << endl;
1479  } else if (sandesh_type->is_sandesh_trace_object()) {
1480  indent(out) << base_class <<
1481  ".__init__(self, type=SandeshType.TRACE_OBJECT)" << endl;
1482  } else {
1483  indent(out) << base_class << ".__init__(self)" << endl;
1484  }
1485 
1486  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
1487  // Initialize fields
1488  t_type* type = (*m_iter)->get_type();
1489  if (!type->is_base_type() && !type->is_enum() && (*m_iter)->get_value() != NULL) {
1490  indent(out) <<
1491  "if " << (*m_iter)->get_name() << " is " << "self.thrift_spec[" <<
1492  (*m_iter)->get_key() << "][4]:" << endl;
1493  indent(out) << " " << (*m_iter)->get_name() << " = " <<
1494  render_field_default_value(*m_iter) << endl;
1495  } else if (type->is_static_const_string()) {
1496  indent(out) <<
1497  "self." << (*m_iter)->get_name() << " = " <<
1498  render_const_value(type, (*m_iter)->get_value()) << endl;
1499  } else {
1500  indent(out) <<
1501  "self." << (*m_iter)->get_name() << " = " << (*m_iter)->get_name() << endl;
1502  }
1503  }
1504 
1505  indent(out) << "self._scope = sandesh.scope()" << endl;
1506  indent(out) << "self._module = sandesh.module()" << endl;
1507  indent(out) << "self._source = sandesh.source_id()" << endl;
1508  indent(out) << "self._node_type = sandesh.node_type()" << endl;
1509  indent(out) << "self._instance_id = sandesh.instance_id()" << endl;
1510  indent(out) << "self._seqnum = 0" << endl;
1511  indent(out) << "self._timestamp = UTCTimestampUsec()" << endl;
1512  indent(out) << "self._versionsig = " << tsandesh->get_4byte_fingerprint() << endl;
1513  generate_py_sandesh_hint(out, tsandesh);
1514  if (sandesh_type->is_sandesh_system() ||
1515  sandesh_type->is_sandesh_object() ||
1516  sandesh_type->is_sandesh_flow()) {
1517  indent(out) << "self._category = category" << endl;
1518  indent(out) << "self._level = level" << endl;
1519  }
1520  if (sandesh_type->is_sandesh_uve() ||
1521  sandesh_type->is_sandesh_dynamic_uve() ||
1522  sandesh_type->is_sandesh_alarm()) {
1523  indent(out) << "if table is not None:" << endl;
1524  indent_up();
1525  indent(out) << "self.data._table = table" << endl;
1526  indent_down();
1527  }
1528  indent_down();
1529 
1530  out << endl;
1531  }
1532 
1533  if (sandesh_type->is_sandesh_system() ||
1534  sandesh_type->is_sandesh_object() ||
1535  sandesh_type->is_sandesh_flow()) {
1536  generate_py_sandesh_async(out, tsandesh);
1537  } else if (sandesh_type->is_sandesh_request()) {
1538  generate_py_sandesh_request(out, tsandesh);
1539  } else if (sandesh_type->is_sandesh_response()) {
1540  generate_py_sandesh_response(out, tsandesh);
1541  } else if (sandesh_type->is_sandesh_uve() ||
1542  sandesh_type->is_sandesh_alarm()) {
1543  generate_py_sandesh_uve(out, tsandesh, true);
1544  } else if (sandesh_type->is_sandesh_dynamic_uve()) {
1545  generate_py_sandesh_uve(out, tsandesh, false);
1546  } else if (sandesh_type->is_sandesh_trace() ||
1547  sandesh_type->is_sandesh_trace_object()) {
1548  generate_py_sandesh_trace(out, tsandesh);
1549  }
1550 
1551  generate_py_sandesh_logger(out, tsandesh);
1552 
1553  if (!gen_dynamic_) {
1554  generate_py_sandesh_reader(out, tsandesh);
1555  generate_py_sandesh_writer(out, tsandesh);
1556  }
1557 
1558  generate_py_sandesh_compare(out, tsandesh);
1559  generate_py_sandesh_sizeof(out, tsandesh);
1560 
1561  if (!gen_slots_) {
1562  // Printing utilities so that on the command line thrift
1563  // structs look pretty like dictionaries
1564  out <<
1565  indent() << "def __repr__(self):" << endl <<
1566  indent() << " L = ['%s=%r' % (key, value)" << endl <<
1567  indent() << " for key, value in self.__dict__.items()]" << endl <<
1568  indent() << " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1569  endl;
1570 
1571  // Equality and inequality methods that compare by value
1572  out <<
1573  indent() << "def __eq__(self, other):" << endl;
1574  indent_up();
1575  out <<
1576  indent() << "return isinstance(other, self.__class__) and "
1577  "self.__dict__ == other.__dict__" << endl;
1578  indent_down();
1579  out << endl;
1580 
1581  out <<
1582  indent() << "def __ne__(self, other):" << endl;
1583  indent_up();
1584 
1585  out <<
1586  indent() << "return not (self == other)" << endl;
1587  indent_down();
1588  } else if (!gen_dynamic_) {
1589  // no base class available to implement __eq__ and __repr__ and __ne__ for us
1590  // so we must provide one that uses __slots__
1591  out <<
1592  indent() << "def __repr__(self):" << endl <<
1593  indent() << " L = ['%s=%r' % (key, getattr(self, key))" << endl <<
1594  indent() << " for key in self.__slots__]" << endl <<
1595  indent() << " return '%s(%s)' % (self.__class__.__name__, ', '.join(L))" << endl <<
1596  endl;
1597 
1598  // Equality method that compares each attribute by value and type, walking __slots__
1599  out <<
1600  indent() << "def __eq__(self, other):" << endl <<
1601  indent() << " if not isinstance(other, self.__class__):" << endl <<
1602  indent() << " return False" << endl <<
1603  indent() << " for attr in self.__slots__:" << endl <<
1604  indent() << " my_val = getattr(self, attr)" << endl <<
1605  indent() << " other_val = getattr(other, attr)" << endl <<
1606  indent() << " if my_val != other_val:" << endl <<
1607  indent() << " return False" << endl <<
1608  indent() << " return True" << endl <<
1609  endl;
1610 
1611  out <<
1612  indent() << "def __ne__(self, other):" << endl <<
1613  indent() << " return not (self == other)" << endl <<
1614  endl;
1615  }
1616  indent_down();
1617 }
1618 
1622 void t_py_generator::generate_py_sandesh_reader(ofstream& out,
1623  t_sandesh* tsandesh) {
1624  const vector<t_field*>& fields = tsandesh->get_members();
1625  vector<t_field*>::const_iterator f_iter;
1626 
1627  indent(out) <<
1628  "def read(self, iprot):" << endl;
1629  indent_up();
1630 
1631  indent(out) <<
1632  "if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1633  "and isinstance(iprot.trans, TTransport.CReadableTransport) "
1634  "and self.thrift_spec is not None "
1635  "and fastbinary is not None:" << endl;
1636  indent_up();
1637 
1638  indent(out) <<
1639  "fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))" << endl;
1640  indent(out) <<
1641  "return -1" << endl;
1642  indent_down();
1643 
1644  indent(out) <<
1645  "read_cnt = 0" << endl;
1646 
1647  indent(out) <<
1648  "(length, sandesh_name) = iprot.readSandeshBegin()" << endl;
1649  indent(out) <<
1650  "if length < 0: return -1" << endl;
1651  indent(out) <<
1652  "read_cnt += length" << endl;
1653 
1654  // Loop over reading in fields
1655  indent(out) <<
1656  "while True:" << endl;
1657  indent_up();
1658 
1659  // Read beginning field marker
1660  indent(out) <<
1661  "(length, fname, ftype, fid) = iprot.readFieldBegin()" << endl;
1662  indent(out) <<
1663  "if length < 0: return -1" << endl;
1664  indent(out) <<
1665  "read_cnt += length" << endl;
1666 
1667  // Check for field STOP marker and break
1668  indent(out) <<
1669  "if ftype == TType.STOP:" << endl;
1670  indent_up();
1671  indent(out) <<
1672  "break" << endl;
1673  indent_down();
1674 
1675  // Switch statement on the field we are reading
1676  bool first = true;
1677 
1678  // Generate deserialization code for known cases
1679  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1680  if (first) {
1681  first = false;
1682  out <<
1683  indent() << "if ";
1684  } else {
1685  out <<
1686  indent() << "elif ";
1687  }
1688  out << "fid == " << (*f_iter)->get_key() << ":" << endl;
1689  indent_up();
1690  indent(out) << "if ftype == " << type_to_enum((*f_iter)->get_type()) << ":" << endl;
1691  indent_up();
1692  generate_deserialize_field(out, *f_iter, "self.");
1693  indent_down();
1694  out <<
1695  indent() << "else:" << endl <<
1696  indent() << " iprot.skip(ftype)" << endl;
1697  indent_down();
1698  }
1699 
1700  // In the default case we skip the field
1701  out <<
1702  indent() << "else:" << endl <<
1703  indent() << " iprot.skip(ftype)" << endl;
1704 
1705  // Read field end marker
1706  indent(out) <<
1707  "length = iprot.readFieldEnd()" << endl;
1708  indent(out) <<
1709  "if length < 0: return -1" << endl;
1710  indent(out) <<
1711  "read_cnt += length" << endl;
1712 
1713  indent_down();
1714 
1715  indent(out) <<
1716  "length = iprot.readSandeshEnd()" << endl;
1717  indent(out) <<
1718  "if length < 0: return -1" << endl;
1719  indent(out) <<
1720  "read_cnt += length" << endl;
1721 
1722  indent(out) <<
1723  "return read_cnt" << endl;
1724 
1725  indent_down();
1726  out << endl;
1727 }
1728 
1729 void t_py_generator::generate_py_sandesh_writer(ofstream& out,
1730  t_sandesh* tsandesh) {
1731  const vector<t_field*>& fields = tsandesh->get_sorted_members();
1732  vector<t_field*>::const_iterator f_iter;
1733 
1734  indent(out) <<
1735  "def write(self, oprot):" << endl;
1736  indent_up();
1737 
1738  indent(out) <<
1739  "if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated "
1740  "and self.thrift_spec is not None "
1741  "and fastbinary is not None:" << endl;
1742  indent_up();
1743 
1744  indent(out) <<
1745  "oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))" << endl;
1746  indent(out) <<
1747  "return 0" << endl;
1748  indent_down();
1749 
1750  indent(out) <<
1751  "if oprot.writeSandeshBegin(self.__class__.__name__) < 0: return -1" << endl;
1752  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1753  // Write field header
1754  indent(out) <<
1755  "if self." << (*f_iter)->get_name() << " is not None:" << endl;
1756  indent_up();
1757  indent(out) <<
1758  "annotations = {}" << endl;
1759  if (!((*f_iter)->annotations_.empty())) {
1760  std::map<std::string, std::string>::iterator it;
1761  for (it = (*f_iter)->annotations_.begin(); it != (*f_iter)->annotations_.end(); it++) {
1762  indent(out) << "annotations['" << (*it).first << "'] = '" <<
1763  (*it).second << "'" << endl;
1764  }
1765  }
1766  indent(out) <<
1767  "if oprot.writeFieldBegin(" <<
1768  "'" << (*f_iter)->get_name() << "', " <<
1769  type_to_enum((*f_iter)->get_type()) << ", " <<
1770  (*f_iter)->get_key() << ", annotations) < 0: return -1" << endl;
1771 
1772  // Write field contents
1773  generate_serialize_field(out, *f_iter, "self.");
1774 
1775  // Write field closer
1776  indent(out) <<
1777  "if oprot.writeFieldEnd() < 0: return -1" << endl;
1778 
1779  indent_down();
1780  }
1781 
1782  // Write the struct map
1783  indent(out) <<
1784  "if oprot.writeFieldStop() < 0: return -1" << endl;
1785  indent(out) <<
1786  "if oprot.writeSandeshEnd() < 0: return -1" << endl;
1787  indent(out) <<
1788  "return 0" << endl;
1789  out << endl;
1790  indent_down();
1791  generate_py_sandesh_required_validator(out, tsandesh);
1792  out <<
1793  endl;
1794 }
1795 
1796 void t_py_generator::generate_py_sandesh_required_validator(ofstream& out,
1797  t_sandesh* tsandesh) {
1798  indent(out) << "def validate(self):" << endl;
1799  indent_up();
1800 
1801  const vector<t_field*>& fields = tsandesh->get_members();
1802 
1803  if (fields.size() > 0) {
1804  vector<t_field*>::const_iterator f_iter;
1805 
1806  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1807  t_field* field = (*f_iter);
1808  if (field->get_req() == t_field::T_REQUIRED) {
1809  indent(out) << "if self." << field->get_name() << " is None:" << endl;
1810  indent(out) << " raise TProtocol.TProtocolException(message='Required field " <<
1811  field->get_name() << " is unset!')" << endl;
1812  }
1813  }
1814  }
1815 
1816  indent(out) << "return" << endl << endl;
1817  indent_down();
1818 }
1819 
1820 void t_py_generator::generate_py_sandesh_compare(ofstream& out,
1821  t_sandesh* tsandesh) {
1822  const vector<t_field*>& fields = tsandesh->get_sorted_members();
1823  vector<t_field*>::const_iterator f_iter;
1824 
1825  indent(out) <<
1826  "def compare(self, other):" << endl;
1827  indent_up();
1828  indent(out) <<
1829  "if not isinstance(other, self.__class__):" << endl;
1830  indent_up();
1831  indent(out) <<
1832  "return False" << endl;
1833  indent_down();
1834 
1835  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1836  indent(out) <<
1837  "if self." << (*f_iter)->get_name() << " != " <<
1838  "other." << (*f_iter)->get_name() << ":" << endl;
1839  indent_up();
1840  indent(out) << "return False" << endl;
1841  indent_down();
1842  }
1843 
1844  indent(out) << "return True" << endl << endl;
1845  indent_down();
1846 }
1847 
1848 void t_py_generator::generate_py_sandesh_http_attr(ofstream& out,
1849  t_type *ftype, const std::string& namel, const std::string& namer) {
1850 
1851  if (ftype->is_base_type()) {
1852 
1853  t_base_type::t_base bftype = ((t_base_type *)ftype)->get_base();
1854 
1855  indent(out) <<
1856  "if bottle.request.query." << namer << ":" << endl;
1857  indent_up();
1858  if (bftype == t_base_type::TYPE_STRING) {
1859  indent(out) <<
1860  "sandesh_req." << namel << " = str(" <<
1861  "bottle.request.query." << namer << ")" << endl;
1862  } else if (bftype == t_base_type::TYPE_UUID) {
1863  indent(out) << "try:" << endl;
1864  indent_up();
1865  indent(out) << "sandesh_req." << namel << " = uuid.UUID("
1866  << "bottle.request.query." << namer << ")" << endl;
1867  indent_down();
1868  indent(out) << "except ValueError:" << endl;
1869  indent_up();
1870  indent(out) << "return SandeshHttp.http_error('Invalid value for "
1871  << namel << ":" << namer << "')" << endl;
1872  indent_down();
1873  } else if (bftype == t_base_type::TYPE_IPADDR) {
1874  indent(out) << "try:" << endl;
1875  indent_up();
1876  indent(out) << "sandesh_req." << namel << " = netaddr.IPAddress("
1877  << "bottle.request.query." << namer << ")" << endl;
1878  indent_down();
1879  indent(out) << "except ValueError:" << endl;
1880  indent_up();
1881  indent(out) << "return SandeshHttp.http_error('Invalid value for "
1882  << namel << ":" << namer << "')" << endl;
1883  indent_down();
1884  } else {
1885  assert(bftype == t_base_type::TYPE_BOOL ||
1886  bftype == t_base_type::TYPE_BYTE ||
1887  bftype == t_base_type::TYPE_I16 ||
1888  bftype == t_base_type::TYPE_I32 ||
1889  bftype == t_base_type::TYPE_I64 ||
1890  bftype == t_base_type::TYPE_U16 ||
1891  bftype == t_base_type::TYPE_U32 ||
1892  bftype == t_base_type::TYPE_U64 ||
1893  bftype == t_base_type::TYPE_IPV4);
1894  indent(out) <<
1895  "try:" << endl;
1896  indent_up();
1897  indent(out) <<
1898  "sandesh_req." << namel << " = int(" <<
1899  "bottle.request.query." << namer << ")" << endl;
1900  indent_down();
1901  indent(out) <<
1902  "except ValueError:" << endl;
1903  indent_up();
1904  indent(out) <<
1905  "return SandeshHttp.http_error('Invalid data provided in Sandesh Request')" << endl;
1906  indent_down();
1907  }
1908  indent_down();
1909 
1910  } else {
1911  // Ignore this field for now
1912  }
1913 }
1914 
1915 void t_py_generator::generate_py_sandesh_http_request_handler(ofstream& out,
1916  t_sandesh* tsandesh) {
1917  const vector<t_field*>& fields = tsandesh->get_sorted_members();
1918  vector<t_field*>::const_iterator f_iter;
1919 
1920  indent(out) <<
1921  "@staticmethod" << endl;
1922  indent(out) <<
1923  "def handle_http_request(sandesh=sandesh_base.sandesh_global):" << endl;
1924  indent_up();
1925  indent(out) <<
1926  "sandesh_req = " << tsandesh->get_name() << "()" << endl;
1927  indent(out) <<
1928  "if not sandesh_req:" << endl;
1929  indent_up();
1930  indent(out) << "return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->get_name() <<
1931  "\" not implemented')" << endl;
1932  indent_down();
1933  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1934  t_type *ftype = (*f_iter)->get_type();
1935  if (f_iter == fields.begin()) {
1936  generate_py_sandesh_http_attr(out, ftype, (*f_iter)->get_name(), "x");
1937  }
1938  generate_py_sandesh_http_attr(out, ftype, (*f_iter)->get_name(), (*f_iter)->get_name());
1939  }
1940  // TODO: Call validate() to check if all the mandatory parameters are provided
1941  indent(out) << "sandesh_req._context = bottle.request.url" << endl;
1942  indent(out) << "handle_req_fn = getattr(sandesh_req, \"handle_request\", None)" << endl;
1943  indent(out) << "if callable(handle_req_fn):" << endl;
1944  indent_up();
1945  indent(out) << "handle_req_fn(sandesh_req)" << endl;
1946  indent_down();
1947  indent(out) << "else:" << endl;
1948  indent_up();
1949  indent(out) << "return SandeshHttp.http_error('Sandesh Request \"" << tsandesh->get_name() <<
1950  "\" not implemented')" << endl;
1951  indent_down();
1952  indent(out) << "resp = SandeshHttp.get_http_response()" << endl;
1953  indent(out) << "if resp:" << endl;
1954  indent_up();
1955  indent(out) << "return resp" << endl;
1956  indent_down();
1957  indent(out) << "else:" << endl;
1958  indent_up();
1959  indent(out) << "return SandeshHttp.http_error('No Response for Sandesh Request \"" <<
1960  tsandesh->get_name() << "\"')" << endl;
1961  indent_down();
1962  indent(out) << endl;
1963  indent_down();
1964  indent_down();
1965 }
1966 
1967 void t_py_generator::generate_py_sandesh_request_list(ofstream& out) {
1968  out << endl << endl;
1969  out << "_SANDESH_REQUEST_LIST = [" << endl;
1970  std::vector<std::string>::const_iterator it;
1971  for (it = sandesh_req_list_.begin(); it != sandesh_req_list_.end(); ++it) {
1972  indent(out) << *it << "," << endl;
1973  }
1974  out << "]" << endl;
1975 }
1976 
1977 void t_py_generator::generate_py_sandesh_http_request_list(ofstream& out,
1978  t_sandesh* tsandesh) {
1979  indent(out) <<
1980  "{ 'uri':" << "'/Snh_" << tsandesh->get_name() << "'" <<
1981  ", 'method':" << "ttypes." << tsandesh->get_name() << ".handle_http_request " <<
1982  "}," << endl;
1983 }
1984 
1985 void t_py_generator::py_autogen_sandesh_http_request_open(ofstream& out) {
1986  indent(out) << endl;
1987  indent(out) <<
1988  "_HTTP_REQUEST_LIST = [" << endl;
1989 }
1990 
1991 void t_py_generator::py_autogen_sandesh_http_request_close(ofstream& out) {
1992  out << "]" << endl << endl;
1993 }
1994 
1995 std::string t_py_generator::py_autogen_sandesh_request_skeleton_comment() {
1996  return
1997  std::string("\n") +
1998  "# This autogenerated skeleton file illustrates the implementation of" +
1999  "\n" +
2000  "# derived class to handle the sandesh request." +
2001  "\n";
2002 }
2003 
2004 void t_py_generator::generate_py_sandesh_skeleton_request(ofstream& out,
2005  t_sandesh* tsandesh) {
2006  const vector<t_field*>& members = tsandesh->get_members();
2007  vector<t_field*>::const_iterator m_iter;
2008 
2009  out << endl <<
2010  "# Create a derived class from \"" << tsandesh->get_name() << "\" to handle ";
2011  out << endl <<
2012  "# the sandesh request. Add this derived class \"" << tsandesh->get_name() << "_derived\"";
2013  out << endl <<
2014  "# in module " << tsandesh->get_name() << "_derived.py and " <<
2015  "add it in your package" << endl;
2016 
2017  out << endl <<
2018  "class " << tsandesh->get_name() << "_derived";
2019  out << "(" << tsandesh->get_name() << "):" << endl;
2020  indent_up();
2021  out << endl;
2022 
2023  if (members.size() > 0) {
2024  out <<
2025  indent() << "def __init__(self):" << endl;
2026  indent_up();
2027  out <<
2028  indent() << tsandesh->get_name() << ".__init__(self";
2029 
2030  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
2031  // skip const string
2032  t_type* type = get_true_type((*m_iter)->get_type());
2033  if (type->is_static_const_string()) {
2034  continue;
2035  }
2036  // This fills in default values, as opposed to nulls
2037  out << ", " << declare_argument(*m_iter);
2038  }
2039  out << ")" << endl;
2040  indent_down();
2041  }
2042  out << endl;
2043  out << indent() << "def handle_request(self):" << endl;
2044  indent_up();
2045  indent(out) <<
2046  "# Add your code to handle the \"" << tsandesh->get_name() <<
2047  "\" request" << endl;
2048  indent(out) <<
2049  "pass" << endl;
2050  indent_down();
2051  indent(out) << endl;
2052 }
2053 
2054 void t_py_generator::generate_struct_log(ofstream& out,
2055  string prefix,
2056  string log_str) {
2057  indent(out) <<
2058  log_str << ".write('<< ')" << endl;
2059  indent(out) <<
2060  log_str << ".write(" << prefix << ".log())" << endl;
2061  indent(out) <<
2062  log_str << ".write('>>')" << endl;
2063 }
2064 
2065 void t_py_generator::generate_container_log(ofstream& out,
2066  string prefix,
2067  t_type* ttype,
2068  string log_str) {
2069  if (ttype->is_map()) {
2070  string kiter = tmp("kiter");
2071  string viter = tmp("viter");
2072  indent(out) <<
2073  log_str << ".write('{ ')" << endl;
2074  indent(out) <<
2075  "for " << kiter << "," << viter << " in " << prefix << ".items():" << endl;
2076  indent_up();
2077  t_field kfield(((t_map*)ttype)->get_key_type(), kiter);
2078  generate_field_log(out, &kfield, log_str, "");
2079  indent(out) <<
2080  log_str << ".write(' : ')" << endl;
2081  t_field vfield(((t_map*)ttype)->get_val_type(), viter);
2082  generate_field_log(out, &vfield, log_str, "");
2083  indent_down();
2084  indent(out) <<
2085  log_str << ".write(' }')" << endl;
2086  } else if (ttype->is_set()) {
2087  string iter = tmp("iter");
2088  indent(out) <<
2089  log_str << ".write('( ')" << endl;
2090  indent(out) <<
2091  "for " << iter << " in " << prefix << ":" << endl;
2092  indent_up();
2093  t_field efield(((t_set*)ttype)->get_elem_type(), iter);
2094  generate_field_log(out, &efield, log_str, "");
2095  indent(out) <<
2096  log_str << ".write(', ')" << endl;
2097  indent_down();
2098  indent(out) <<
2099  log_str << ".write(' )')" << endl;
2100  } else if (ttype->is_list()) {
2101  string iter = tmp("iter");
2102  indent(out) <<
2103  log_str << ".write('[ ')" << endl;
2104  indent(out) <<
2105  "for " << iter << " in " << prefix << ":" << endl;
2106  indent_up();
2107  t_field efield(((t_list*)ttype)->get_elem_type(), iter);
2108  generate_field_log(out, &efield, log_str, "");
2109  indent(out) <<
2110  log_str << ".write(', ')" << endl;
2111  indent_down();
2112  indent(out) <<
2113  log_str << ".write(' ]')" << endl;
2114  }
2115 }
2116 
2117 void t_py_generator::generate_field_log(ofstream& out,
2118  t_field *tfield,
2119  string log_str,
2120  string prefix) {
2121  t_type* type = get_true_type(tfield->get_type());
2122 
2123  if (type->is_struct() || type->is_xception()) {
2124  generate_struct_log(out, prefix + tfield->get_name(), log_str);
2125  } else if (type->is_container()) {
2126  generate_container_log(out, prefix + tfield->get_name(), type, log_str);
2127  } else if (type->is_base_type() || type->is_enum()) {
2128  string name = prefix + tfield->get_name();
2129  if (type->is_base_type()) {
2130  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
2131  switch (tbase) {
2133  break;
2135  case t_base_type::TYPE_STATIC_CONST_STRING:
2136  case t_base_type::TYPE_XML:
2137  indent(out) <<
2138  log_str << ".write(" << name << ")" << endl;
2139  break;
2141  indent(out) <<
2142  "if " << name << ":" << endl;
2143  indent_up();
2144  indent(out) <<
2145  log_str << ".write('True')" << endl;
2146  indent_down();
2147  indent(out) <<
2148  "else:" << endl;
2149  indent_up();
2150  indent(out) <<
2151  log_str << ".write('False')" << endl;
2152  indent_down();
2153  break;
2155  indent(out) <<
2156  log_str << ".write(hex(" << name << "))" << endl;
2157  break;
2158  case t_base_type::TYPE_I16:
2159  indent(out) <<
2160  log_str << ".write(str(" << name << "))" << endl;
2161  break;
2162  case t_base_type::TYPE_I32:
2163  indent(out) <<
2164  log_str << ".write(str(" << name << "))" << endl;
2165  break;
2166  case t_base_type::TYPE_I64:
2167  indent(out) <<
2168  log_str << ".write(str(" << name << "))" << endl;
2169  break;
2170  case t_base_type::TYPE_U16:
2171  indent(out) <<
2172  log_str << ".write(str(" << name << "))" << endl;
2173  break;
2174  case t_base_type::TYPE_U32:
2175  indent(out) <<
2176  log_str << ".write(str(" << name << "))" << endl;
2177  break;
2178  case t_base_type::TYPE_U64:
2179  indent(out) <<
2180  log_str << ".write(str(" << name << "))" << endl;
2181  break;
2183  indent(out) <<
2184  log_str << ".write(str(" << name << "))" << endl;
2185  break;
2186  case t_base_type::TYPE_IPV4:
2187  indent(out) << "import socket, struct" << endl;
2188  indent(out) <<
2189  log_str << ".write(socket.inet_ntoa(struct.pack('!L'," << name << ")))" << endl;
2190  break;
2191  case t_base_type::TYPE_IPADDR:
2192  indent(out) <<
2193  log_str << ".write(str(" << name << "))" << endl;
2194  break;
2195  case t_base_type::TYPE_UUID:
2196  indent(out) <<
2197  log_str << ".write(str(" << name << "))" << endl;
2198  break;
2199  default:
2200  throw "compiler error: unrecognized base type " + t_base_type::t_base_name(tbase);
2201  }
2202  } else if (type->is_enum()) {
2203  indent(out) <<
2204  log_str << ".write(str(" << name << "))" << endl;
2205  }
2206  } else {
2207  printf("DO NOT KNOW HOW TO GENERATE LOG FOR FIELD '%s' TYPE '%s'\n",
2208  tfield->get_name().c_str(),
2209  type->get_name().c_str());
2210  }
2211 }
2212 
2213 void t_py_generator::generate_py_sandesh_logger(ofstream &out,
2214  t_sandesh* tsandesh) {
2215  const vector<t_field*>& fields = tsandesh->get_members();
2216  vector<t_field*>::const_iterator f_iter;
2217  t_base_type *sandesh_type = (t_base_type *)tsandesh->get_type();
2218 
2219  std::string log_str = "log_str";
2220  indent(out) <<
2221  "def log(self, trace=False):" << endl;
2222  indent_up();
2223  indent(out) <<
2224  log_str << " = StringIO()" << endl;
2225  bool init = false;
2226  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2227  if (!init) {
2228  init = true;
2229  indent(out) << "if trace:" << endl;
2230  indent_up();
2231  indent(out) << log_str << ".write(str(self._timestamp))" << endl;
2232  indent(out) << log_str << ".write(' ')" << endl;
2233  indent_down();
2234  // Only systemlog, objectlog, and flowlog have valid level and category
2235  if (sandesh_type->is_sandesh_system() ||
2236  sandesh_type->is_sandesh_object() ||
2237  sandesh_type->is_sandesh_flow()) {
2238  indent(out) <<
2239  "if self._category is not None:" << endl;
2240  indent_up();
2241  indent(out) << log_str << ".write(self._category)" << endl;
2242  indent_down();
2243  indent(out) << log_str << ".write(' [')" << endl;
2244  indent(out) << log_str << ".write(SandeshLevel._VALUES_TO_NAMES["
2245  << "self._level])" << endl;
2246  indent(out) << log_str << ".write(']: ')" << endl;
2247  }
2248  indent(out) << log_str << ".write(self.__class__.__name__ + " <<
2249  "': ')" << endl;
2250  }
2251  indent(out) <<
2252  "if self." << (*f_iter)->get_name() << " is not None:" << endl;
2253  indent_up();
2254  if (sandesh_type->is_sandesh_system() ||
2255  sandesh_type->is_sandesh_trace()) {
2256  generate_field_log(out, *f_iter, log_str, "self.");
2257  indent(out) << log_str << ".write(' ')" << endl;
2258  } else {
2259  indent(out) << log_str <<
2260  ".write('" << (*f_iter)->get_name() << " = ')"<< endl;
2261  generate_field_log(out, *f_iter, log_str, "self.");
2262  indent(out) << log_str << ".write(' ')" << endl;
2263  }
2264  indent_down();
2265  }
2266  indent(out) <<
2267  "return log_str.getvalue()" << endl << endl;
2268  indent_down();
2269 }
2270 
2271 void t_py_generator::generate_py_struct_logger(ofstream &out,
2272  t_struct* tstruct) {
2273  const vector<t_field*>& fields = tstruct->get_members();
2274  vector<t_field*>::const_iterator f_iter;
2275 
2276  std::string log_str = "log_str";
2277  indent(out) <<
2278  "def log(self):" << endl;
2279  indent_up();
2280  indent(out) <<
2281  log_str << " = StringIO()" << endl;
2282 
2283  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2284  indent(out) <<
2285  "if self." << (*f_iter)->get_name() << " is not None:" << endl;
2286  indent_up();
2287  t_type *type = get_true_type((*f_iter)->get_type());
2288  bool write_fname = true;
2289  if (type->is_base_type()) {
2290  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
2291  if (tbase == t_base_type::TYPE_STATIC_CONST_STRING) {
2292  write_fname = false;
2293  }
2294  }
2295  if (write_fname) {
2296  indent(out) <<
2297  log_str << ".write('" << (*f_iter)->get_name() << " = ')"<< endl;
2298  }
2299  generate_field_log(out, *f_iter, log_str, "self.");
2300  indent(out) <<
2301  log_str << ".write(' ')" << endl;
2302  indent_down();
2303  }
2304  indent(out) <<
2305  "return log_str.getvalue()" << endl << endl;
2306  indent_down();
2307 }
2308 
2309 void t_py_generator::generate_py_sizeof(std::ofstream& out,
2310  const vector<t_field*>& fields) {
2311  indent(out) << "def __sizeof__(self):" << endl;
2312  indent_up();
2313  indent(out) << "size = 0" << endl;
2314  vector<t_field*>::const_iterator f_iter;
2315  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2316  std::string fname((*f_iter)->get_name());
2317  indent(out) << "if self." << fname << " is not None:" << endl;
2318  indent_up();
2319  indent(out) << "size += getsizeof(self." << fname << ")" << endl;
2320  t_type* type = get_true_type((*f_iter)->get_type());
2321  if (type->is_container()) {
2322  if (type->is_map()) {
2323  indent(out) <<
2324  "size += sum(map(getsizeof, chain.from_iterable(iter(self." <<
2325  fname << ".items()))))" << endl;
2326 
2327  } else {
2328  indent(out) <<
2329  "size += sum(map(getsizeof, self." << fname << "))" << endl;
2330  }
2331  }
2332  indent_down();
2333  }
2334  indent(out) << "return size" << endl << endl;
2335  indent_down();
2336 }
2337 
2338 void t_py_generator::generate_py_struct_sizeof(std::ofstream& out,
2339  t_struct* tstruct) {
2340  const vector<t_field*>& fields = tstruct->get_members();
2341  generate_py_sizeof(out, fields);
2342 }
2343 
2344 void t_py_generator::generate_py_sandesh_sizeof(std::ofstream& out,
2345  t_sandesh* tsandesh) {
2346  const vector<t_field*>& fields = tsandesh->get_members();
2347  generate_py_sizeof(out, fields);
2348 }
2349 
2350 void t_py_generator::generate_py_sandesh_hint(ofstream& out,
2351  t_sandesh* tsandesh) {
2352  bool has_key_annotation = tsandesh->has_key_annotation();
2353  string shints = "0";
2354 
2355  if (has_key_annotation) {
2356  shints += " | SANDESH_KEY_HINT";
2357  }
2358 
2359  indent(out) << "self._hints = " << shints << endl;
2360 }
2361 
2362 void t_py_generator::generate_py_sandesh_trace(std::ofstream& out,
2363  t_sandesh* tsandesh) {
2364 }
2365 
2366 void t_py_generator::generate_py_sandesh_async(std::ofstream& out,
2367  t_sandesh* tsandesh) {
2368 }
2369 
2370 void t_py_generator::generate_py_sandesh_request(std::ofstream& out,
2371  t_sandesh* tsandesh) {
2372  // Generate http request handler
2373  generate_py_sandesh_http_request_handler(out, tsandesh);
2374  // Update sandesh request list
2375  sandesh_req_list_.push_back(tsandesh->get_name());
2376  // Update _HTTP_REQUEST_LIST in http_request.py
2377  generate_py_sandesh_http_request_list(f_http_request_, tsandesh);
2378  // Generate the Sandesh Request Skeleton
2379  generate_py_sandesh_skeleton_request(f_request_impl_, tsandesh);
2380 }
2381 
2382 void t_py_generator::generate_py_sandesh_response(std::ofstream& out,
2383  t_sandesh* tsandesh) {
2384 }
2385 
2386 void t_py_generator::generate_py_sandesh_uve(std::ofstream& out,
2387  t_sandesh* tsandesh,
2388  bool update) {
2389  const vector<t_field*>& fields = tsandesh->get_members();
2390  vector<t_field*>::const_iterator f_iter = fields.begin();
2391  assert((*f_iter)->get_name() == "data");
2392  t_type* t = get_true_type((*f_iter)->get_type());
2393  t_struct* ts = (t_struct*)t;
2394  if (update) {
2395  out << indent() << "def update_uve(self, tdata):" << endl;
2396  indent_up();
2397  assert(t->is_struct());
2398  const vector<t_field*>& sfields = ts->get_members();
2399  vector<t_field*>::const_iterator s_iter;
2400 
2401  for (s_iter = sfields.begin(); s_iter != sfields.end(); ++s_iter) {
2402  out << indent() << "if self.data." << (*s_iter)->get_name() << " is not None:" << endl;
2403  indent_up();
2404  out << indent() << "tdata." << (*s_iter)->get_name() << " = self.data." <<
2405  (*s_iter)->get_name() << endl;
2406  indent_down();
2407  }
2408  out << indent() << "return tdata" << endl;
2409  f_iter++;
2410  assert(f_iter == fields.end());
2411  indent_down();
2412  out << endl;
2413  }
2414 
2415  const t_base_type *sandesh_type = (t_base_type *)tsandesh->get_type();
2416  if (sandesh_type->is_sandesh_uve() || sandesh_type->is_sandesh_dynamic_uve()) {
2417  // Update sandesh UVE list
2418  sandesh_uve_list_.push_back(boost::make_tuple(tsandesh->get_name(),
2419  ts->get_name()));
2420  } else if (sandesh_type->is_sandesh_alarm()) {
2421  // Update sandesh Alarm list
2422  sandesh_alarm_list_.push_back(boost::make_tuple(tsandesh->get_name(),
2423  ts->get_name()));
2424  }
2425 }
2426 
2427 void t_py_generator::generate_py_sandesh_uve_list(ofstream& out) {
2428  out << endl << endl;
2429  out << "_SANDESH_UVE_LIST = [" << endl;
2430  std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2431  for (it = sandesh_uve_list_.begin(); it != sandesh_uve_list_.end(); ++it) {
2432  indent(out) << "(" << it->get<0>() << ", " << it->get<1>() << ")," << endl;
2433  }
2434  out << "]" << endl;
2435 }
2436 
2437 void t_py_generator::generate_py_sandesh_alarm_list(ofstream& out) {
2438  out << endl << endl;
2439  out << "_SANDESH_ALARM_LIST = [" << endl;
2440  std::vector<boost::tuple<std::string, std::string> >::const_iterator it;
2441  for (it = sandesh_alarm_list_.begin(); it != sandesh_alarm_list_.end();
2442  ++it) {
2443  indent(out) << "(" << it->get<0>() << ", " << it->get<1>() << ")," << endl;
2444  }
2445  out << "]" << endl;
2446 }
2447 #endif
2448 
2455  string f_service_name = package_dir_+"/"+service_name_+".py";
2456  f_service_.open(f_service_name.c_str());
2457 
2458  f_service_ <<
2459  py_autogen_comment() << endl <<
2460  py_imports() << endl;
2461 
2462  if (tservice->get_extends() != NULL) {
2463  f_service_ <<
2464  "import " << get_real_py_module(tservice->get_extends()->get_program(), gen_twisted_) <<
2465  "." << tservice->get_extends()->get_name() << endl;
2466  }
2467 
2468  f_service_ <<
2469  "from .ttypes import *" << endl <<
2470  "from thrift.Thrift import TProcessor" << endl <<
2471  render_fastbinary_includes() << endl;
2472 
2473  if (gen_twisted_) {
2474  f_service_ <<
2475  "from zope.interface import Interface, implements" << endl <<
2476  "from twisted.internet import defer" << endl <<
2477  "from thrift.transport import TTwisted" << endl;
2478  }
2479 
2480  f_service_ << endl;
2481 
2482  // Generate the three main parts of the service (well, two for now in PHP)
2483  generate_service_interface(tservice);
2484  generate_service_client(tservice);
2485  generate_service_server(tservice);
2486  generate_service_helpers(tservice);
2487  generate_service_remote(tservice);
2488 
2489  // Close service file
2490  f_service_.close();
2491 }
2492 
2499  vector<t_function*> functions = tservice->get_functions();
2500  vector<t_function*>::iterator f_iter;
2501 
2502  f_service_ <<
2503  "# HELPER FUNCTIONS AND STRUCTURES" << endl;
2504 
2505  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2506  t_struct* ts = (*f_iter)->get_arglist();
2509  }
2510 }
2511 
2518  if (!tfunction->is_oneway()) {
2519  t_struct result(program_, tfunction->get_name() + "_result");
2520  t_field success(tfunction->get_returntype(), "success", 0);
2521  if (!tfunction->get_returntype()->is_void()) {
2522  result.append(&success);
2523  }
2524 
2525  t_struct* xs = tfunction->get_xceptions();
2526  const vector<t_field*>& fields = xs->get_members();
2527  vector<t_field*>::const_iterator f_iter;
2528  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
2529  result.append(*f_iter);
2530  }
2531  generate_py_struct_definition(f_service_, &result, false, true);
2532  }
2533 }
2534 
2541  string extends = "";
2542  string extends_if = "";
2543  if (tservice->get_extends() != NULL) {
2544  extends = type_name(tservice->get_extends());
2545  extends_if = "(" + extends + ".Iface)";
2546  } else {
2547  if (gen_twisted_) {
2548  extends_if = "(Interface)";
2549  } else if (gen_newstyle_ || gen_dynamic_) {
2550  extends_if = "(object)";
2551  }
2552  }
2553 
2554  f_service_ <<
2555  "class Iface" << extends_if << ":" << endl;
2556  indent_up();
2558  vector<t_function*> functions = tservice->get_functions();
2559  if (functions.empty()) {
2560  f_service_ <<
2561  indent() << "pass" << endl;
2562  } else {
2563  vector<t_function*>::iterator f_iter;
2564  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2565  f_service_ <<
2566  indent() << "def " << function_signature_if(*f_iter) << ":" << endl;
2567  indent_up();
2569  f_service_ <<
2570  indent() << "pass" << endl << endl;
2571  indent_down();
2572  }
2573  }
2574 
2575  indent_down();
2576  f_service_ <<
2577  endl;
2578 }
2579 
2586  string extends = "";
2587  string extends_client = "";
2588  if (tservice->get_extends() != NULL) {
2589  extends = type_name(tservice->get_extends());
2590  if (gen_twisted_) {
2591  extends_client = "(" + extends + ".Client)";
2592  } else {
2593  extends_client = extends + ".Client, ";
2594  }
2595  } else {
2596  if (gen_twisted_ && (gen_newstyle_ || gen_dynamic_)) {
2597  extends_client = "(object)";
2598  }
2599  }
2600 
2601  if (gen_twisted_) {
2602  f_service_ <<
2603  "class Client" << extends_client << ":" << endl <<
2604  " implements(Iface)" << endl << endl;
2605  } else {
2606  f_service_ <<
2607  "class Client(" << extends_client << "Iface):" << endl;
2608  }
2609  indent_up();
2611 
2612  // Constructor function
2613  if (gen_twisted_) {
2614  f_service_ <<
2615  indent() << "def __init__(self, transport, oprot_factory):" << endl;
2616  } else {
2617  f_service_ <<
2618  indent() << "def __init__(self, iprot, oprot=None):" << endl;
2619  }
2620  if (extends.empty()) {
2621  if (gen_twisted_) {
2622  f_service_ <<
2623  indent() << " self._transport = transport" << endl <<
2624  indent() << " self._oprot_factory = oprot_factory" << endl <<
2625  indent() << " self._seqid = 0" << endl <<
2626  indent() << " self._reqs = {}" << endl <<
2627  endl;
2628  } else {
2629  f_service_ <<
2630  indent() << " self._iprot = self._oprot = iprot" << endl <<
2631  indent() << " if oprot is not None:" << endl <<
2632  indent() << " self._oprot = oprot" << endl <<
2633  indent() << " self._seqid = 0" << endl <<
2634  endl;
2635  }
2636  } else {
2637  if (gen_twisted_) {
2638  f_service_ <<
2639  indent() << " " << extends << ".Client.__init__(self, transport, oprot_factory)" << endl <<
2640  endl;
2641  } else {
2642  f_service_ <<
2643  indent() << " " << extends << ".Client.__init__(self, iprot, oprot)" << endl <<
2644  endl;
2645  }
2646  }
2647 
2648  // Generate client method implementations
2649  vector<t_function*> functions = tservice->get_functions();
2650  vector<t_function*>::const_iterator f_iter;
2651  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2652  t_struct* arg_struct = (*f_iter)->get_arglist();
2653  const vector<t_field*>& fields = arg_struct->get_members();
2654  vector<t_field*>::const_iterator fld_iter;
2655  string funname = (*f_iter)->get_name();
2656 
2657  // Open function
2658  indent(f_service_) <<
2659  "def " << function_signature(*f_iter) << ":" << endl;
2660  indent_up();
2662  if (gen_twisted_) {
2663  indent(f_service_) << "self._seqid += 1" << endl;
2664  if (!(*f_iter)->is_oneway()) {
2665  indent(f_service_) <<
2666  "d = self._reqs[self._seqid] = defer.Deferred()" << endl;
2667  }
2668  }
2669 
2670  indent(f_service_) <<
2671  "self.send_" << funname << "(";
2672 
2673  bool first = true;
2674  for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2675  if (first) {
2676  first = false;
2677  } else {
2678  f_service_ << ", ";
2679  }
2680  f_service_ << (*fld_iter)->get_name();
2681  }
2682  f_service_ << ")" << endl;
2683 
2684  if (!(*f_iter)->is_oneway()) {
2685  f_service_ << indent();
2686  if (gen_twisted_) {
2687  f_service_ << "return d" << endl;
2688  } else {
2689  if (!(*f_iter)->get_returntype()->is_void()) {
2690  f_service_ << "return ";
2691  }
2692  f_service_ <<
2693  "self.recv_" << funname << "()" << endl;
2694  }
2695  } else {
2696  if (gen_twisted_) {
2697  f_service_ <<
2698  indent() << "return defer.succeed(None)" << endl;
2699  }
2700  }
2701  indent_down();
2702  f_service_ << endl;
2703 
2704  indent(f_service_) <<
2705  "def send_" << function_signature(*f_iter) << ":" << endl;
2706 
2707  indent_up();
2708 
2709  std::string argsname = (*f_iter)->get_name() + "_args";
2710 
2711  // Serialize the request header
2712  if (gen_twisted_) {
2713  f_service_ <<
2714  indent() << "oprot = self._oprot_factory.getProtocol(self._transport)" << endl <<
2715  indent() <<
2716  "oprot.writeMessageBegin('" << (*f_iter)->get_name() << "', TMessageType.CALL, self._seqid)"
2717  << endl;
2718  } else {
2719  f_service_ <<
2720  indent() << "self._oprot.writeMessageBegin('" << (*f_iter)->get_name() << "', TMessageType.CALL, self._seqid)" << endl;
2721  }
2722 
2723  f_service_ <<
2724  indent() << "args = " << argsname << "()" << endl;
2725 
2726  for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
2727  f_service_ <<
2728  indent() << "args." << (*fld_iter)->get_name() << " = " << (*fld_iter)->get_name() << endl;
2729  }
2730 
2731  // Write to the stream
2732  if (gen_twisted_) {
2733  f_service_ <<
2734  indent() << "args.write(oprot)" << endl <<
2735  indent() << "oprot.writeMessageEnd()" << endl <<
2736  indent() << "oprot.trans.flush()" << endl;
2737  } else {
2738  f_service_ <<
2739  indent() << "args.write(self._oprot)" << endl <<
2740  indent() << "self._oprot.writeMessageEnd()" << endl <<
2741  indent() << "self._oprot.trans.flush()" << endl;
2742  }
2743 
2744  indent_down();
2745 
2746  if (!(*f_iter)->is_oneway()) {
2747  std::string resultname = (*f_iter)->get_name() + "_result";
2748  // Open function
2749  f_service_ <<
2750  endl;
2751  if (gen_twisted_) {
2752  f_service_ <<
2753  indent() << "def recv_" << (*f_iter)->get_name() <<
2754  "(self, iprot, mtype, rseqid):" << endl;
2755  } else {
2756  t_struct noargs(program_);
2757  t_function recv_function((*f_iter)->get_returntype(),
2758  string("recv_") + (*f_iter)->get_name(),
2759  &noargs);
2760  f_service_ <<
2761  indent() << "def " << function_signature(&recv_function) << ":" << endl;
2762  }
2763  indent_up();
2764 
2765  // TODO(mcslee): Validate message reply here, seq ids etc.
2766 
2767  if (gen_twisted_) {
2768  f_service_ <<
2769  indent() << "d = self._reqs.pop(rseqid)" << endl;
2770  } else {
2771  f_service_ <<
2772  indent() << "(fname, mtype, rseqid) = self._iprot.readMessageBegin()" << endl;
2773  }
2774 
2775  f_service_ <<
2776  indent() << "if mtype == TMessageType.EXCEPTION:" << endl <<
2777  indent() << " x = TApplicationException()" << endl;
2778 
2779  if (gen_twisted_) {
2780  f_service_ <<
2781  indent() << " x.read(iprot)" << endl <<
2782  indent() << " iprot.readMessageEnd()" << endl <<
2783  indent() << " return d.errback(x)" << endl <<
2784  indent() << "result = " << resultname << "()" << endl <<
2785  indent() << "result.read(iprot)" << endl <<
2786  indent() << "iprot.readMessageEnd()" << endl;
2787  } else {
2788  f_service_ <<
2789  indent() << " x.read(self._iprot)" << endl <<
2790  indent() << " self._iprot.readMessageEnd()" << endl <<
2791  indent() << " raise x" << endl <<
2792  indent() << "result = " << resultname << "()" << endl <<
2793  indent() << "result.read(self._iprot)" << endl <<
2794  indent() << "self._iprot.readMessageEnd()" << endl;
2795  }
2796 
2797  // Careful, only return _result if not a void function
2798  if (!(*f_iter)->get_returntype()->is_void()) {
2799  f_service_ <<
2800  indent() << "if result.success is not None:" << endl;
2801  if (gen_twisted_) {
2802  f_service_ <<
2803  indent() << " return d.callback(result.success)" << endl;
2804  } else {
2805  f_service_ <<
2806  indent() << " return result.success" << endl;
2807  }
2808  }
2809 
2810  t_struct* xs = (*f_iter)->get_xceptions();
2811  const std::vector<t_field*>& xceptions = xs->get_members();
2812  vector<t_field*>::const_iterator x_iter;
2813  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
2814  f_service_ <<
2815  indent() << "if result." << (*x_iter)->get_name() << " is not None:" << endl;
2816  if (gen_twisted_) {
2817  f_service_ <<
2818  indent() << " return d.errback(result." << (*x_iter)->get_name() << ")" << endl;
2819 
2820  } else {
2821  f_service_ <<
2822  indent() << " raise result." << (*x_iter)->get_name() << "" << endl;
2823  }
2824  }
2825 
2826  // Careful, only return _result if not a void function
2827  if ((*f_iter)->get_returntype()->is_void()) {
2828  if (gen_twisted_) {
2829  indent(f_service_) <<
2830  "return d.callback(None)" << endl;
2831  } else {
2832  indent(f_service_) <<
2833  "return" << endl;
2834  }
2835  } else {
2836  if (gen_twisted_) {
2837  f_service_ <<
2838  indent() << "return d.errback(TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() << " failed: unknown result\"))" << endl;
2839  } else {
2840  f_service_ <<
2841  indent() << "raise TApplicationException(TApplicationException.MISSING_RESULT, \"" << (*f_iter)->get_name() << " failed: unknown result\");" << endl;
2842  }
2843  }
2844 
2845  // Close function
2846  indent_down();
2847  f_service_ << endl;
2848  }
2849  }
2850 
2851  indent_down();
2852  f_service_ <<
2853  endl;
2854 }
2855 
2862  vector<t_function*> functions = tservice->get_functions();
2863  vector<t_function*>::iterator f_iter;
2864 
2865  string f_remote_name = package_dir_+"/"+service_name_+"-remote";
2866  ofstream f_remote;
2867  f_remote.open(f_remote_name.c_str());
2868 
2869  f_remote <<
2870  "#!/usr/bin/env python" << endl <<
2871  py_autogen_comment() << endl <<
2872  "import sys" << endl <<
2873  "import pprint" << endl <<
2874  "from urlparse import urlparse" << endl <<
2875  "from thrift.transport import TTransport" << endl <<
2876  "from thrift.transport import TSocket" << endl <<
2877  "from thrift.transport import THttpClient" << endl <<
2878  "from thrift.protocol import TBinaryProtocol" << endl <<
2879  endl;
2880 
2881  f_remote <<
2882  "import " << service_name_ << endl <<
2883  "from .ttypes import *" << endl <<
2884  endl;
2885 
2886  f_remote <<
2887  "if len(sys.argv) <= 1 or sys.argv[1] == '--help':" << endl <<
2888  " print ''" << endl <<
2889  " print 'Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] function [arg1 [arg2...]]'" << endl <<
2890  " print ''" << endl <<
2891  " print 'Functions:'" << endl;
2892  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2893  f_remote <<
2894  " print ' " << (*f_iter)->get_returntype()->get_name() << " " << (*f_iter)->get_name() << "(";
2895  t_struct* arg_struct = (*f_iter)->get_arglist();
2896  const std::vector<t_field*>& args = arg_struct->get_members();
2897  vector<t_field*>::const_iterator a_iter;
2898  int num_args = args.size();
2899  bool first = true;
2900  for (int i = 0; i < num_args; ++i) {
2901  if (first) {
2902  first = false;
2903  } else {
2904  f_remote << ", ";
2905  }
2906  f_remote <<
2907  args[i]->get_type()->get_name() << " " << args[i]->get_name();
2908  }
2909  f_remote << ")'" << endl;
2910  }
2911  f_remote <<
2912  " print ''" << endl <<
2913  " sys.exit(0)" << endl <<
2914  endl;
2915 
2916  f_remote <<
2917  "pp = pprint.PrettyPrinter(indent = 2)" << endl <<
2918  "host = 'localhost'" << endl <<
2919  "port = 9090" << endl <<
2920  "uri = ''" << endl <<
2921  "framed = False" << endl <<
2922  "http = False" << endl <<
2923  "argi = 1" << endl <<
2924  endl <<
2925  "if sys.argv[argi] == '-h':" << endl <<
2926  " parts = sys.argv[argi+1].split(':')" << endl <<
2927  " host = parts[0]" << endl <<
2928  " if len(parts) > 1:" << endl <<
2929  " port = int(parts[1])" << endl <<
2930  " argi += 2" << endl <<
2931  endl <<
2932  "if sys.argv[argi] == '-u':" << endl <<
2933  " url = urlparse(sys.argv[argi+1])" << endl <<
2934  " parts = url[1].split(':')" << endl <<
2935  " host = parts[0]" << endl <<
2936  " if len(parts) > 1:" << endl <<
2937  " port = int(parts[1])" << endl <<
2938  " else:" << endl <<
2939  " port = 80" << endl <<
2940  " uri = url[2]" << endl <<
2941  " if url[4]:" << endl <<
2942  " uri += '?%s' % url[4]" << endl <<
2943  " http = True" << endl <<
2944  " argi += 2" << endl <<
2945  endl <<
2946  "if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed':" << endl <<
2947  " framed = True" << endl <<
2948  " argi += 1" << endl <<
2949  endl <<
2950  "cmd = sys.argv[argi]" << endl <<
2951  "args = sys.argv[argi+1:]" << endl <<
2952  endl <<
2953  "if http:" << endl <<
2954  " transport = THttpClient.THttpClient(host, port, uri)" << endl <<
2955  "else:" << endl <<
2956  " socket = TSocket.TSocket(host, port)" << endl <<
2957  " if framed:" << endl <<
2958  " transport = TTransport.TFramedTransport(socket)" << endl <<
2959  " else:" << endl <<
2960  " transport = TTransport.TBufferedTransport(socket)" << endl <<
2961  "protocol = TBinaryProtocol.TBinaryProtocol(transport)" << endl <<
2962  "client = " << service_name_ << ".Client(protocol)" << endl <<
2963  "transport.open()" << endl <<
2964  endl;
2965 
2966  // Generate the dispatch methods
2967  bool first = true;
2968 
2969  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
2970  if (first) {
2971  first = false;
2972  } else {
2973  f_remote << "el";
2974  }
2975 
2976  t_struct* arg_struct = (*f_iter)->get_arglist();
2977  const std::vector<t_field*>& args = arg_struct->get_members();
2978  vector<t_field*>::const_iterator a_iter;
2979  int num_args = args.size();
2980 
2981  f_remote <<
2982  "if cmd == '" << (*f_iter)->get_name() << "':" << endl <<
2983  " if len(args) != " << num_args << ":" << endl <<
2984  " print '" << (*f_iter)->get_name() << " requires " << num_args << " args'" << endl <<
2985  " sys.exit(1)" << endl <<
2986  " pp.pprint(client." << (*f_iter)->get_name() << "(";
2987  for (int i = 0; i < num_args; ++i) {
2988  if (args[i]->get_type()->is_string()) {
2989  f_remote << "args[" << i << "],";
2990  } else {
2991  f_remote << "eval(args[" << i << "]),";
2992  }
2993  }
2994  f_remote << "))" << endl;
2995 
2996  f_remote << endl;
2997  }
2998  f_remote << "else:" << endl;
2999  f_remote << " print 'Unrecognized method %s' % cmd" << endl;
3000  f_remote << " sys.exit(1)" << endl;
3001  f_remote << endl;
3002 
3003  f_remote << "transport.close()" << endl;
3004 
3005  // Close service file
3006  f_remote.close();
3007 
3008 #ifndef _MSC_VER
3009 
3010  // Make file executable, love that bitwise OR action
3011  chmod(f_remote_name.c_str(),
3012  S_IRUSR
3013  | S_IWUSR
3014  | S_IXUSR
3015 #ifndef MINGW
3016  | S_IRGRP
3017  | S_IXGRP
3018  | S_IROTH
3019  | S_IXOTH
3020 #endif
3021  );
3022 
3023 #endif // _MSC_VER
3024 }
3025 
3032  // Generate the dispatch methods
3033  vector<t_function*> functions = tservice->get_functions();
3034  vector<t_function*>::iterator f_iter;
3035 
3036  string extends = "";
3037  string extends_processor = "";
3038  if (tservice->get_extends() != NULL) {
3039  extends = type_name(tservice->get_extends());
3040  extends_processor = extends + ".Processor, ";
3041  }
3042 
3043  // Generate the header portion
3044  if (gen_twisted_) {
3045  f_service_ <<
3046  "class Processor(" << extends_processor << "TProcessor):" << endl <<
3047  " implements(Iface)" << endl << endl;
3048  } else {
3049  f_service_ <<
3050  "class Processor(" << extends_processor << "Iface, TProcessor):" << endl;
3051  }
3052 
3053  indent_up();
3054 
3055  indent(f_service_) <<
3056  "def __init__(self, handler):" << endl;
3057  indent_up();
3058  if (extends.empty()) {
3059  if (gen_twisted_) {
3060  f_service_ <<
3061  indent() << "self._handler = Iface(handler)" << endl;
3062  } else {
3063  f_service_ <<
3064  indent() << "self._handler = handler" << endl;
3065  }
3066 
3067  f_service_ <<
3068  indent() << "self._processMap = {}" << endl;
3069  } else {
3070  if (gen_twisted_) {
3071  f_service_ <<
3072  indent() << extends << ".Processor.__init__(self, Iface(handler))" << endl;
3073  } else {
3074  f_service_ <<
3075  indent() << extends << ".Processor.__init__(self, handler)" << endl;
3076  }
3077  }
3078  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3079  f_service_ <<
3080  indent() << "self._processMap[\"" << (*f_iter)->get_name() << "\"] = Processor.process_" << (*f_iter)->get_name() << endl;
3081  }
3082  indent_down();
3083  f_service_ << endl;
3084 
3085  // Generate the server implementation
3086  indent(f_service_) <<
3087  "def process(self, iprot, oprot):" << endl;
3088  indent_up();
3089 
3090  f_service_ <<
3091  indent() << "(name, type, seqid) = iprot.readMessageBegin()" << endl;
3092 
3093  // TODO(mcslee): validate message
3094 
3095  // HOT: dictionary function lookup
3096  f_service_ <<
3097  indent() << "if name not in self._processMap:" << endl <<
3098  indent() << " iprot.skip(TType.STRUCT)" << endl <<
3099  indent() << " iprot.readMessageEnd()" << endl <<
3100  indent() << " x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))" << endl <<
3101  indent() << " oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)" << endl <<
3102  indent() << " x.write(oprot)" << endl <<
3103  indent() << " oprot.writeMessageEnd()" << endl <<
3104  indent() << " oprot.trans.flush()" << endl;
3105 
3106  if (gen_twisted_) {
3107  f_service_ <<
3108  indent() << " return defer.succeed(None)" << endl;
3109  } else {
3110  f_service_ <<
3111  indent() << " return" << endl;
3112  }
3113 
3114  f_service_ <<
3115  indent() << "else:" << endl;
3116 
3117  if (gen_twisted_) {
3118  f_service_ <<
3119  indent() << " return self._processMap[name](self, seqid, iprot, oprot)" << endl;
3120  } else {
3121  f_service_ <<
3122  indent() << " self._processMap[name](self, seqid, iprot, oprot)" << endl;
3123 
3124  // Read end of args field, the T_STOP, and the struct close
3125  f_service_ <<
3126  indent() << "return True" << endl;
3127  }
3128 
3129  indent_down();
3130  f_service_ << endl;
3131 
3132  // Generate the process subfunctions
3133  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
3134  generate_process_function(tservice, *f_iter);
3135  }
3136 
3137  indent_down();
3138  f_service_ << endl;
3139 }
3140 
3147  t_function* tfunction) {
3148  (void) tservice;
3149  // Open function
3150  indent(f_service_) <<
3151  "def process_" << tfunction->get_name() <<
3152  "(self, seqid, iprot, oprot):" << endl;
3153  indent_up();
3154 
3155  string argsname = tfunction->get_name() + "_args";
3156  string resultname = tfunction->get_name() + "_result";
3157 
3158  f_service_ <<
3159  indent() << "args = " << argsname << "()" << endl <<
3160  indent() << "args.read(iprot)" << endl <<
3161  indent() << "iprot.readMessageEnd()" << endl;
3162 
3163  t_struct* xs = tfunction->get_xceptions();
3164  const std::vector<t_field*>& xceptions = xs->get_members();
3165  vector<t_field*>::const_iterator x_iter;
3166 
3167  // Declare result for non oneway function
3168  if (!tfunction->is_oneway()) {
3169  f_service_ <<
3170  indent() << "result = " << resultname << "()" << endl;
3171  }
3172 
3173  if (gen_twisted_) {
3174  // Generate the function call
3175  t_struct* arg_struct = tfunction->get_arglist();
3176  const std::vector<t_field*>& fields = arg_struct->get_members();
3177  vector<t_field*>::const_iterator f_iter;
3178 
3179  f_service_ <<
3180  indent() << "d = defer.maybeDeferred(self._handler." <<
3181  tfunction->get_name() << ", ";
3182  bool first = true;
3183  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3184  if (first) {
3185  first = false;
3186  } else {
3187  f_service_ << ", ";
3188  }
3189  f_service_ << "args." << (*f_iter)->get_name();
3190  }
3191  f_service_ << ")" << endl;
3192 
3193  // Shortcut out here for oneway functions
3194  if (tfunction->is_oneway()) {
3195  f_service_ <<
3196  indent() << "return d" << endl;
3197  indent_down();
3198  f_service_ << endl;
3199  return;
3200  }
3201 
3202  f_service_ <<
3203  indent() <<
3204  "d.addCallback(self.write_results_success_" <<
3205  tfunction->get_name() << ", result, seqid, oprot)" << endl;
3206 
3207  if (xceptions.size() > 0) {
3208  f_service_ <<
3209  indent() <<
3210  "d.addErrback(self.write_results_exception_" <<
3211  tfunction->get_name() << ", result, seqid, oprot)" << endl;
3212  }
3213 
3214  f_service_ <<
3215  indent() << "return d" << endl;
3216 
3217  indent_down();
3218  f_service_ << endl;
3219 
3220  indent(f_service_) <<
3221  "def write_results_success_" << tfunction->get_name() <<
3222  "(self, success, result, seqid, oprot):" << endl;
3223  indent_up();
3224  f_service_ <<
3225  indent() << "result.success = success" << endl <<
3226  indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() <<
3227  "\", TMessageType.REPLY, seqid)" << endl <<
3228  indent() << "result.write(oprot)" << endl <<
3229  indent() << "oprot.writeMessageEnd()" << endl <<
3230  indent() << "oprot.trans.flush()" << endl;
3231  indent_down();
3232  f_service_ << endl;
3233 
3234  // Try block for a function with exceptions
3235  if (!tfunction->is_oneway() && xceptions.size() > 0) {
3236  indent(f_service_) <<
3237  "def write_results_exception_" << tfunction->get_name() <<
3238  "(self, error, result, seqid, oprot):" << endl;
3239  indent_up();
3240  f_service_ <<
3241  indent() << "try:" << endl;
3242 
3243  // Kinda absurd
3244  f_service_ <<
3245  indent() << " error.raiseException()" << endl;
3246  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3247  f_service_ <<
3248  indent() << "except " << type_name((*x_iter)->get_type()) << ", " << (*x_iter)->get_name() << ":" << endl;
3249  if (!tfunction->is_oneway()) {
3250  indent_up();
3251  f_service_ <<
3252  indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name() << endl;
3253  indent_down();
3254  } else {
3255  f_service_ <<
3256  indent() << "pass" << endl;
3257  }
3258  }
3259  f_service_ <<
3260  indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() <<
3261  "\", TMessageType.REPLY, seqid)" << endl <<
3262  indent() << "result.write(oprot)" << endl <<
3263  indent() << "oprot.writeMessageEnd()" << endl <<
3264  indent() << "oprot.trans.flush()" << endl;
3265  indent_down();
3266  f_service_ << endl;
3267  }
3268  } else {
3269 
3270  // Try block for a function with exceptions
3271  if (xceptions.size() > 0) {
3272  f_service_ <<
3273  indent() << "try:" << endl;
3274  indent_up();
3275  }
3276 
3277  // Generate the function call
3278  t_struct* arg_struct = tfunction->get_arglist();
3279  const std::vector<t_field*>& fields = arg_struct->get_members();
3280  vector<t_field*>::const_iterator f_iter;
3281 
3282  f_service_ << indent();
3283  if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
3284  f_service_ << "result.success = ";
3285  }
3286  f_service_ <<
3287  "self._handler." << tfunction->get_name() << "(";
3288  bool first = true;
3289  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
3290  if (first) {
3291  first = false;
3292  } else {
3293  f_service_ << ", ";
3294  }
3295  f_service_ << "args." << (*f_iter)->get_name();
3296  }
3297  f_service_ << ")" << endl;
3298 
3299  if (!tfunction->is_oneway() && xceptions.size() > 0) {
3300  indent_down();
3301  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
3302  f_service_ <<
3303  indent() << "except " << type_name((*x_iter)->get_type()) << ", " << (*x_iter)->get_name() << ":" << endl;
3304  if (!tfunction->is_oneway()) {
3305  indent_up();
3306  f_service_ <<
3307  indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name() << endl;
3308  indent_down();
3309  } else {
3310  f_service_ <<
3311  indent() << "pass" << endl;
3312  }
3313  }
3314  }
3315 
3316  // Shortcut out here for oneway functions
3317  if (tfunction->is_oneway()) {
3318  f_service_ <<
3319  indent() << "return" << endl;
3320  indent_down();
3321  f_service_ << endl;
3322  return;
3323  }
3324 
3325  f_service_ <<
3326  indent() << "oprot.writeMessageBegin(\"" << tfunction->get_name() << "\", TMessageType.REPLY, seqid)" << endl <<
3327  indent() << "result.write(oprot)" << endl <<
3328  indent() << "oprot.writeMessageEnd()" << endl <<
3329  indent() << "oprot.trans.flush()" << endl;
3330 
3331  // Close function
3332  indent_down();
3333  f_service_ << endl;
3334  }
3335 }
3336 
3341  t_field* tfield,
3342  string prefix,
3343  bool inclass) {
3344  (void) inclass;
3345  t_type* type = get_true_type(tfield->get_type());
3346 
3347  if (type->is_void()) {
3348  throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " +
3349  prefix + tfield->get_name();
3350  }
3351 
3352  string name = prefix + tfield->get_name();
3353 
3354  if (type->is_struct() || type->is_xception()) {
3356  (t_struct*)type,
3357  name);
3358  } else if (type->is_container()) {
3360  } else if (type->is_base_type() || type->is_enum()) {
3361  indent(out) <<
3362 #ifdef SANDESH
3363  "(length, " << name << ") = iprot.";
3364 #else
3365  name << " = iprot.";
3366 #endif
3367  if (type->is_base_type()) {
3368  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
3369  switch (tbase) {
3371  throw "compiler error: cannot serialize void field in a struct: " +
3372  name;
3373  break;
3375 #ifdef SANDESH
3376  case t_base_type::TYPE_STATIC_CONST_STRING:
3377 #endif
3378  if (((t_base_type*)type)->is_binary() || !gen_utf8strings_) {
3379  out << "readString();";
3380  } else {
3381  out << "readString().decode('utf-8')";
3382  }
3383  break;
3384 #ifdef SANDESH
3385  case t_base_type::TYPE_XML:
3386  out << "readXML();";
3387  break;
3388  case t_base_type::TYPE_UUID:
3389  out << "readUUID();";
3390  break;
3391 #endif
3393  out << "readBool();";
3394  break;
3396  out << "readByte();";
3397  break;
3398  case t_base_type::TYPE_I16:
3399  out << "readI16();";
3400  break;
3401  case t_base_type::TYPE_I32:
3402  out << "readI32();";
3403  break;
3404  case t_base_type::TYPE_I64:
3405  out << "readI64();";
3406  break;
3407 #ifdef SANDESH
3408  case t_base_type::TYPE_U16:
3409  out << "readU16();";
3410  break;
3411  case t_base_type::TYPE_U32:
3412  out << "readU32();";
3413  break;
3414  case t_base_type::TYPE_U64:
3415  out << "readU64();";
3416  break;
3417  case t_base_type::TYPE_IPV4:
3418  out << "readIPV4();";
3419  break;
3420  case t_base_type::TYPE_IPADDR:
3421  out << "readIPADDR()";
3422  break;
3423 #endif
3425  out << "readDouble();";
3426  break;
3427  default:
3428  throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
3429  }
3430  } else if (type->is_enum()) {
3431  out << "readI32();";
3432  }
3433  out << endl;
3434 #ifdef SANDESH
3435  indent(out) << "if length < 0: return -1" << endl;
3436  indent(out) << "read_cnt += length" << endl;
3437 #endif
3438  } else {
3439  printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
3440  tfield->get_name().c_str(), type->get_name().c_str());
3441  }
3442 }
3443 
3448  t_struct* tstruct,
3449  string prefix) {
3450  out <<
3451  indent() << prefix << " = " << type_name(tstruct) << "()" << endl <<
3452 #ifdef SANDESH
3453  indent() << "read_cnt += " << prefix << ".read(iprot)" << endl;
3454 #else
3455  indent() << prefix << ".read(iprot)" << endl;
3456 #endif
3457 }
3458 
3464  t_type* ttype,
3465  string prefix) {
3466  string size = tmp("_size");
3467  string ktype = tmp("_ktype");
3468  string vtype = tmp("_vtype");
3469  string etype = tmp("_etype");
3470 
3471  t_field fsize(g_type_i32, size);
3472  t_field fktype(g_type_byte, ktype);
3473  t_field fvtype(g_type_byte, vtype);
3474  t_field fetype(g_type_byte, etype);
3475 
3476  // Declare variables, read header
3477  if (ttype->is_map()) {
3478  out <<
3479  indent() << prefix << " = {}" << endl <<
3480 #ifdef SANDESH
3481  indent() << "(length, " << ktype << ", " << vtype << ", " << size << " ) = iprot.readMapBegin() " << endl <<
3482  indent() << "read_cnt += length" << endl;
3483 #else
3484  indent() << "(" << ktype << ", " << vtype << ", " << size << " ) = iprot.readMapBegin() " << endl;
3485 #endif
3486  } else if (ttype->is_set()) {
3487  out <<
3488  indent() << prefix << " = set()" << endl <<
3489 #ifdef SANDESH
3490  indent() << "(length, " << etype << ", " << size << ") = iprot.readSetBegin()" << endl <<
3491  indent() << "read_cnt += length" << endl;
3492 #else
3493  indent() << "(" << etype << ", " << size << ") = iprot.readSetBegin()" << endl;
3494 #endif
3495  } else if (ttype->is_list()) {
3496  out <<
3497  indent() << prefix << " = []" << endl <<
3498 #ifdef SANDESH
3499  indent() << "(length, " << etype << ", " << size << ") = iprot.readListBegin()" << endl <<
3500  indent() << "read_cnt += length" << endl;
3501 #else
3502  indent() << "(" << etype << ", " << size << ") = iprot.readListBegin()" << endl;
3503 #endif
3504  }
3505 
3506  // For loop iterates over elements
3507  string i = tmp("_i");
3508  indent(out) <<
3509  "for " << i << " in range(" << size << "):" << endl;
3510 
3511  indent_up();
3512 
3513  if (ttype->is_map()) {
3514  generate_deserialize_map_element(out, (t_map*)ttype, prefix);
3515  } else if (ttype->is_set()) {
3516 #ifdef SANDESH
3517  t_type *etype = ((t_set*)ttype)->get_elem_type();
3518  if (etype->is_base_type() || etype->is_enum()) {
3519  indent(out) << "read_cnt += iprot.readContainerElementBegin()" << endl;
3520  }
3521 #endif
3522  generate_deserialize_set_element(out, (t_set*)ttype, prefix);
3523 #ifdef SANDESH
3524  if (etype->is_base_type() || etype->is_enum()) {
3525  indent(out) << "read_cnt += iprot.readContainerElementEnd()" << endl;
3526  }
3527 #endif
3528  } else if (ttype->is_list()) {
3529 #ifdef SANDESH
3530  t_type *etype = ((t_list*)ttype)->get_elem_type();
3531  if (etype->is_base_type() || etype->is_enum()) {
3532  indent(out) << "read_cnt += iprot.readContainerElementBegin()" << endl;
3533  }
3534 #endif
3535  generate_deserialize_list_element(out, (t_list*)ttype, prefix);
3536 #ifdef SANDESH
3537  if (etype->is_base_type() || etype->is_enum()) {
3538  indent(out) << "read_cnt += iprot.readContainerElementEnd()" << endl;
3539  }
3540 #endif
3541  }
3542 
3543  indent_down();
3544 
3545  // Read container end
3546  if (ttype->is_map()) {
3547 #ifdef SANDESH
3548  indent(out) << "read_cnt += iprot.readMapEnd()" << endl;
3549 #else
3550  indent(out) << "iprot.readMapEnd()" << endl;
3551 #endif
3552  } else if (ttype->is_set()) {
3553 #ifdef SANDESH
3554  indent(out) << "read_cnt += iprot.readSetEnd()" << endl;
3555 #else
3556  indent(out) << "iprot.readSetEnd()" << endl;
3557 #endif
3558  } else if (ttype->is_list()) {
3559 #ifdef SANDESH
3560  indent(out) << "read_cnt += iprot.readListEnd()" << endl;
3561 #else
3562  indent(out) << "iprot.readListEnd()" << endl;
3563 #endif
3564  }
3565 }
3566 
3567 
3572  t_map* tmap,
3573  string prefix) {
3574  string key = tmp("_key");
3575  string val = tmp("_val");
3576  t_field fkey(tmap->get_key_type(), key);
3577  t_field fval(tmap->get_val_type(), val);
3578 
3579 #ifdef SANDESH
3580  t_type* kttype = tmap->get_key_type();
3581  if (kttype->is_base_type() || kttype->is_enum()) {
3582  indent(out) << "read_cnt += iprot.readContainerElementBegin()" << endl;
3583  }
3584 #endif
3585  generate_deserialize_field(out, &fkey);
3586 #ifdef SANDESH
3587  if (kttype->is_base_type() || kttype->is_enum()) {
3588  indent(out) << "read_cnt += iprot.readContainerElementEnd()" << endl;
3589  }
3590 #endif
3591 
3592 #ifdef SANDESH
3593  t_type* vttype = tmap->get_val_type();
3594  if (vttype->is_base_type() || vttype->is_enum()) {
3595  indent(out) << "read_cnt += iprot.readContainerElementBegin()" << endl;
3596  }
3597 #endif
3598  generate_deserialize_field(out, &fval);
3599 #ifdef SANDESH
3600  if (vttype->is_base_type() || vttype->is_enum()) {
3601  indent(out) << "read_cnt += iprot.readContainerElementEnd()" << endl;
3602  }
3603 #endif
3604 
3605  indent(out) <<
3606  prefix << "[" << key << "] = " << val << endl;
3607 }
3608 
3613  t_set* tset,
3614  string prefix) {
3615  string elem = tmp("_elem");
3616  t_field felem(tset->get_elem_type(), elem);
3617 
3618  generate_deserialize_field(out, &felem);
3619 
3620  indent(out) <<
3621  prefix << ".add(" << elem << ")" << endl;
3622 }
3623 
3628  t_list* tlist,
3629  string prefix) {
3630  string elem = tmp("_elem");
3631  t_field felem(tlist->get_elem_type(), elem);
3632 
3633  generate_deserialize_field(out, &felem);
3634 
3635  indent(out) <<
3636  prefix << ".append(" << elem << ")" << endl;
3637 }
3638 
3639 
3647  t_field* tfield,
3648  string prefix) {
3649  t_type* type = get_true_type(tfield->get_type());
3650 
3651  // Do nothing for void types
3652  if (type->is_void()) {
3653  throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
3654  prefix + tfield->get_name();
3655  }
3656 
3657  if (type->is_struct() || type->is_xception()) {
3659  (t_struct*)type,
3660  prefix + tfield->get_name());
3661  } else if (type->is_container()) {
3663  type,
3664  prefix + tfield->get_name());
3665  } else if (type->is_base_type() || type->is_enum()) {
3666 
3667  string name = prefix + tfield->get_name();
3668 
3669  indent(out) <<
3670  "if oprot.";
3671 
3672  if (type->is_base_type()) {
3673  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
3674  switch (tbase) {
3676  throw
3677  "compiler error: cannot serialize void field in a struct: " + name;
3678  break;
3680 #ifdef SANDESH
3681  case t_base_type::TYPE_STATIC_CONST_STRING:
3682 #endif
3683  if (((t_base_type*)type)->is_binary() || !gen_utf8strings_) {
3684  out << "writeString(" << name << ")";
3685  } else {
3686  out << "writeString(" << name << ".encode('utf-8'))";
3687  }
3688  break;
3689 #ifdef SANDESH
3690  case t_base_type::TYPE_XML:
3691  out << "writeXML(" << name << ")";
3692  break;
3693  case t_base_type::TYPE_UUID:
3694  out << "writeUUID(" << name << ")";
3695  break;
3696 #endif
3698  out << "writeBool(" << name << ")";
3699  break;
3701  out << "writeByte(" << name << ")";
3702  break;
3703  case t_base_type::TYPE_I16:
3704  out << "writeI16(" << name << ")";
3705  break;
3706  case t_base_type::TYPE_I32:
3707  out << "writeI32(" << name << ")";
3708  break;
3709  case t_base_type::TYPE_I64:
3710  out << "writeI64(" << name << ")";
3711  break;
3712 #ifdef SANDESH
3713  case t_base_type::TYPE_U16:
3714  out << "writeU16(" << name << ")";
3715  break;
3716  case t_base_type::TYPE_U32:
3717  out << "writeU32(" << name << ")";
3718  break;
3719  case t_base_type::TYPE_U64:
3720  out << "writeU64(" << name << ")";
3721  break;
3722  case t_base_type::TYPE_IPV4:
3723  out << "writeIPV4(" << name << ")";
3724  break;
3725  case t_base_type::TYPE_IPADDR:
3726  out << "writeIPADDR(" << name << ")";
3727  break;
3728 #endif
3730  out << "writeDouble(" << name << ")";
3731  break;
3732  default:
3733  throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
3734  }
3735  } else if (type->is_enum()) {
3736  out << "writeI32(" << name << ")";
3737  }
3738  out << " < 0: return -1" << endl;
3739 #ifdef SANDESH
3740  } else if (type->is_sandesh()) {
3741  generate_serialize_sandesh(out, (t_sandesh*)type,
3742  prefix + tfield->get_name());
3743 #endif
3744  } else {
3745  printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n",
3746  prefix.c_str(),
3747  tfield->get_name().c_str(),
3748  type->get_name().c_str());
3749  }
3750 }
3751 
3759  t_struct* tstruct,
3760  string prefix) {
3761  (void) tstruct;
3762  indent(out) <<
3763  "if " << prefix << ".write(oprot) < 0: return -1" << endl;
3764 }
3765 
3766 #ifdef SANDESH
3773 void t_py_generator::generate_serialize_sandesh(ofstream &out,
3774  t_sandesh* tsandesh,
3775  string prefix) {
3776  (void) tsandesh;
3777  indent(out) <<
3778  "if " << prefix << ".write(oprot) < 0: return -1" << endl;
3779 }
3780 #endif
3781 
3783  t_type* ttype,
3784  string prefix) {
3785  if (ttype->is_map()) {
3786  indent(out) <<
3787  "if oprot.writeMapBegin(" <<
3788  type_to_enum(((t_map*)ttype)->get_key_type()) << ", " <<
3789  type_to_enum(((t_map*)ttype)->get_val_type()) << ", " <<
3790  "len(" << prefix << ")) < 0: return -1" << endl;
3791  } else if (ttype->is_set()) {
3792  indent(out) <<
3793  "if oprot.writeSetBegin(" <<
3794  type_to_enum(((t_set*)ttype)->get_elem_type()) << ", " <<
3795  "len(" << prefix << ")) < 0: return -1" << endl;
3796  } else if (ttype->is_list()) {
3797  indent(out) <<
3798  "if oprot.writeListBegin(" <<
3799  type_to_enum(((t_list*)ttype)->get_elem_type()) << ", " <<
3800  "len(" << prefix << ")) < 0: return -1" << endl;
3801  }
3802 
3803  if (ttype->is_map()) {
3804  string kiter = tmp("kiter");
3805  string viter = tmp("viter");
3806  indent(out) <<
3807  "for " << kiter << "," << viter << " in " << prefix << ".items():" << endl;
3808  indent_up();
3809  generate_serialize_map_element(out, (t_map*)ttype, kiter, viter);
3810  indent_down();
3811  } else if (ttype->is_set()) {
3812  string iter = tmp("iter");
3813  indent(out) <<
3814  "for " << iter << " in " << prefix << ":" << endl;
3815  indent_up();
3816 #ifdef SANDESH
3817  t_type *etype = ((t_set*)ttype)->get_elem_type();
3818  if (etype->is_base_type() || etype->is_enum()) {
3819  indent(out) << "if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3820  }
3821 #endif
3822  generate_serialize_set_element(out, (t_set*)ttype, iter);
3823 #ifdef SANDESH
3824  if (etype->is_base_type() || etype->is_enum()) {
3825  indent(out) << "if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3826  }
3827 #endif
3828  indent_down();
3829  } else if (ttype->is_list()) {
3830  string iter = tmp("iter");
3831  indent(out) <<
3832  "for " << iter << " in " << prefix << ":" << endl;
3833  indent_up();
3834 #ifdef SANDESH
3835  t_type *etype = ((t_list*)ttype)->get_elem_type();
3836  if (etype->is_base_type() || etype->is_enum()) {
3837  indent(out) << "if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3838  }
3839 #endif
3840  generate_serialize_list_element(out, (t_list*)ttype, iter);
3841 #ifdef SANDESH
3842  if (etype->is_base_type() || etype->is_enum()) {
3843  indent(out) << "if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3844  }
3845 #endif
3846  indent_down();
3847  }
3848 
3849  if (ttype->is_map()) {
3850  indent(out) <<
3851  "if oprot.writeMapEnd() < 0: return -1" << endl;
3852  } else if (ttype->is_set()) {
3853  indent(out) <<
3854  "if oprot.writeSetEnd() < 0: return -1" << endl;
3855  } else if (ttype->is_list()) {
3856  indent(out) <<
3857  "if oprot.writeListEnd() < 0: return -1" << endl;
3858  }
3859 }
3860 
3866  t_map* tmap,
3867  string kiter,
3868  string viter) {
3869 #ifdef SANDESH
3870  t_type* kttype = tmap->get_key_type();
3871  if (kttype->is_base_type() || kttype->is_enum()) {
3872  indent(out) << "if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3873  }
3874 #endif
3875  t_field kfield(tmap->get_key_type(), kiter);
3876  generate_serialize_field(out, &kfield, "");
3877 #ifdef SANDESH
3878  if (kttype->is_base_type() || kttype->is_enum()) {
3879  indent(out) << "if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3880  }
3881 #endif
3882 
3883 #ifdef SANDESH
3884  t_type* vttype = tmap->get_val_type();
3885  if (vttype->is_base_type() || vttype->is_enum()) {
3886  indent(out) << "if oprot.writeContainerElementBegin() < 0: return -1" << endl;
3887  }
3888 #endif
3889  t_field vfield(tmap->get_val_type(), viter);
3890  generate_serialize_field(out, &vfield, "");
3891 #ifdef SANDESH
3892  if (vttype->is_base_type() || vttype->is_enum()) {
3893  indent(out) << "if oprot.writeContainerElementEnd() < 0: return -1" << endl;
3894  }
3895 #endif
3896 }
3897 
3902  t_set* tset,
3903  string iter) {
3904  t_field efield(tset->get_elem_type(), iter);
3905  generate_serialize_field(out, &efield, "");
3906 }
3907 
3912  t_list* tlist,
3913  string iter) {
3914  t_field efield(tlist->get_elem_type(), iter);
3915  generate_serialize_field(out, &efield, "");
3916 }
3917 
3922  t_struct* tstruct) {
3923  generate_python_docstring(out, tstruct, tstruct, "Attributes");
3924 }
3925 
3930  t_function* tfunction) {
3931  generate_python_docstring(out, tfunction, tfunction->get_arglist(), "Parameters");
3932 }
3933 
3938  t_doc* tdoc,
3939  t_struct* tstruct,
3940  const char* subheader) {
3941  bool has_doc = false;
3942  stringstream ss;
3943  if (tdoc->has_doc()) {
3944  has_doc = true;
3945  ss << tdoc->get_doc();
3946  }
3947 
3948  const vector<t_field*>& fields = tstruct->get_members();
3949  if (fields.size() > 0) {
3950  if (has_doc) {
3951  ss << endl;
3952  }
3953  has_doc = true;
3954  ss << subheader << ":\n";
3955  vector<t_field*>::const_iterator p_iter;
3956  for (p_iter = fields.begin(); p_iter != fields.end(); ++p_iter) {
3957  t_field* p = *p_iter;
3958  ss << " - " << p->get_name();
3959  if (p->has_doc()) {
3960  ss << ": " << p->get_doc();
3961  } else {
3962  ss << endl;
3963  }
3964  }
3965  }
3966 
3967  if (has_doc) {
3969  "\"\"\"\n",
3970  "", ss.str(),
3971  "\"\"\"\n");
3972  }
3973 }
3974 
3979  t_doc* tdoc) {
3980  if (tdoc->has_doc()) {
3982  "\"\"\"\n",
3983  "", tdoc->get_doc(),
3984  "\"\"\"\n");
3985  }
3986 }
3987 
3994  std::ostringstream result;
3995  result << tfield->get_name() << "=";
3996  if (tfield->get_value() != NULL) {
3997  result << "thrift_spec[" <<
3998  tfield->get_key() << "][4]";
3999  } else {
4000  result << "None";
4001  }
4002  return result.str();
4003 }
4004 
4011  t_type* type = get_true_type(tfield->get_type());
4012  if (tfield->get_value() != NULL) {
4013  return render_const_value(type, tfield->get_value());
4014  } else {
4015  return "None";
4016  }
4017 }
4018 
4026  string prefix) {
4027  // TODO(mcslee): Nitpicky, no ',' if argument_list is empty
4028  return
4029  prefix + tfunction->get_name() +
4030  "(self, " + argument_list(tfunction->get_arglist()) + ")";
4031 }
4032 
4040  string prefix) {
4041  // TODO(mcslee): Nitpicky, no ',' if argument_list is empty
4042  string signature = prefix + tfunction->get_name() + "(";
4043  if (!gen_twisted_) {
4044  signature += "self, ";
4045  }
4046  signature += argument_list(tfunction->get_arglist()) + ")";
4047  return signature;
4048 }
4049 
4050 
4055  string result = "";
4056 
4057  const vector<t_field*>& fields = tstruct->get_members();
4058  vector<t_field*>::const_iterator f_iter;
4059  bool first = true;
4060  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
4061  if (first) {
4062  first = false;
4063  } else {
4064  result += ", ";
4065  }
4066  result += (*f_iter)->get_name();
4067  }
4068  return result;
4069 }
4070 
4072  t_program* program = ttype->get_program();
4073  if (ttype->is_service()) {
4074  return get_real_py_module(program, gen_twisted_) + "." + ttype->get_name();
4075  }
4076  if (program != NULL && program != program_) {
4077  return get_real_py_module(program, gen_twisted_) + "_ttypes." + ttype->get_name();
4078  }
4079  return ttype->get_name();
4080 }
4081 
4086  type = get_true_type(type);
4087 
4088  if (type->is_base_type()) {
4089  t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
4090  switch (tbase) {
4092  throw "NO T_VOID CONSTRUCT";
4094  return "TType.STRING";
4096  return "TType.BOOL";
4098  return "TType.BYTE";
4099  case t_base_type::TYPE_I16:
4100  return "TType.I16";
4101  case t_base_type::TYPE_I32:
4102  return "TType.I32";
4103  case t_base_type::TYPE_I64:
4104  return "TType.I64";
4106  return "TType.DOUBLE";
4107 #ifdef SANDESH
4108  case t_base_type::TYPE_XML:
4109  return "TType.XML";
4110  case t_base_type::TYPE_UUID:
4111  return "TType.UUID";
4112  case t_base_type::TYPE_U16:
4113  return "TType.U16";
4114  case t_base_type::TYPE_U32:
4115  return "TType.U32";
4116  case t_base_type::TYPE_U64:
4117  return "TType.U64";
4118  case t_base_type::TYPE_IPV4:
4119  return "TType.IPV4";
4120  case t_base_type::TYPE_IPADDR:
4121  return "TType.IPADDR";
4122  case t_base_type::TYPE_STATIC_CONST_STRING:
4123  return "TType.STRING";
4124  case t_base_type::TYPE_SANDESH_SYSTEM:
4125  return "TType.STRING";
4126  case t_base_type::TYPE_SANDESH_REQUEST:
4127  return "TType.STRING";
4128  case t_base_type::TYPE_SANDESH_RESPONSE:
4129  return "TType.STRING";
4130  case t_base_type::TYPE_SANDESH_TRACE:
4131  return "TType.STRING";
4132  case t_base_type::TYPE_SANDESH_TRACE_OBJECT:
4133  return "TType.STRING";
4134  case t_base_type::TYPE_SANDESH_BUFFER:
4135  return "TTytpe.STRING";
4136  case t_base_type::TYPE_SANDESH_UVE:
4137  return "TTytpe.STRING";
4138  case t_base_type::TYPE_SANDESH_DYNAMIC_UVE:
4139  return "TTytpe.STRING";
4140  case t_base_type::TYPE_SANDESH_ALARM:
4141  return "TTytpe.STRING";
4142  case t_base_type::TYPE_SANDESH_OBJECT:
4143  return "TTytpe.STRING";
4144  case t_base_type::TYPE_SANDESH_FLOW:
4145  return "TTytpe.STRING";
4146  case t_base_type::TYPE_SANDESH_SESSION:
4147  return "TTytpe.STRING";
4148 #endif
4149  }
4150  } else if (type->is_enum()) {
4151  return "TType.I32";
4152  } else if (type->is_struct() || type->is_xception()) {
4153  return "TType.STRUCT";
4154 #ifdef SANDESH
4155  } else if (type->is_sandesh()) {
4156  return "TType.SANDESH";
4157 #endif
4158  } else if (type->is_map()) {
4159  return "TType.MAP";
4160  } else if (type->is_set()) {
4161  return "TType.SET";
4162  } else if (type->is_list()) {
4163  return "TType.LIST";
4164  }
4165 
4166  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
4167 }
4168 
4171  while (ttype->is_typedef()) {
4172  ttype = ((t_typedef*)ttype)->get_type();
4173  }
4174 
4175  if (ttype->is_base_type() || ttype->is_enum()) {
4176  return "None";
4177  } else if (ttype->is_struct() || ttype->is_xception()) {
4178  return "(" + type_name(ttype) + ", " + type_name(ttype) + ".thrift_spec)";
4179  } else if (ttype->is_map()) {
4180  return "(" +
4181  type_to_enum(((t_map*)ttype)->get_key_type()) + "," +
4182  type_to_spec_args(((t_map*)ttype)->get_key_type()) + "," +
4183  type_to_enum(((t_map*)ttype)->get_val_type()) + "," +
4184  type_to_spec_args(((t_map*)ttype)->get_val_type()) +
4185  ")";
4186 
4187  } else if (ttype->is_set()) {
4188  return "(" +
4189  type_to_enum(((t_set*)ttype)->get_elem_type()) + "," +
4190  type_to_spec_args(((t_set*)ttype)->get_elem_type()) +
4191  ")";
4192 
4193  } else if (ttype->is_list()) {
4194  return "(" +
4195  type_to_enum(((t_list*)ttype)->get_elem_type()) + "," +
4196  type_to_spec_args(((t_list*)ttype)->get_elem_type()) +
4197  ")";
4198  }
4199 
4200  throw "INVALID TYPE IN type_to_spec_args: " + ttype->get_name();
4201 }
4202 
4203 
4204 THRIFT_REGISTER_GENERATOR(py, "Python",
4205 " new_style: Generate new-style classes.\n" \
4206 " twisted: Generate Twisted-friendly RPC services.\n" \
4207 " utf8strings: Encode/decode strings using utf8 in the generated code.\n" \
4208 " slots: Generate code using slots for instance members.\n" \
4209 " dynamic: Generate dynamic code, less code generated but slower.\n" \
4210 " dynbase=CLS Derive generated classes from class CLS instead of TBase.\n" \
4211 " dynexc=CLS Derive generated exceptions from CLS instead of TExceptionBase.\n" \
4212 " dynimport='from foo.bar import CLS'\n" \
4213 " Add an import line to generated code to find the dynbase class.\n")
t_base get_base() const
Definition: t_base_type.h:84
static std::string t_base_name(t_base tbase)
Definition: t_base_type.h:221
const std::vector< t_const_value * > & get_list() const
double get_double() const
std::string get_string() const
Definition: t_const_value.h:66
t_const_value_type get_type() const
const std::map< t_const_value *, t_const_value * > & get_map() const
int64_t get_integer() const
Definition: t_const_value.h:75
t_type * get_type() const
Definition: t_const.h:43
std::string get_name() const
Definition: t_const.h:47
t_const_value * get_value() const
Definition: t_const.h:51
Definition: t_doc.h:30
bool has_doc()
Definition: t_doc.h:44
const std::string & get_doc() const
Definition: t_doc.h:40
Definition: t_enum.h:33
const std::vector< t_enum_value * > & get_constants()
Definition: t_enum.h:46
int32_t get_key() const
Definition: t_field.h:102
t_const_value * get_value()
Definition: t_field.h:124
const std::string & get_name() const
Definition: t_field.h:98
t_type * get_type() const
Definition: t_field.h:94
@ T_REQUIRED
Definition: t_field.h:107
e_req get_req() const
Definition: t_field.h:116
bool is_oneway() const
Definition: t_function.h:106
t_type * get_returntype() const
Definition: t_function.h:90
t_struct * get_arglist() const
Definition: t_function.h:98
t_struct * get_xceptions() const
Definition: t_function.h:102
const std::string & get_name() const
Definition: t_function.h:94
std::string tmp(std::string name)
Definition: t_generator.h:163
std::string service_name_
Definition: t_generator.h:291
void generate_docstring_comment(std::ofstream &out, const std::string &comment_start, const std::string &line_prefix, const std::string &contents, const std::string &comment_end)
Definition: t_generator.cc:110
void indent_up()
Definition: t_generator.h:173
t_program * program_
Definition: t_generator.h:279
std::string indent()
Definition: t_generator.h:184
static t_type * get_true_type(t_type *type)
Definition: t_generator.h:271
void indent_down()
Definition: t_generator.h:177
Definition: t_list.h:32
t_type * get_elem_type() const
Definition: t_list.h:37
Definition: t_map.h:33
t_type * get_key_type() const
Definition: t_map.h:39
t_type * get_val_type() const
Definition: t_map.h:43
const std::string & get_namespace() const
Definition: t_program.h:98
const std::string & get_name() const
Definition: t_program.h:95
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)
std::string render_fastbinary_includes()
std::string copy_options_
std::ofstream f_consts_
std::string render_const_value(t_type *type, t_const_value *value)
void generate_enum(t_enum *tenum)
std::string type_to_spec_args(t_type *ttype)
void generate_struct(t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_function *tfunction)
std::ofstream f_service_
void generate_deserialize_map_element(std::ofstream &out, t_map *tmap, std::string prefix="")
std::string gen_dynbaseclass_
std::string py_autogen_comment()
void generate_serialize_set_element(std::ofstream &out, t_set *tmap, std::string iter)
static bool is_valid_namespace(const std::string &sub_namespace)
void generate_serialize_map_element(std::ofstream &out, t_map *tmap, std::string kiter, std::string viter)
void generate_py_struct_writer(std::ofstream &out, t_struct *tstruct)
void generate_deserialize_list_element(std::ofstream &out, t_list *tlist, std::string prefix="")
std::string argument_list(t_struct *tstruct)
std::string future_imports()
void generate_deserialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
std::string py_imports()
std::string type_to_enum(t_type *ttype)
void generate_py_function_helpers(t_function *tfunction)
void generate_py_struct_required_validator(std::ofstream &out, t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_struct *tstruct)
void generate_service_server(t_service *tservice)
void generate_serialize_list_element(std::ofstream &out, t_list *tlist, std::string iter)
void generate_deserialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
void generate_deserialize_set_element(std::ofstream &out, t_set *tset, std::string prefix="")
void generate_serialize_container(std::ofstream &out, t_type *ttype, std::string prefix="")
void generate_py_struct_reader(std::ofstream &out, t_struct *tstruct)
void generate_python_docstring(std::ofstream &out, t_doc *tdoc, t_struct *tstruct, const char *subheader)
void generate_xception(t_struct *txception)
std::string import_dynbase_
std::string package_dir_
std::string function_signature(t_function *tfunction, std::string prefix="")
std::string type_name(t_type *ttype)
void generate_process_function(t_service *tservice, t_function *tfunction)
void generate_python_docstring(std::ofstream &out, t_doc *tdoc)
std::ofstream f_types_
void generate_service(t_service *tservice)
std::string function_signature_if(t_function *tfunction, std::string prefix="")
void generate_serialize_field(std::ofstream &out, t_field *tfield, std::string prefix="")
std::string gen_dynbaseclass_exc_
void generate_service_client(t_service *tservice)
void generate_service_interface(t_service *tservice)
void generate_service_remote(t_service *tservice)
void generate_typedef(t_typedef *ttypedef)
void generate_const(t_const *tconst)
void generate_serialize_struct(std::ofstream &out, t_struct *tstruct, std::string prefix="")
static std::string get_real_py_module(const t_program *program, bool gen_twisted)
std::string declare_argument(t_field *tfield)
t_py_generator(t_program *program, const std::map< std::string, std::string > &parsed_options, const std::string &option_string)
std::string render_includes()
void generate_service_helpers(t_service *tservice)
std::string render_field_default_value(t_field *tfield)
void generate_deserialize_field(std::ofstream &out, t_field *tfield, std::string prefix="", bool inclass=false)
virtual bool has_key_annotation() const
const t_type * get_type()
Definition: t_sandesh.h:74
t_service * get_extends()
Definition: t_service.h:63
const std::vector< t_function * > & get_functions() const
Definition: t_service.h:59
Definition: t_set.h:32
t_type * get_elem_type() const
Definition: t_set.h:37
bool append(t_field *elem)
const members_type & get_sorted_members()
const members_type & get_members()
Definition: t_type.h:51
virtual bool is_service() const
Definition: t_type.h:82
const uint32_t get_4byte_fingerprint() const
Definition: t_type.h:142
virtual bool is_set() const
Definition: t_type.h:80
virtual bool is_xception() const
Definition: t_type.h:77
virtual bool is_struct() const
Definition: t_type.h:76
virtual bool is_enum() const
Definition: t_type.h:75
virtual const std::string & get_name() const
Definition: t_type.h:59
t_program * get_program()
Definition: t_type.h:84
virtual bool is_base_type() const
Definition: t_type.h:64
virtual bool is_list() const
Definition: t_type.h:79
virtual bool is_typedef() const
Definition: t_type.h:74
virtual bool is_map() const
Definition: t_type.h:81
virtual bool is_void() const
Definition: t_type.h:63
uint8_t type
Definition: load_balance.h:2
void init()
Definition: bgp_log.cc:38
#define MKDIR(x)
Definition: platform.h:31
#define THRIFT_REGISTER_GENERATOR(language, long_name, doc)
#define SANDESH_VERSION
Definition: version.h:1