Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
30 ashish 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
 * Contains some contributions under the Thrift Software License.
20
 * Please see doc/old-thrift-license.txt in the Thrift distribution for
21
 * details.
22
 */
23
 
24
#include <string>
25
#include <fstream>
26
#include <iostream>
27
#include <vector>
28
 
29
#include <stdlib.h>
30
#include <sys/stat.h>
31
#include <sys/types.h>
32
#include <sstream>
33
 
34
#include <boost/tokenizer.hpp>
35
 
36
#include "t_oop_generator.h"
37
#include "platform.h"
38
using namespace std;
39
 
40
 
41
/**
42
 * Ruby code generator.
43
 *
44
 */
45
class t_rb_generator : public t_oop_generator {
46
 public:
47
  t_rb_generator(
48
      t_program* program,
49
      const std::map<std::string, std::string>& parsed_options,
50
      const std::string& option_string)
51
    : t_oop_generator(program)
52
  {
53
    out_dir_base_ = "gen-rb";
54
  }
55
 
56
  /**
57
   * Init and close methods
58
   */
59
 
60
  void init_generator();
61
  void close_generator();
62
 
63
  /**
64
   * Program-level generation functions
65
   */
66
 
67
  void generate_typedef     (t_typedef*  ttypedef);
68
  void generate_enum        (t_enum*     tenum);
69
  void generate_const       (t_const*    tconst);
70
  void generate_struct      (t_struct*   tstruct);
71
  void generate_xception    (t_struct*   txception);
72
  void generate_service     (t_service*  tservice);
73
 
74
  std::string render_const_value(t_type* type, t_const_value* value);
75
 
76
  /**
77
   * Struct generation code
78
   */
79
 
80
  void generate_rb_struct(std::ofstream& out, t_struct* tstruct, bool is_exception);
81
  void generate_rb_struct_required_validator(std::ofstream& out, t_struct* tstruct);
82
  void generate_rb_function_helpers(t_function* tfunction);
83
  void generate_rb_simple_constructor(std::ofstream& out, t_struct* tstruct);
84
  void generate_rb_simple_exception_constructor(std::ofstream& out, t_struct* tstruct);
85
  void generate_field_constants (std::ofstream& out, t_struct* tstruct);
86
  void generate_accessors   (std::ofstream& out, t_struct* tstruct);
87
  void generate_field_defns (std::ofstream& out, t_struct* tstruct);
88
  void generate_field_data  (std::ofstream& out, t_type* field_type, const std::string& field_name, t_const_value* field_value, bool optional);
89
 
90
  /**
91
   * Service-level generation functions
92
   */
93
 
94
  void generate_service_helpers   (t_service*  tservice);
95
  void generate_service_interface (t_service* tservice);
96
  void generate_service_client    (t_service* tservice);
97
  void generate_service_server    (t_service* tservice);
98
  void generate_process_function  (t_service* tservice, t_function* tfunction);
99
 
100
  /**
101
   * Serialization constructs
102
   */
103
 
104
  void generate_deserialize_field        (std::ofstream &out,
105
                                          t_field*    tfield,
106
                                          std::string prefix="",
107
                                          bool inclass=false);
108
 
109
  void generate_deserialize_struct       (std::ofstream &out,
110
                                          t_struct*   tstruct,
111
                                          std::string prefix="");
112
 
113
  void generate_deserialize_container    (std::ofstream &out,
114
                                          t_type*     ttype,
115
                                          std::string prefix="");
116
 
117
  void generate_deserialize_set_element  (std::ofstream &out,
118
                                          t_set*      tset,
119
                                          std::string prefix="");
120
 
121
  void generate_deserialize_map_element  (std::ofstream &out,
122
                                          t_map*      tmap,
123
                                          std::string prefix="");
124
 
125
  void generate_deserialize_list_element (std::ofstream &out,
126
                                          t_list*     tlist,
127
                                          std::string prefix="");
128
 
129
  void generate_serialize_field          (std::ofstream &out,
130
                                          t_field*    tfield,
131
                                          std::string prefix="");
132
 
133
  void generate_serialize_struct         (std::ofstream &out,
134
                                          t_struct*   tstruct,
135
                                          std::string prefix="");
136
 
137
  void generate_serialize_container      (std::ofstream &out,
138
                                          t_type*     ttype,
139
                                          std::string prefix="");
140
 
141
  void generate_serialize_map_element    (std::ofstream &out,
142
                                          t_map*      tmap,
143
                                          std::string kiter,
144
                                          std::string viter);
145
 
146
  void generate_serialize_set_element    (std::ofstream &out,
147
                                          t_set*      tmap,
148
                                          std::string iter);
149
 
150
  void generate_serialize_list_element   (std::ofstream &out,
151
                                          t_list*     tlist,
152
                                          std::string iter);
153
 
154
  void generate_rdoc                     (std::ofstream& out, 
155
                                          t_doc* tdoc);
156
 
157
  /**
158
   * Helper rendering functions
159
   */
160
 
161
  std::string rb_autogen_comment();
162
  std::string render_includes();
163
  std::string declare_field(t_field* tfield);
164
  std::string type_name(t_type* ttype);
165
  std::string full_type_name(t_type* ttype);
166
  std::string function_signature(t_function* tfunction, std::string prefix="");
167
  std::string argument_list(t_struct* tstruct);
168
  std::string type_to_enum(t_type* ttype);
169
 
170
 
171
 
172
  std::vector<std::string> ruby_modules(t_program* p) {
173
    std::string ns = p->get_namespace("rb");
174
    boost::tokenizer<> tok(ns);
175
    std::vector<std::string> modules;
176
 
177
    for(boost::tokenizer<>::iterator beg=tok.begin(); beg != tok.end(); ++beg) {
178
      modules.push_back(capitalize(*beg));
179
    }
180
 
181
    return modules;
182
  }
183
 
184
  void begin_namespace(std::ofstream&, std::vector<std::string>);
185
  void end_namespace(std::ofstream&, std::vector<std::string>);
186
 
187
 private:
188
 
189
  /**
190
   * File streams
191
   */
192
 
193
  std::ofstream f_types_;
194
  std::ofstream f_consts_;
195
  std::ofstream f_service_;
196
 
197
};
198
 
199
 
200
/**
201
 * Prepares for file generation by opening up the necessary file output
202
 * streams.
203
 *
204
 * @param tprogram The program to generate
205
 */
206
void t_rb_generator::init_generator() {
207
  // Make output directory
208
  MKDIR(get_out_dir().c_str());
209
 
210
  // Make output file
211
  string f_types_name = get_out_dir()+underscore(program_name_)+"_types.rb";
212
  f_types_.open(f_types_name.c_str());
213
 
214
  string f_consts_name = get_out_dir()+underscore(program_name_)+"_constants.rb";
215
  f_consts_.open(f_consts_name.c_str());
216
 
217
  // Print header
218
  f_types_ <<
219
    rb_autogen_comment() << endl <<
220
    render_includes() << endl;
221
    begin_namespace(f_types_, ruby_modules(program_));
222
 
223
  f_consts_ <<
224
    rb_autogen_comment() << endl <<
225
    "require '" << underscore(program_name_) << "_types'" << endl <<
226
    endl;
227
    begin_namespace(f_consts_, ruby_modules(program_));
228
 
229
}
230
 
231
/**
232
 * Renders all the imports necessary for including another Thrift program
233
 */
234
string t_rb_generator::render_includes() {
235
  const vector<t_program*>& includes = program_->get_includes();
236
  string result = "";
237
  for (size_t i = 0; i < includes.size(); ++i) {
238
    result += "require '" + underscore(includes[i]->get_name()) + "_types'\n";
239
  }
240
  if (includes.size() > 0) {
241
    result += "\n";
242
  }
243
  return result;
244
}
245
 
246
/**
247
 * Autogen'd comment
248
 */
249
string t_rb_generator::rb_autogen_comment() {
250
  return
251
    std::string("#\n") +
252
    "# Autogenerated by Thrift\n" +
253
    "#\n" +
254
    "# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
255
    "#\n";
256
}
257
 
258
/**
259
 * Closes the type files
260
 */
261
void t_rb_generator::close_generator() {
262
  // Close types file
263
  end_namespace(f_types_, ruby_modules(program_));
264
  end_namespace(f_consts_, ruby_modules(program_));
265
  f_types_.close();
266
  f_consts_.close();
267
}
268
 
269
/**
270
 * Generates a typedef. This is not done in Ruby, types are all implicit.
271
 *
272
 * @param ttypedef The type definition
273
 */
274
void t_rb_generator::generate_typedef(t_typedef* ttypedef) {}
275
 
276
/**
277
 * Generates code for an enumerated type. Done using a class to scope
278
 * the values.
279
 *
280
 * @param tenum The enumeration
281
 */
282
void t_rb_generator::generate_enum(t_enum* tenum) {
283
  indent(f_types_) <<
284
    "module " << capitalize(tenum->get_name()) << endl;
285
  indent_up();
286
 
287
  vector<t_enum_value*> constants = tenum->get_constants();
288
  vector<t_enum_value*>::iterator c_iter;
289
  int value = -1;
290
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
291
    if ((*c_iter)->has_value()) {
292
      value = (*c_iter)->get_value();
293
    } else {
294
      ++value;
295
    }
296
 
297
    // Ruby class constants have to be capitalized... omg i am so on the fence
298
    // about languages strictly enforcing capitalization why can't we just all
299
    // agree and play nice.
300
    string name = capitalize((*c_iter)->get_name());
301
 
302
    f_types_ <<
303
      indent() << name << " = " << value << endl;
304
  }
305
 
306
  //Create a hash mapping values back to their names (as strings) since ruby has no native enum type
307
  indent(f_types_) << "VALUE_MAP = {";
308
  bool first = true;
309
  value = -1;
310
  for(c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
311
    //Populate the hash
312
    //If no value is given, use the next available one
313
    if ((*c_iter)->has_value())
314
      value = (*c_iter)->get_value();
315
    else ++value;
316
 
317
    first ? first = false : f_types_ << ", ";
318
    f_types_ << value << " => \"" << capitalize((*c_iter)->get_name()) << "\"";
319
 
320
  }
321
  f_types_ << "}" << endl;
322
 
323
  // Create a set with valid values for this enum
324
  indent(f_types_) << "VALID_VALUES = Set.new([";
325
  first = true;
326
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
327
    // Populate the set
328
    first ? first = false: f_types_ << ", ";
329
    f_types_ << capitalize((*c_iter)->get_name());
330
  }
331
  f_types_ << "]).freeze" << endl;
332
 
333
  indent_down();
334
  indent(f_types_) <<
335
    "end" << endl << endl;
336
}
337
 
338
/**
339
 * Generate a constant value
340
 */
341
void t_rb_generator::generate_const(t_const* tconst) {
342
  t_type* type = tconst->get_type();
343
  string name = tconst->get_name();
344
  t_const_value* value = tconst->get_value();
345
 
346
  name[0] = toupper(name[0]);
347
 
348
  indent(f_consts_) << name << " = " << render_const_value(type, value);
349
  f_consts_ << endl << endl;
350
}
351
 
352
/**
353
 * Prints the value of a constant with the given type. Note that type checking
354
 * is NOT performed in this function as it is always run beforehand using the
355
 * validate_types method in main.cc
356
 */
357
string t_rb_generator::render_const_value(t_type* type, t_const_value* value) {
358
  type = get_true_type(type);
359
  std::ostringstream out;
360
  if (type->is_base_type()) {
361
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
362
    switch (tbase) {
363
    case t_base_type::TYPE_STRING:
364
      out << "%q\"" << get_escaped_string(value) << '"';
365
      break;
366
    case t_base_type::TYPE_BOOL:
367
      out << (value->get_integer() > 0 ? "true" : "false");
368
      break;
369
    case t_base_type::TYPE_BYTE:
370
    case t_base_type::TYPE_I16:
371
    case t_base_type::TYPE_I32:
372
    case t_base_type::TYPE_I64:
373
      out << value->get_integer();
374
      break;
375
    case t_base_type::TYPE_DOUBLE:
376
      if (value->get_type() == t_const_value::CV_INTEGER) {
377
        out << value->get_integer();
378
      } else {
379
        out << value->get_double();
380
      }
381
      break;
382
    default:
383
      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
384
    }
385
  } else if (type->is_enum()) {
386
    indent(out) << value->get_integer();
387
  } else if (type->is_struct() || type->is_xception()) {
388
    out << full_type_name(type) << ".new({" << endl;
389
    indent_up();
390
    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
391
    vector<t_field*>::const_iterator f_iter;
392
    const map<t_const_value*, t_const_value*>& val = value->get_map();
393
    map<t_const_value*, t_const_value*>::const_iterator v_iter;
394
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
395
      t_type* field_type = NULL;
396
      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
397
        if ((*f_iter)->get_name() == v_iter->first->get_string()) {
398
          field_type = (*f_iter)->get_type();
399
        }
400
      }
401
      if (field_type == NULL) {
402
        throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
403
      }
404
      out << indent();
405
      out << render_const_value(g_type_string, v_iter->first);
406
      out << " => ";
407
      out << render_const_value(field_type, v_iter->second);
408
      out << "," << endl;
409
    }
410
    indent_down();
411
    indent(out) << "})";
412
  } else if (type->is_map()) {
413
    t_type* ktype = ((t_map*)type)->get_key_type();
414
    t_type* vtype = ((t_map*)type)->get_val_type();
415
    out << "{" << endl;
416
    indent_up();
417
    const map<t_const_value*, t_const_value*>& val = value->get_map();
418
    map<t_const_value*, t_const_value*>::const_iterator v_iter;
419
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
420
      out << indent();
421
      out << render_const_value(ktype, v_iter->first);
422
      out << " => ";
423
      out << render_const_value(vtype, v_iter->second);
424
      out << "," << endl;
425
    }
426
    indent_down();
427
    indent(out) << "}";
428
  } else if (type->is_list() || type->is_set()) {
429
    t_type* etype;
430
    if (type->is_list()) {
431
      etype = ((t_list*)type)->get_elem_type();
432
    } else {
433
      etype = ((t_set*)type)->get_elem_type();
434
    }
435
    if (type->is_set()) {
436
      out << "Set.new([" << endl;
437
    } else {
438
      out << "[" << endl;
439
    }
440
    indent_up();
441
    const vector<t_const_value*>& val = value->get_list();
442
    vector<t_const_value*>::const_iterator v_iter;
443
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
444
      out << indent();
445
      out << render_const_value(etype, *v_iter);
446
      out << "," << endl;
447
    }
448
    indent_down();
449
    if (type->is_set()) {
450
      indent(out) << "])";
451
    } else {
452
      indent(out) << "]";
453
    }
454
  } else {
455
    throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
456
  }
457
  return out.str();
458
}
459
 
460
/**
461
 * Generates a ruby struct
462
 */
463
void t_rb_generator::generate_struct(t_struct* tstruct) {
464
  generate_rb_struct(f_types_, tstruct, false);
465
}
466
 
467
/**
468
 * Generates a struct definition for a thrift exception. Basically the same
469
 * as a struct but extends the Exception class.
470
 *
471
 * @param txception The struct definition
472
 */
473
void t_rb_generator::generate_xception(t_struct* txception) {
474
  generate_rb_struct(f_types_, txception, true);
475
}
476
 
477
/**
478
 * Generates a ruby struct
479
 */
480
void t_rb_generator::generate_rb_struct(std::ofstream& out, t_struct* tstruct, bool is_exception = false) {
481
  generate_rdoc(out, tstruct);
482
  indent(out) << "class " << type_name(tstruct);
483
  if (is_exception) {
484
    out << " < ::Thrift::Exception";
485
  }
486
  out << endl;
487
 
488
  indent_up();
489
  indent(out) << "include ::Thrift::Struct" << endl;
490
 
491
  if (is_exception) {
492
    generate_rb_simple_exception_constructor(out, tstruct);
493
  }
494
 
495
  generate_field_constants(out, tstruct);
496
  generate_accessors(out, tstruct);
497
  generate_field_defns(out, tstruct);
498
  generate_rb_struct_required_validator(out, tstruct);
499
 
500
  indent_down();
501
  indent(out) << "end" << endl << endl;
502
}
503
 
504
void t_rb_generator::generate_rb_simple_exception_constructor(std::ofstream& out, t_struct* tstruct) {
505
  const vector<t_field*>& members = tstruct->get_members();
506
 
507
  if (members.size() == 1) {
508
    vector<t_field*>::const_iterator m_iter = members.begin();
509
 
510
    if ((*m_iter)->get_type()->is_string()) {
511
      string name = (*m_iter)->get_name();
512
 
513
      indent(out) << "def initialize(message=nil)" << endl;
514
      indent_up();
515
      indent(out) << "super()" << endl;
516
      indent(out) << "self." << name << " = message" << endl;
517
      indent_down();
518
      indent(out) << "end" << endl << endl;
519
 
520
      if (name != "message") {
521
        indent(out) << "def message; " << name << " end" << endl << endl;
522
      }
523
    }
524
  }
525
}
526
 
527
void t_rb_generator::generate_field_constants(std::ofstream& out, t_struct* tstruct) {
528
  const vector<t_field*>& fields = tstruct->get_members();
529
  vector<t_field*>::const_iterator f_iter;
530
 
531
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
532
    std::string field_name = (*f_iter)->get_name();
533
    std::string cap_field_name = upcase_string(field_name);
534
 
535
    indent(out) << cap_field_name << " = " << (*f_iter)->get_key() << endl;
536
  }
537
  out << endl;
538
}
539
 
540
void t_rb_generator::generate_accessors(std::ofstream& out, t_struct* tstruct) {
541
  const vector<t_field*>& members = tstruct->get_members();
542
  vector<t_field*>::const_iterator m_iter;
543
 
544
  if (members.size() > 0) {
545
    indent(out) << "::Thrift::Struct.field_accessor self";
546
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
547
      out << ", :" << (*m_iter)->get_name();
548
    }
549
    out << endl;
550
  }
551
}
552
 
553
void t_rb_generator::generate_field_defns(std::ofstream& out, t_struct* tstruct) {
554
  const vector<t_field*>& fields = tstruct->get_members();
555
  vector<t_field*>::const_iterator f_iter;
556
 
557
  indent(out) << "FIELDS = {" << endl;
558
  indent_up();
559
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
560
    if (f_iter != fields.begin()) {
561
      out << "," << endl;
562
    }
563
 
564
    // generate the field docstrings within the FIELDS constant. no real better place...
565
    generate_rdoc(out, *f_iter);
566
 
567
    indent(out) <<
568
      upcase_string((*f_iter)->get_name()) << " => ";
569
 
570
    generate_field_data(out, (*f_iter)->get_type(), (*f_iter)->get_name(), (*f_iter)->get_value(), 
571
      (*f_iter)->get_req() == t_field::T_OPTIONAL);
572
  }
573
  indent_down();
574
  out << endl;
575
  indent(out) << "}" << endl << endl;
576
 
577
  indent(out) << "def struct_fields; FIELDS; end" << endl << endl;
578
 
579
}
580
 
581
void t_rb_generator::generate_field_data(std::ofstream& out, t_type* field_type,
582
    const std::string& field_name = "", t_const_value* field_value = NULL, bool optional = false) {
583
  field_type = get_true_type(field_type);
584
 
585
  // Begin this field's defn
586
  out << "{:type => " << type_to_enum(field_type);
587
 
588
  if (!field_name.empty()) {
589
    out << ", :name => '" << field_name << "'";
590
  }
591
 
592
  if (field_value != NULL) {
593
    out << ", :default => " << render_const_value(field_type, field_value);
594
  }
595
 
596
  if (!field_type->is_base_type()) {
597
    if (field_type->is_struct() || field_type->is_xception()) {
598
      out << ", :class => " << full_type_name((t_struct*)field_type);
599
    } else if (field_type->is_list()) {
600
      out << ", :element => ";
601
      generate_field_data(out, ((t_list*)field_type)->get_elem_type());
602
    } else if (field_type->is_map()) {
603
      out << ", :key => ";
604
      generate_field_data(out, ((t_map*)field_type)->get_key_type());
605
      out << ", :value => ";
606
      generate_field_data(out, ((t_map*)field_type)->get_val_type());
607
    } else if (field_type->is_set()) {
608
      out << ", :element => ";
609
      generate_field_data(out, ((t_set*)field_type)->get_elem_type());
610
    }
611
  }
612
 
613
  if(optional) {
614
    out << ", :optional => true";
615
  }
616
 
617
  if (field_type->is_enum()) {
618
    out << ", :enum_class => " << full_type_name(field_type);
619
  }
620
 
621
  // End of this field's defn
622
  out << "}";
623
}
624
 
625
void t_rb_generator::begin_namespace(std::ofstream& out, vector<std::string> modules) {
626
  for (vector<std::string>::iterator m_iter = modules.begin(); m_iter != modules.end(); ++m_iter) {
627
    indent(out) << "module " << *m_iter << endl;
628
    indent_up();
629
  }
630
}
631
 
632
void t_rb_generator::end_namespace(std::ofstream& out, vector<std::string> modules) {
633
  for (vector<std::string>::reverse_iterator m_iter = modules.rbegin(); m_iter != modules.rend(); ++m_iter) {
634
    indent_down();
635
    indent(out) << "end" << endl;
636
  }
637
}
638
 
639
 
640
/**
641
 * Generates a thrift service.
642
 *
643
 * @param tservice The service definition
644
 */
645
void t_rb_generator::generate_service(t_service* tservice) {
646
  string f_service_name = get_out_dir()+underscore(service_name_)+".rb";
647
  f_service_.open(f_service_name.c_str());
648
 
649
  f_service_ <<
650
    rb_autogen_comment() << endl <<
651
    "require 'thrift'" << endl;
652
 
653
  if (tservice->get_extends() != NULL) {
654
    f_service_ <<
655
      "require '" << underscore(tservice->get_extends()->get_name()) << "'" << endl;
656
  }
657
 
658
  f_service_ <<
659
    "require '" << underscore(program_name_) << "_types'" << endl <<
660
    endl;
661
 
662
  begin_namespace(f_service_, ruby_modules(tservice->get_program()));
663
 
664
  indent(f_service_) << "module " << capitalize(tservice->get_name()) << endl;
665
  indent_up();
666
 
667
  // Generate the three main parts of the service (well, two for now in PHP)
668
  generate_service_client(tservice);
669
  generate_service_server(tservice);
670
  generate_service_helpers(tservice);
671
 
672
  indent_down();
673
  indent(f_service_) << "end" << endl <<
674
    endl;
675
 
676
  end_namespace(f_service_, ruby_modules(tservice->get_program()));
677
 
678
  // Close service file
679
  f_service_.close();
680
}
681
 
682
/**
683
 * Generates helper functions for a service.
684
 *
685
 * @param tservice The service to generate a header definition for
686
 */
687
void t_rb_generator::generate_service_helpers(t_service* tservice) {
688
  vector<t_function*> functions = tservice->get_functions();
689
  vector<t_function*>::iterator f_iter;
690
 
691
  indent(f_service_) <<
692
    "# HELPER FUNCTIONS AND STRUCTURES" << endl << endl;
693
 
694
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
695
    t_struct* ts = (*f_iter)->get_arglist();
696
    generate_rb_struct(f_service_, ts);
697
    generate_rb_function_helpers(*f_iter);
698
  }
699
}
700
 
701
/**
702
 * Generates a struct and helpers for a function.
703
 *
704
 * @param tfunction The function
705
 */
706
void t_rb_generator::generate_rb_function_helpers(t_function* tfunction) {
707
  t_struct result(program_, tfunction->get_name() + "_result");
708
  t_field success(tfunction->get_returntype(), "success", 0);
709
  if (!tfunction->get_returntype()->is_void()) {
710
    result.append(&success);
711
  }
712
 
713
  t_struct* xs = tfunction->get_xceptions();
714
  const vector<t_field*>& fields = xs->get_members();
715
  vector<t_field*>::const_iterator f_iter;
716
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
717
    result.append(*f_iter);
718
  }
719
  generate_rb_struct(f_service_, &result);
720
}
721
 
722
/**
723
 * Generates a service client definition.
724
 *
725
 * @param tservice The service to generate a server for.
726
 */
727
void t_rb_generator::generate_service_client(t_service* tservice) {
728
  string extends = "";
729
  string extends_client = "";
730
  if (tservice->get_extends() != NULL) {
731
    extends = full_type_name(tservice->get_extends());
732
    extends_client = " < " + extends + "::Client ";
733
  }
734
 
735
  indent(f_service_) <<
736
    "class Client" << extends_client << endl;
737
  indent_up();
738
 
739
  indent(f_service_) <<
740
    "include ::Thrift::Client" << endl << endl;
741
 
742
  // Generate client method implementations
743
  vector<t_function*> functions = tservice->get_functions();
744
  vector<t_function*>::const_iterator f_iter;
745
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
746
    t_struct* arg_struct = (*f_iter)->get_arglist();
747
    const vector<t_field*>& fields = arg_struct->get_members();
748
    vector<t_field*>::const_iterator fld_iter;
749
    string funname = (*f_iter)->get_name();
750
 
751
    // Open function
752
    indent(f_service_) <<
753
      "def " << function_signature(*f_iter) << endl;
754
    indent_up();
755
      indent(f_service_) <<
756
        "send_" << funname << "(";
757
 
758
      bool first = true;
759
      for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
760
        if (first) {
761
          first = false;
762
        } else {
763
          f_service_ << ", ";
764
        }
765
        f_service_ << (*fld_iter)->get_name();
766
      }
767
      f_service_ << ")" << endl;
768
 
769
      if (!(*f_iter)->is_oneway()) {
770
        f_service_ << indent();
771
        if (!(*f_iter)->get_returntype()->is_void()) {
772
          f_service_ << "return ";
773
        }
774
        f_service_ <<
775
          "recv_" << funname << "()" << endl;
776
      }
777
    indent_down();
778
    indent(f_service_) << "end" << endl;
779
    f_service_ << endl;
780
 
781
    indent(f_service_) <<
782
      "def send_" << function_signature(*f_iter) << endl;
783
    indent_up();
784
 
785
      std::string argsname = capitalize((*f_iter)->get_name() + "_args");
786
 
787
      indent(f_service_) << "send_message('" << funname << "', " << argsname;
788
 
789
      for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
790
        f_service_ << ", :" << (*fld_iter)->get_name() << " => " << (*fld_iter)->get_name();
791
      }
792
 
793
      f_service_ << ")" << endl;
794
 
795
    indent_down();
796
    indent(f_service_) << "end" << endl;
797
 
798
    if (!(*f_iter)->is_oneway()) {
799
      std::string resultname = capitalize((*f_iter)->get_name() + "_result");
800
      t_struct noargs(program_);
801
 
802
      t_function recv_function((*f_iter)->get_returntype(),
803
                               string("recv_") + (*f_iter)->get_name(),
804
                               &noargs);
805
      // Open function
806
      f_service_ <<
807
        endl <<
808
        indent() << "def " << function_signature(&recv_function) << endl;
809
      indent_up();
810
 
811
      // TODO(mcslee): Validate message reply here, seq ids etc.
812
 
813
      f_service_ <<
814
        indent() << "result = receive_message(" << resultname << ")" << endl;
815
 
816
      // Careful, only return _result if not a void function
817
      if (!(*f_iter)->get_returntype()->is_void()) {
818
        f_service_ <<
819
          indent() << "return result.success unless result.success.nil?" << endl;
820
      }
821
 
822
      t_struct* xs = (*f_iter)->get_xceptions();
823
      const std::vector<t_field*>& xceptions = xs->get_members();
824
      vector<t_field*>::const_iterator x_iter;
825
      for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
826
        indent(f_service_) <<
827
          "raise result." << (*x_iter)->get_name() <<
828
            " unless result." << (*x_iter)->get_name() << ".nil?" << endl;
829
      }
830
 
831
      // Careful, only return _result if not a void function
832
      if ((*f_iter)->get_returntype()->is_void()) {
833
        indent(f_service_) <<
834
          "return" << endl;
835
      } else {
836
        f_service_ <<
837
          indent() << "raise ::Thrift::ApplicationException.new(::Thrift::ApplicationException::MISSING_RESULT, '" << (*f_iter)->get_name() << " failed: unknown result')" << endl;
838
      }
839
 
840
      // Close function
841
      indent_down();
842
      indent(f_service_) << "end" << endl << endl;
843
    }
844
  }
845
 
846
  indent_down();
847
  indent(f_service_) << "end" << endl << endl;
848
}
849
 
850
/**
851
 * Generates a service server definition.
852
 *
853
 * @param tservice The service to generate a server for.
854
 */
855
void t_rb_generator::generate_service_server(t_service* tservice) {
856
  // Generate the dispatch methods
857
  vector<t_function*> functions = tservice->get_functions();
858
  vector<t_function*>::iterator f_iter;
859
 
860
  string extends = "";
861
  string extends_processor = "";
862
  if (tservice->get_extends() != NULL) {
863
    extends = full_type_name(tservice->get_extends());
864
    extends_processor = " < " + extends + "::Processor ";
865
  }
866
 
867
  // Generate the header portion
868
  indent(f_service_) <<
869
    "class Processor" << extends_processor << endl;
870
  indent_up();
871
 
872
  f_service_ <<
873
    indent() << "include ::Thrift::Processor" << endl <<
874
    endl;
875
 
876
  // Generate the process subfunctions
877
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
878
    generate_process_function(tservice, *f_iter);
879
  }
880
 
881
  indent_down();
882
  indent(f_service_) << "end" << endl << endl;
883
}
884
 
885
/**
886
 * Generates a process function definition.
887
 *
888
 * @param tfunction The function to write a dispatcher for
889
 */
890
void t_rb_generator::generate_process_function(t_service* tservice,
891
                                               t_function* tfunction) {
892
  // Open function
893
  indent(f_service_) <<
894
    "def process_" << tfunction->get_name() <<
895
    "(seqid, iprot, oprot)" << endl;
896
  indent_up();
897
 
898
  string argsname = capitalize(tfunction->get_name()) + "_args";
899
  string resultname = capitalize(tfunction->get_name()) + "_result";
900
 
901
  f_service_ <<
902
    indent() << "args = read_args(iprot, " << argsname << ")" << endl;
903
 
904
  t_struct* xs = tfunction->get_xceptions();
905
  const std::vector<t_field*>& xceptions = xs->get_members();
906
  vector<t_field*>::const_iterator x_iter;
907
 
908
  // Declare result for non oneway function
909
  if (!tfunction->is_oneway()) {
910
    f_service_ <<
911
      indent() << "result = " << resultname << ".new()" << endl;
912
  }
913
 
914
  // Try block for a function with exceptions
915
  if (xceptions.size() > 0) {
916
    f_service_ <<
917
      indent() << "begin" << endl;
918
    indent_up();
919
  }
920
 
921
  // Generate the function call
922
  t_struct* arg_struct = tfunction->get_arglist();
923
  const std::vector<t_field*>& fields = arg_struct->get_members();
924
  vector<t_field*>::const_iterator f_iter;
925
 
926
  f_service_ << indent();
927
  if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
928
    f_service_ << "result.success = ";
929
  }
930
  f_service_ <<
931
    "@handler." << tfunction->get_name() << "(";
932
  bool first = true;
933
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
934
    if (first) {
935
      first = false;
936
    } else {
937
      f_service_ << ", ";
938
    }
939
    f_service_ << "args." << (*f_iter)->get_name();
940
  }
941
  f_service_ << ")" << endl;
942
 
943
  if (!tfunction->is_oneway() && xceptions.size() > 0) {
944
    indent_down();
945
    for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
946
      f_service_ <<
947
        indent() << "rescue " << full_type_name((*x_iter)->get_type()) << " => " << (*x_iter)->get_name() << endl;
948
      if (!tfunction->is_oneway()) {
949
        indent_up();
950
        f_service_ <<
951
          indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name() << endl;
952
        indent_down();
953
      }
954
    }
955
    indent(f_service_) << "end" << endl;
956
  }
957
 
958
  // Shortcut out here for oneway functions
959
  if (tfunction->is_oneway()) {
960
    f_service_ <<
961
      indent() << "return" << endl;
962
    indent_down();
963
    indent(f_service_) << "end" << endl << endl;
964
    return;
965
  }
966
 
967
  f_service_ <<
968
    indent() << "write_result(result, oprot, '" << tfunction->get_name() << "', seqid)" << endl;
969
 
970
  // Close function
971
  indent_down();
972
  indent(f_service_) << "end" << endl << endl;
973
}
974
 
975
/**
976
 * Renders a function signature of the form 'type name(args)'
977
 *
978
 * @param tfunction Function definition
979
 * @return String of rendered function definition
980
 */
981
string t_rb_generator::function_signature(t_function* tfunction,
982
                                           string prefix) {
983
  // TODO(mcslee): Nitpicky, no ',' if argument_list is empty
984
  return
985
    prefix + tfunction->get_name() +
986
    "(" +  argument_list(tfunction->get_arglist()) + ")";
987
}
988
 
989
/**
990
 * Renders a field list
991
 */
992
string t_rb_generator::argument_list(t_struct* tstruct) {
993
  string result = "";
994
 
995
  const vector<t_field*>& fields = tstruct->get_members();
996
  vector<t_field*>::const_iterator f_iter;
997
  bool first = true;
998
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
999
    if (first) {
1000
      first = false;
1001
    } else {
1002
      result += ", ";
1003
    }
1004
    result += (*f_iter)->get_name();
1005
  }
1006
  return result;
1007
}
1008
 
1009
string t_rb_generator::type_name(t_type* ttype) {
1010
  string prefix = "";
1011
 
1012
  string name = ttype->get_name();
1013
  if (ttype->is_struct() || ttype->is_xception() || ttype->is_enum()) {
1014
    name = capitalize(ttype->get_name());
1015
  }
1016
 
1017
  return prefix + name;
1018
}
1019
 
1020
string t_rb_generator::full_type_name(t_type* ttype) {
1021
  string prefix = "";
1022
  vector<std::string> modules = ruby_modules(ttype->get_program());
1023
  for (vector<std::string>::iterator m_iter = modules.begin();
1024
       m_iter != modules.end(); ++m_iter) {
1025
    prefix += *m_iter + "::";
1026
  }
1027
  return prefix + type_name(ttype);
1028
}
1029
 
1030
/**
1031
 * Converts the parse type to a Ruby tyoe
1032
 */
1033
string t_rb_generator::type_to_enum(t_type* type) {
1034
  type = get_true_type(type);
1035
 
1036
  if (type->is_base_type()) {
1037
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1038
    switch (tbase) {
1039
    case t_base_type::TYPE_VOID:
1040
      throw "NO T_VOID CONSTRUCT";
1041
    case t_base_type::TYPE_STRING:
1042
      return "::Thrift::Types::STRING";
1043
    case t_base_type::TYPE_BOOL:
1044
      return "::Thrift::Types::BOOL";
1045
    case t_base_type::TYPE_BYTE:
1046
      return "::Thrift::Types::BYTE";
1047
    case t_base_type::TYPE_I16:
1048
      return "::Thrift::Types::I16";
1049
    case t_base_type::TYPE_I32:
1050
      return "::Thrift::Types::I32";
1051
    case t_base_type::TYPE_I64:
1052
      return "::Thrift::Types::I64";
1053
    case t_base_type::TYPE_DOUBLE:
1054
      return "::Thrift::Types::DOUBLE";
1055
    }
1056
  } else if (type->is_enum()) {
1057
    return "::Thrift::Types::I32";
1058
  } else if (type->is_struct() || type->is_xception()) {
1059
    return "::Thrift::Types::STRUCT";
1060
  } else if (type->is_map()) {
1061
    return "::Thrift::Types::MAP";
1062
  } else if (type->is_set()) {
1063
    return "::Thrift::Types::SET";
1064
  } else if (type->is_list()) {
1065
    return "::Thrift::Types::LIST";
1066
  }
1067
 
1068
  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
1069
}
1070
 
1071
 
1072
void t_rb_generator::generate_rdoc(std::ofstream& out, t_doc* tdoc) {
1073
  if (tdoc->has_doc()) {
1074
    generate_docstring_comment(out,
1075
      "", "# ", tdoc->get_doc(), "");
1076
  }
1077
}
1078
 
1079
void t_rb_generator::generate_rb_struct_required_validator(std::ofstream& out, 
1080
                                                           t_struct* tstruct) {
1081
  indent(out) << "def validate" << endl;
1082
  indent_up();
1083
 
1084
  const vector<t_field*>& fields = tstruct->get_members();
1085
  vector<t_field*>::const_iterator f_iter;
1086
 
1087
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1088
    t_field* field = (*f_iter);
1089
    if (field->get_req() == t_field::T_REQUIRED) {
1090
      indent(out) << "raise ::Thrift::ProtocolException.new(::Thrift::ProtocolException::UNKNOWN, 'Required field " << field->get_name() << " is unset!')";
1091
      if (field->get_type()->is_bool()) {
1092
        out << " if @" << field->get_name() << ".nil?";
1093
      } else {
1094
        out << " unless @" << field->get_name();
1095
      }
1096
      out << endl;
1097
    }
1098
  }
1099
 
1100
  // if field is an enum, check that its value is valid
1101
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1102
    t_field* field = (*f_iter);
1103
 
1104
    if (field->get_type()->is_enum()){      
1105
      indent(out) << "unless @" << field->get_name() << ".nil? || " << full_type_name(field->get_type()) << "::VALID_VALUES.include?(@" << field->get_name() << ")" << endl;
1106
      indent_up();
1107
      indent(out) << "raise ::Thrift::ProtocolException.new(::Thrift::ProtocolException::UNKNOWN, 'Invalid value of field " << field->get_name() << "!')" << endl;  
1108
      indent_down();
1109
      indent(out) << "end" << endl;
1110
    }
1111
  }  
1112
 
1113
  indent_down();
1114
  indent(out) << "end" << endl << endl;
1115
 
1116
}
1117
 
1118
THRIFT_REGISTER_GENERATOR(rb, "Ruby", "");