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
 
20
#include <string>
21
#include <fstream>
22
#include <iostream>
23
#include <vector>
24
 
25
#include <stdlib.h>
26
#include <sys/stat.h>
27
#include <sys/types.h>
28
#include <sstream>
29
#include "t_oop_generator.h"
30
#include "platform.h"
31
using namespace std;
32
 
33
 
34
/**
35
 * OCaml code generator.
36
 *
37
 */
38
class t_ocaml_generator : public t_oop_generator {
39
 public:
40
  t_ocaml_generator(
41
      t_program* program,
42
      const std::map<std::string, std::string>& parsed_options,
43
      const std::string& option_string)
44
    : t_oop_generator(program)
45
  {
46
    out_dir_base_ = "gen-ocaml";
47
  }
48
 
49
  /**
50
   * Init and close methods
51
   */
52
 
53
  void init_generator();
54
  void close_generator();
55
 
56
  /**
57
   * Program-level generation functions
58
   */
59
  void generate_program  ();
60
  void generate_typedef  (t_typedef*  ttypedef);
61
  void generate_enum     (t_enum*     tenum);
62
  void generate_const    (t_const*    tconst);
63
  void generate_struct   (t_struct*   tstruct);
64
  void generate_xception (t_struct*   txception);
65
  void generate_service  (t_service*  tservice);
66
 
67
  std::string render_const_value(t_type* type, t_const_value* value);
68
 
69
  /**
70
   * Struct generation code
71
   */
72
 
73
  void generate_ocaml_struct(t_struct* tstruct, bool is_exception);
74
  void generate_ocaml_struct_definition(std::ofstream& out, t_struct* tstruct, bool is_xception=false);
75
  void generate_ocaml_struct_sig(std::ofstream& out, t_struct* tstruct, bool is_exception);
76
  void generate_ocaml_struct_reader(std::ofstream& out, t_struct* tstruct);
77
  void generate_ocaml_struct_writer(std::ofstream& out, t_struct* tstruct);
78
  void generate_ocaml_function_helpers(t_function* tfunction);
79
 
80
  /**
81
   * Service-level generation functions
82
   */
83
 
84
  void generate_service_helpers   (t_service*  tservice);
85
  void generate_service_interface (t_service* tservice);
86
  void generate_service_client    (t_service* tservice);
87
  void generate_service_server    (t_service* tservice);
88
  void generate_process_function  (t_service* tservice, t_function* tfunction);
89
 
90
  /**
91
   * Serialization constructs
92
   */
93
 
94
  void generate_deserialize_field        (std::ofstream &out,
95
                                          t_field*    tfield,
96
                                          std::string prefix);
97
 
98
  void generate_deserialize_struct       (std::ofstream &out,
99
                                          t_struct*   tstruct);
100
 
101
  void generate_deserialize_container    (std::ofstream &out,
102
                                          t_type*     ttype);
103
 
104
  void generate_deserialize_set_element  (std::ofstream &out,
105
                                          t_set*      tset);
106
 
107
 
108
  void generate_deserialize_list_element (std::ofstream &out,
109
                                          t_list*     tlist,
110
                                          std::string prefix="");
111
  void generate_deserialize_type          (std::ofstream &out,
112
                                           t_type* type);
113
 
114
  void generate_serialize_field          (std::ofstream &out,
115
                                          t_field*    tfield,
116
                                          std::string name= "");
117
 
118
  void generate_serialize_struct         (std::ofstream &out,
119
                                          t_struct*   tstruct,
120
                                          std::string prefix="");
121
 
122
  void generate_serialize_container      (std::ofstream &out,
123
                                          t_type*     ttype,
124
                                          std::string prefix="");
125
 
126
  void generate_serialize_map_element    (std::ofstream &out,
127
                                          t_map*      tmap,
128
                                          std::string kiter,
129
                                          std::string viter);
130
 
131
  void generate_serialize_set_element    (std::ofstream &out,
132
                                          t_set*      tmap,
133
                                          std::string iter);
134
 
135
  void generate_serialize_list_element   (std::ofstream &out,
136
                                          t_list*     tlist,
137
                                          std::string iter);
138
 
139
  /**
140
   * Helper rendering functions
141
   */
142
 
143
  std::string ocaml_autogen_comment();
144
  std::string ocaml_imports();
145
  std::string type_name(t_type* ttype);
146
  std::string function_signature(t_function* tfunction, std::string prefix="");
147
  std::string function_type(t_function* tfunc, bool method=false, bool options = false);
148
  std::string argument_list(t_struct* tstruct);
149
  std::string type_to_enum(t_type* ttype);
150
  std::string render_ocaml_type(t_type* type);
151
 
152
 
153
 private:
154
 
155
  /**
156
   * File streams
157
   */
158
 
159
  std::ofstream f_types_;
160
  std::ofstream f_consts_;
161
  std::ofstream f_service_;
162
 
163
  std::ofstream f_types_i_;
164
  std::ofstream f_service_i_;
165
 
166
};
167
 
168
 
169
/*
170
 * This is necessary because we want typedefs to appear later,
171
 * after all the types have been declared.
172
 */
173
void t_ocaml_generator::generate_program() {
174
  // Initialize the generator
175
  init_generator();
176
 
177
  // Generate enums
178
  vector<t_enum*> enums = program_->get_enums();
179
  vector<t_enum*>::iterator en_iter;
180
  for (en_iter = enums.begin(); en_iter != enums.end(); ++en_iter) {
181
    generate_enum(*en_iter);
182
  }
183
 
184
  // Generate structs
185
  vector<t_struct*> structs = program_->get_structs();
186
  vector<t_struct*>::iterator st_iter;
187
  for (st_iter = structs.begin(); st_iter != structs.end(); ++st_iter) {
188
    generate_struct(*st_iter);
189
  }
190
 
191
  // Generate xceptions
192
  vector<t_struct*> xceptions = program_->get_xceptions();
193
  vector<t_struct*>::iterator x_iter;
194
  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
195
    generate_xception(*x_iter);
196
  }
197
 
198
  // Generate typedefs
199
  vector<t_typedef*> typedefs = program_->get_typedefs();
200
  vector<t_typedef*>::iterator td_iter;
201
  for (td_iter = typedefs.begin(); td_iter != typedefs.end(); ++td_iter) {
202
    generate_typedef(*td_iter);
203
  }
204
 
205
  // Generate services
206
  vector<t_service*> services = program_->get_services();
207
  vector<t_service*>::iterator sv_iter;
208
  for (sv_iter = services.begin(); sv_iter != services.end(); ++sv_iter) {
209
    service_name_ = get_service_name(*sv_iter);
210
    generate_service(*sv_iter);
211
  }
212
 
213
  // Generate constants
214
  vector<t_const*> consts = program_->get_consts();
215
  generate_consts(consts);
216
 
217
  // Close the generator
218
  close_generator();
219
}
220
 
221
 
222
/**
223
 * Prepares for file generation by opening up the necessary file output
224
 * streams.
225
 *
226
 * @param tprogram The program to generate
227
 */
228
void t_ocaml_generator::init_generator() {
229
  // Make output directory
230
  MKDIR(get_out_dir().c_str());
231
 
232
  // Make output file
233
  string f_types_name = get_out_dir()+program_name_+"_types.ml";
234
  f_types_.open(f_types_name.c_str());
235
  string f_types_i_name = get_out_dir()+program_name_+"_types.mli";
236
  f_types_i_.open(f_types_i_name.c_str());
237
 
238
  string f_consts_name = get_out_dir()+program_name_+"_consts.ml";
239
  f_consts_.open(f_consts_name.c_str());
240
 
241
  // Print header
242
  f_types_ <<
243
    ocaml_autogen_comment() << endl <<
244
    ocaml_imports() << endl;
245
  f_types_i_ <<
246
    ocaml_autogen_comment() << endl <<
247
    ocaml_imports() << endl;
248
  f_consts_ <<
249
    ocaml_autogen_comment() << endl <<
250
    ocaml_imports() << endl <<
251
    "open " << capitalize(program_name_)<<"_types"<< endl;
252
}
253
 
254
 
255
/**
256
 * Autogen'd comment
257
 */
258
string t_ocaml_generator::ocaml_autogen_comment() {
259
  return
260
    std::string("(*\n") +
261
    " Autogenerated by Thrift\n" +
262
    "\n" +
263
    " DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING\n" +
264
    "*)\n";
265
}
266
 
267
/**
268
 * Prints standard thrift imports
269
 */
270
string t_ocaml_generator::ocaml_imports() {
271
  return "open Thrift";
272
}
273
 
274
/**
275
 * Closes the type files
276
 */
277
void t_ocaml_generator::close_generator() {
278
  // Close types file
279
  f_types_.close();
280
}
281
 
282
/**
283
 * Generates a typedef. Ez.
284
 *
285
 * @param ttypedef The type definition
286
 */
287
void t_ocaml_generator::generate_typedef(t_typedef* ttypedef) {
288
  f_types_ <<
289
    indent() << "type "<< decapitalize(ttypedef->get_symbolic()) << " = " << render_ocaml_type(ttypedef->get_type()) << endl << endl;
290
  f_types_i_ <<
291
    indent() << "type "<< decapitalize(ttypedef->get_symbolic()) << " = " << render_ocaml_type(ttypedef->get_type()) << endl << endl;
292
}
293
 
294
/**
295
 * Generates code for an enumerated type.
296
 * the values.
297
 *
298
 * @param tenum The enumeration
299
 */
300
void t_ocaml_generator::generate_enum(t_enum* tenum) {
301
  indent(f_types_) << "module " << capitalize(tenum->get_name()) << " = " << endl << "struct" << endl;
302
  indent(f_types_i_) << "module " << capitalize(tenum->get_name()) << " : " << endl << "sig" << endl;
303
  indent_up();
304
  indent(f_types_) << "type t = " << endl;
305
  indent(f_types_i_) << "type t = " << endl;
306
  indent_up();
307
  vector<t_enum_value*> constants = tenum->get_constants();
308
  vector<t_enum_value*>::iterator c_iter;
309
  int value = -1;
310
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
311
    string name = capitalize((*c_iter)->get_name());
312
    indent(f_types_) << "| " << name << endl;
313
    indent(f_types_i_) << "| " << name << endl;
314
  }
315
  indent_down();
316
 
317
  indent(f_types_) << "let to_i = function" << endl;
318
  indent(f_types_i_) << "val to_i : t -> int" << endl;
319
  indent_up();
320
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
321
    if ((*c_iter)->has_value()) {
322
      value = (*c_iter)->get_value();
323
    } else {
324
      ++value;
325
    }
326
    string name = capitalize((*c_iter)->get_name());
327
 
328
    f_types_ <<
329
      indent() << "| " << name << " -> " << value << endl;
330
  }
331
  indent_down();
332
 
333
  indent(f_types_) << "let of_i = function" << endl;
334
  indent(f_types_i_) << "val of_i : int -> t" << endl;
335
  indent_up();
336
  for(c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
337
    if ((*c_iter)->has_value()) {
338
      value = (*c_iter)->get_value();
339
    } else {
340
      ++value;
341
    }
342
    string name = capitalize((*c_iter)->get_name());
343
 
344
    f_types_ <<
345
      indent() << "| " << value << " -> " << name << endl;
346
  }
347
  indent(f_types_) << "| _ -> raise Thrift_error" << endl;
348
  indent_down();
349
  indent_down();
350
  indent(f_types_) << "end" << endl;
351
  indent(f_types_i_) << "end" << endl;
352
}
353
 
354
/**
355
 * Generate a constant value
356
 */
357
void t_ocaml_generator::generate_const(t_const* tconst) {
358
  t_type* type = tconst->get_type();
359
  string name = decapitalize(tconst->get_name());
360
  t_const_value* value = tconst->get_value();
361
 
362
  indent(f_consts_) << "let " << name << " = " << render_const_value(type, value) << endl << endl;
363
}
364
 
365
/**
366
 * Prints the value of a constant with the given type. Note that type checking
367
 * is NOT performed in this function as it is always run beforehand using the
368
 * validate_types method in main.cc
369
 */
370
string t_ocaml_generator::render_const_value(t_type* type, t_const_value* value) {
371
  type = get_true_type(type);
372
  std::ostringstream out;
373
  if (type->is_base_type()) {
374
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
375
    switch (tbase) {
376
    case t_base_type::TYPE_STRING:
377
      out << '"' << get_escaped_string(value) << '"';
378
      break;
379
    case t_base_type::TYPE_BOOL:
380
      out << (value->get_integer() > 0 ? "true" : "false");
381
      break;
382
    case t_base_type::TYPE_BYTE:
383
    case t_base_type::TYPE_I16:
384
    case t_base_type::TYPE_I32:
385
      out << value->get_integer();
386
      break;
387
    case t_base_type::TYPE_I64:
388
      out << value->get_integer() << "L";
389
      break;
390
    case t_base_type::TYPE_DOUBLE:
391
      if (value->get_type() == t_const_value::CV_INTEGER) {
392
        out << value->get_integer();
393
      } else {
394
        out << value->get_double();
395
      }
396
      break;
397
    default:
398
      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
399
    }
400
  } else if (type->is_enum()) {
401
    t_enum* tenum = (t_enum*)type;
402
    vector<t_enum_value*> constants = tenum->get_constants();
403
    vector<t_enum_value*>::iterator c_iter;
404
    int val = -1;
405
    for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
406
      if ((*c_iter)->has_value()) {
407
        val = (*c_iter)->get_value();
408
      } else {
409
        ++val;
410
      }
411
      if(val == value->get_integer()){
412
        indent(out) << capitalize(tenum->get_name()) << "." << capitalize((*c_iter)->get_name());
413
        break;
414
      }
415
    }
416
  } else if (type->is_struct() || type->is_xception()) {
417
    string cname = type_name(type);
418
    string ct = tmp("_c");
419
    out << endl;
420
    indent_up();
421
    indent(out) << "(let " << ct << " = new " << cname << " in" << endl;
422
    indent_up();
423
    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
424
    vector<t_field*>::const_iterator f_iter;
425
    const map<t_const_value*, t_const_value*>& val = value->get_map();
426
    map<t_const_value*, t_const_value*>::const_iterator v_iter;
427
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
428
      t_type* field_type = NULL;
429
      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
430
        if ((*f_iter)->get_name() == v_iter->first->get_string()) {
431
          field_type = (*f_iter)->get_type();
432
        }
433
      }
434
      if (field_type == NULL) {
435
        throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
436
      }
437
      string fname = v_iter->first->get_string();
438
      out << indent();
439
      out << ct <<"#set_" << fname << " ";
440
      out << render_const_value(field_type, v_iter->second);
441
      out << ";" << endl;
442
    }
443
    indent(out) << ct << ")";
444
    indent_down();
445
    indent_down();
446
  } else if (type->is_map()) {
447
    t_type* ktype = ((t_map*)type)->get_key_type();
448
    t_type* vtype = ((t_map*)type)->get_val_type();
449
    const map<t_const_value*, t_const_value*>& val = value->get_map();
450
    map<t_const_value*, t_const_value*>::const_iterator v_iter;
451
    string hm = tmp("_hm");
452
    out << endl;
453
    indent_up();
454
    indent(out) << "(let " << hm << " = Hashtbl.create " << val.size() << " in" << endl;
455
    indent_up();
456
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
457
      string key = render_const_value(ktype, v_iter->first);
458
      string val = render_const_value(vtype, v_iter->second);
459
      indent(out) << "Hashtbl.add " << hm << " " << key << " " << val << ";" << endl;
460
    }
461
    indent(out) << hm << ")";
462
    indent_down();
463
    indent_down();
464
  } else if (type->is_list()) {
465
    t_type* etype;
466
    etype = ((t_list*)type)->get_elem_type();
467
    out << "[" << endl;
468
    indent_up();
469
    const vector<t_const_value*>& val = value->get_list();
470
    vector<t_const_value*>::const_iterator v_iter;
471
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
472
      out << indent();
473
      out << render_const_value(etype, *v_iter);
474
      out << ";" << endl;
475
    }
476
    indent_down();
477
    indent(out) << "]";
478
  } else if (type->is_set()) {
479
    t_type* etype = ((t_set*)type)->get_elem_type();
480
    const vector<t_const_value*>& val = value->get_list();
481
    vector<t_const_value*>::const_iterator v_iter;
482
    string hm = tmp("_hm");
483
    indent(out) << "(let " << hm << " = Hashtbl.create " << val.size() << " in" << endl;
484
    indent_up();
485
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
486
      string val = render_const_value(etype, *v_iter);
487
      indent(out) << "Hashtbl.add " << hm << " " << val << " true;" << endl;
488
    }
489
    indent(out) << hm << ")" << endl;
490
    indent_down();
491
    out << endl;
492
  } else {
493
    throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
494
  }
495
  return out.str();
496
}
497
 
498
/**
499
 * Generates a "struct"
500
 */
501
void t_ocaml_generator::generate_struct(t_struct* tstruct) {
502
  generate_ocaml_struct(tstruct, false);
503
}
504
 
505
/**
506
 * Generates a struct definition for a thrift exception. Basically the same
507
 * as a struct, but also has an exception declaration.
508
 *
509
 * @param txception The struct definition
510
 */
511
void t_ocaml_generator::generate_xception(t_struct* txception) {
512
  generate_ocaml_struct(txception, true);
513
}
514
 
515
/**
516
 * Generates an OCaml struct
517
 */
518
void t_ocaml_generator::generate_ocaml_struct(t_struct* tstruct,
519
                                              bool is_exception) {
520
  generate_ocaml_struct_definition(f_types_, tstruct, is_exception);
521
  generate_ocaml_struct_sig(f_types_i_,tstruct,is_exception);
522
}
523
 
524
/**
525
 * Generates a struct definition for a thrift data type.
526
 *
527
 * @param tstruct The struct definition
528
 */
529
void t_ocaml_generator::generate_ocaml_struct_definition(ofstream& out,
530
                                                         t_struct* tstruct,
531
                                                         bool is_exception) {
532
  const vector<t_field*>& members = tstruct->get_members();
533
  vector<t_field*>::const_iterator m_iter;
534
  string tname = type_name(tstruct);
535
  indent(out) << "class " << tname << " =" << endl;
536
  indent(out) << "object (self)" << endl;
537
 
538
  indent_up();
539
 
540
  string x = tmp("_x");
541
  if (members.size() > 0) {
542
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
543
      string mname = decapitalize((*m_iter)->get_name());
544
      indent(out) << "val mutable _" << mname << " : " << render_ocaml_type((*m_iter)->get_type()) << " option = None" << endl;
545
      indent(out) << "method get_" << mname << " = _" << mname << endl;
546
      indent(out) << "method grab_" << mname << " = match _"<<mname<<" with None->raise (Field_empty \""<<tname<<"."<<mname<<"\") | Some " << x <<" -> " << x << endl;
547
      indent(out) << "method set_" << mname << " " << x << " = _" << mname << " <- Some " << x << endl;
548
    }
549
  }
550
  generate_ocaml_struct_writer(out, tstruct);
551
  indent_down();
552
  indent(out) << "end" << endl;
553
 
554
  if(is_exception){
555
    indent(out) << "exception " << capitalize(tname) <<" of " << tname << endl;
556
  }
557
 
558
  generate_ocaml_struct_reader(out, tstruct);
559
}
560
 
561
/**
562
 * Generates a struct definition for a thrift data type.
563
 *
564
 * @param tstruct The struct definition
565
 */
566
void t_ocaml_generator::generate_ocaml_struct_sig(ofstream& out,
567
                                                  t_struct* tstruct,
568
                                                  bool is_exception) {
569
  const vector<t_field*>& members = tstruct->get_members();
570
  vector<t_field*>::const_iterator m_iter;
571
  string tname = type_name(tstruct);
572
  indent(out) << "class " << tname << " :" << endl;
573
  indent(out) << "object" << endl;
574
 
575
  indent_up();
576
 
577
  string x = tmp("_x");
578
  if (members.size() > 0) {
579
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
580
      string mname = decapitalize((*m_iter)->get_name());
581
      string type = render_ocaml_type((*m_iter)->get_type());
582
      indent(out) << "method get_" << mname << " : " << type << " option" << endl;
583
      indent(out) << "method grab_" << mname << " : " << type << endl;
584
      indent(out) << "method set_" << mname << " : " << type << " -> unit" << endl;
585
    }
586
  }
587
  indent(out) << "method write : Protocol.t -> unit" << endl;
588
  indent_down();
589
  indent(out) << "end" << endl;
590
 
591
  if(is_exception){
592
    indent(out) << "exception " << capitalize(tname) <<" of " << tname << endl;
593
  }
594
 
595
  indent(out) << "val read_" << tname << " : Protocol.t -> " << tname << endl;
596
}
597
 
598
/**
599
 * Generates the read method for a struct
600
 */
601
void t_ocaml_generator::generate_ocaml_struct_reader(ofstream& out, t_struct* tstruct) {
602
  const vector<t_field*>& fields = tstruct->get_members();
603
  vector<t_field*>::const_iterator f_iter;
604
  string sname = type_name(tstruct);
605
  string str = tmp("_str");
606
  string t = tmp("_t");
607
  string id = tmp("_id");
608
  indent(out) <<
609
    "let rec read_" << sname << " (iprot : Protocol.t) =" << endl;
610
  indent_up();
611
  indent(out) << "let " << str << " = new " << sname << " in" << endl;
612
  indent_up();
613
  indent(out) <<
614
    "ignore(iprot#readStructBegin);" << endl;
615
 
616
  // Loop over reading in fields
617
  indent(out) <<
618
    "(try while true do" << endl;
619
  indent_up();
620
  indent_up();
621
 
622
  // Read beginning field marker
623
  indent(out) <<
624
    "let (_," << t <<","<<id<<") = iprot#readFieldBegin in" << endl;
625
 
626
  // Check for field STOP marker and break
627
  indent(out) <<
628
    "if " << t <<" = Protocol.T_STOP then" << endl;
629
  indent_up();
630
  indent(out) <<
631
      "raise Break" << endl;
632
    indent_down();
633
    indent(out) << "else ();" << endl;
634
 
635
    indent(out) << "(match " << id<<" with " << endl;
636
    indent_up();
637
    // Generate deserialization code for known cases
638
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
639
      indent(out) << "| " << (*f_iter)->get_key() << " -> (";
640
      out << "if " << t <<" = " << type_to_enum((*f_iter)->get_type()) << " then" << endl;
641
      indent_up();
642
      indent_up();
643
      generate_deserialize_field(out, *f_iter,str);
644
      indent_down();
645
      out <<
646
        indent() << "else" << endl <<
647
        indent() << "  iprot#skip "<< t << ")" << endl;
648
      indent_down();
649
    }
650
 
651
    // In the default case we skip the field
652
    out <<
653
      indent() << "| _ -> " << "iprot#skip "<<t<<");" << endl;
654
    indent_down();
655
    // Read field end marker
656
    indent(out) << "iprot#readFieldEnd;" << endl;
657
    indent_down();
658
    indent(out) << "done; ()" << endl;
659
    indent_down();
660
    indent(out) << "with Break -> ());" << endl;
661
 
662
    indent(out) <<
663
      "iprot#readStructEnd;" << endl;
664
 
665
    indent(out) << str << endl << endl;
666
    indent_down();
667
    indent_down();
668
}
669
 
670
void t_ocaml_generator::generate_ocaml_struct_writer(ofstream& out,
671
                                               t_struct* tstruct) {
672
  string name = tstruct->get_name();
673
  const vector<t_field*>& fields = tstruct->get_sorted_members();
674
  vector<t_field*>::const_iterator f_iter;
675
  string str = tmp("_str");
676
  string f = tmp("_f");
677
 
678
  indent(out) <<
679
    "method write (oprot : Protocol.t) =" << endl;
680
  indent_up();
681
  indent(out) <<
682
    "oprot#writeStructBegin \""<<name<<"\";" << endl;
683
 
684
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
685
    // Write field header
686
    string mname = "_"+decapitalize((*f_iter)->get_name());
687
    indent(out) <<
688
      "(match " << mname << " with None -> () | Some _v -> " << endl;
689
    indent_up();
690
    indent(out) << "oprot#writeFieldBegin(\""<< (*f_iter)->get_name()<<"\","
691
                <<type_to_enum((*f_iter)->get_type())<<","
692
                <<(*f_iter)->get_key()<<");" << endl;
693
 
694
    // Write field contents
695
    generate_serialize_field(out, *f_iter, "_v");
696
 
697
    // Write field closer
698
    indent(out) << "oprot#writeFieldEnd" << endl;
699
 
700
    indent_down();
701
    indent(out) << ");" << endl;
702
  }
703
 
704
  // Write the struct map
705
  out <<
706
    indent() << "oprot#writeFieldStop;" << endl <<
707
    indent() << "oprot#writeStructEnd" << endl;
708
 
709
  indent_down();
710
}
711
 
712
/**
713
 * Generates a thrift service.
714
 *
715
 * @param tservice The service definition
716
 */
717
void t_ocaml_generator::generate_service(t_service* tservice) {
718
  string f_service_name = get_out_dir()+capitalize(service_name_)+".ml";
719
  f_service_.open(f_service_name.c_str());
720
  string f_service_i_name = get_out_dir()+capitalize(service_name_)+".mli";
721
  f_service_i_.open(f_service_i_name.c_str());
722
 
723
  f_service_ <<
724
    ocaml_autogen_comment() << endl <<
725
    ocaml_imports() << endl;
726
  f_service_i_ <<
727
    ocaml_autogen_comment() << endl <<
728
    ocaml_imports() << endl;
729
 
730
  /* if (tservice->get_extends() != NULL) {
731
    f_service_ <<
732
      "open " << capitalize(tservice->get_extends()->get_name()) << endl;
733
    f_service_i_ <<
734
      "open " << capitalize(tservice->get_extends()->get_name()) << endl;
735
  }
736
  */
737
  f_service_ <<
738
     "open " << capitalize(program_name_) << "_types" << endl <<
739
    endl;
740
 
741
  f_service_i_ <<
742
     "open " << capitalize(program_name_) << "_types" << endl <<
743
    endl;
744
 
745
  // Generate the three main parts of the service
746
  generate_service_helpers(tservice);
747
  generate_service_interface(tservice);
748
  generate_service_client(tservice);
749
  generate_service_server(tservice);
750
 
751
 
752
  // Close service file
753
  f_service_.close();
754
  f_service_i_.close();
755
}
756
 
757
/**
758
 * Generates helper functions for a service.
759
 *
760
 * @param tservice The service to generate a header definition for
761
 */
762
void t_ocaml_generator::generate_service_helpers(t_service* tservice) {
763
  vector<t_function*> functions = tservice->get_functions();
764
  vector<t_function*>::iterator f_iter;
765
 
766
  indent(f_service_) <<
767
    "(* HELPER FUNCTIONS AND STRUCTURES *)" << endl << endl;
768
 
769
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
770
    t_struct* ts = (*f_iter)->get_arglist();
771
    generate_ocaml_struct_definition(f_service_, ts, false);
772
    generate_ocaml_function_helpers(*f_iter);
773
  }
774
}
775
 
776
/**
777
 * Generates a struct and helpers for a function.
778
 *
779
 * @param tfunction The function
780
 */
781
void t_ocaml_generator::generate_ocaml_function_helpers(t_function* tfunction) {
782
  t_struct result(program_, decapitalize(tfunction->get_name()) + "_result");
783
  t_field success(tfunction->get_returntype(), "success", 0);
784
  if (!tfunction->get_returntype()->is_void()) {
785
    result.append(&success);
786
  }
787
 
788
  t_struct* xs = tfunction->get_xceptions();
789
  const vector<t_field*>& fields = xs->get_members();
790
  vector<t_field*>::const_iterator f_iter;
791
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
792
    result.append(*f_iter);
793
  }
794
  generate_ocaml_struct_definition(f_service_, &result, false);
795
}
796
 
797
/**
798
 * Generates a service interface definition.
799
 *
800
 * @param tservice The service to generate a header definition for
801
 */
802
void t_ocaml_generator::generate_service_interface(t_service* tservice) {
803
  f_service_ <<
804
    indent() << "class virtual iface =" << endl << "object (self)" << endl;
805
  f_service_i_ <<
806
    indent() << "class virtual iface :" << endl << "object" << endl;
807
 
808
  indent_up();
809
 
810
  if (tservice->get_extends() != NULL) {
811
    string extends = type_name(tservice->get_extends());
812
    indent(f_service_) << "inherit " << extends << ".iface" << endl;
813
    indent(f_service_i_) << "inherit " << extends << ".iface" << endl;
814
  }
815
 
816
  vector<t_function*> functions = tservice->get_functions();
817
  vector<t_function*>::iterator f_iter;
818
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
819
    string ft = function_type(*f_iter,true,true);
820
    f_service_ <<
821
      indent() << "method virtual " << decapitalize((*f_iter)->get_name()) << " : " << ft  << endl;
822
    f_service_i_ <<
823
      indent() << "method virtual " << decapitalize((*f_iter)->get_name()) << " : " << ft << endl;
824
  }
825
  indent_down();
826
  indent(f_service_) << "end" << endl << endl;
827
  indent(f_service_i_) << "end" << endl << endl;
828
}
829
 
830
/**
831
 * Generates a service client definition. Note that in OCaml, the client doesn't implement iface. This is because
832
 * The client does not (and should not have to) deal with arguments being None.
833
 *
834
 * @param tservice The service to generate a server for.
835
 */
836
void t_ocaml_generator::generate_service_client(t_service* tservice) {
837
  string extends = "";
838
  indent(f_service_) <<
839
    "class client (iprot : Protocol.t) (oprot : Protocol.t) =" << endl << "object (self)" << endl;
840
  indent(f_service_i_) <<
841
    "class client : Protocol.t -> Protocol.t -> " << endl << "object" << endl;
842
  indent_up();
843
 
844
 
845
  if (tservice->get_extends() != NULL) {
846
    extends = type_name(tservice->get_extends());
847
    indent(f_service_) << "inherit " << extends << ".client iprot oprot as super" << endl;
848
    indent(f_service_i_) << "inherit " << extends << ".client" << endl;
849
  }
850
  indent(f_service_) << "val mutable seqid = 0" << endl;
851
 
852
 
853
  // Generate client method implementations
854
  vector<t_function*> functions = tservice->get_functions();
855
  vector<t_function*>::const_iterator f_iter;
856
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
857
    t_struct* arg_struct = (*f_iter)->get_arglist();
858
    const vector<t_field*>& fields = arg_struct->get_members();
859
    vector<t_field*>::const_iterator fld_iter;
860
    string funname = (*f_iter)->get_name();
861
 
862
    // Open function
863
    indent(f_service_) <<
864
      "method " << function_signature(*f_iter) << " = " << endl;
865
    indent(f_service_i_) <<
866
      "method " << decapitalize((*f_iter)->get_name()) << " : " << function_type(*f_iter,true,false) << endl;
867
    indent_up();
868
    indent(f_service_) <<
869
      "self#send_" << funname;
870
 
871
 
872
    for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
873
      f_service_ << " " << decapitalize((*fld_iter)->get_name());
874
    }
875
    f_service_ << ";" << endl;
876
 
877
    if (!(*f_iter)->is_oneway()) {
878
      f_service_ << indent();
879
      f_service_ <<
880
        "self#recv_" << funname << endl;
881
    }
882
    indent_down();
883
 
884
    indent(f_service_) <<
885
      "method private send_" << function_signature(*f_iter) << " = " << endl;
886
    indent_up();
887
 
888
    std::string argsname = decapitalize((*f_iter)->get_name() + "_args");
889
 
890
    // Serialize the request header
891
    f_service_ <<
892
      indent() << "oprot#writeMessageBegin (\"" << (*f_iter)->get_name() << "\", Protocol.CALL, seqid);" << endl;
893
 
894
    f_service_ <<
895
      indent() << "let args = new " << argsname << " in" << endl;
896
    indent_up();
897
 
898
    for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
899
      f_service_ <<
900
        indent() << "args#set_" << (*fld_iter)->get_name() << " " << (*fld_iter)->get_name() << ";" << endl;
901
    }
902
 
903
    // Write to the stream
904
    f_service_ <<
905
      indent() << "args#write oprot;" << endl <<
906
      indent() << "oprot#writeMessageEnd;" << endl <<
907
      indent() << "oprot#getTransport#flush" << endl;
908
 
909
    indent_down();
910
    indent_down();
911
 
912
    if (!(*f_iter)->is_oneway()) {
913
      std::string resultname = decapitalize((*f_iter)->get_name() + "_result");
914
      t_struct noargs(program_);
915
 
916
      t_function recv_function((*f_iter)->get_returntype(),
917
                               string("recv_") + (*f_iter)->get_name(),
918
                               &noargs);
919
      // Open function
920
      f_service_ <<
921
        indent() << "method private " << function_signature(&recv_function) << " =" << endl;
922
      indent_up();
923
 
924
      // TODO(mcslee): Validate message reply here, seq ids etc.
925
 
926
      f_service_ <<
927
        indent() << "let (fname, mtype, rseqid) = iprot#readMessageBegin in" << endl;
928
      indent_up();
929
      f_service_ <<
930
        indent() << "(if mtype = Protocol.EXCEPTION then" << endl <<
931
        indent() << "  let x = Application_Exn.read iprot in" << endl;
932
      indent_up();
933
      f_service_ <<
934
        indent() << "  (iprot#readMessageEnd;" <<
935
        indent() << "   raise (Application_Exn.E x))" << endl;
936
      indent_down();
937
      f_service_ <<
938
        indent() << "else ());" << endl;
939
      string res = "_";
940
 
941
      t_struct* xs = (*f_iter)->get_xceptions();
942
      const std::vector<t_field*>& xceptions = xs->get_members();
943
 
944
      if (!(*f_iter)->get_returntype()->is_void() || xceptions.size() > 0) {
945
        res = "result";
946
      }
947
      f_service_ <<
948
        indent() << "let "<<res<<" = read_" << resultname << " iprot in" << endl;
949
      indent_up();
950
      f_service_ <<
951
        indent() << "iprot#readMessageEnd;" << endl;
952
 
953
      // Careful, only return _result if not a void function
954
      if (!(*f_iter)->get_returntype()->is_void()) {
955
        f_service_ <<
956
          indent() << "match result#get_success with Some v -> v | None -> (" << endl;
957
        indent_up();
958
      }
959
 
960
 
961
      vector<t_field*>::const_iterator x_iter;
962
      for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
963
        f_service_ <<
964
          indent() << "(match result#get_" << (*x_iter)->get_name() << " with None -> () | Some _v ->" << endl;
965
        indent(f_service_) << "  raise (" << capitalize(type_name((*x_iter)->get_type())) << " _v));" << endl;
966
      }
967
 
968
      // Careful, only return _result if not a void function
969
      if ((*f_iter)->get_returntype()->is_void()) {
970
        indent(f_service_) <<
971
          "()" << endl;
972
      } else {
973
        f_service_ <<
974
          indent() << "raise (Application_Exn.E (Application_Exn.create Application_Exn.MISSING_RESULT \"" << (*f_iter)->get_name() << " failed: unknown result\")))" << endl;
975
        indent_down();
976
      }
977
 
978
      // Close function
979
      indent_down();
980
      indent_down();
981
      indent_down();
982
    }
983
  }
984
 
985
  indent_down();
986
  indent(f_service_) << "end" << endl << endl;
987
  indent(f_service_i_) << "end" << endl << endl;
988
}
989
 
990
/**
991
 * Generates a service server definition.
992
 *
993
 * @param tservice The service to generate a server for.
994
 */
995
void t_ocaml_generator::generate_service_server(t_service* tservice) {
996
  // Generate the dispatch methods
997
  vector<t_function*> functions = tservice->get_functions();
998
  vector<t_function*>::iterator f_iter;
999
 
1000
 
1001
  // Generate the header portion
1002
  indent(f_service_) <<
1003
    "class processor (handler : iface) =" << endl << indent() << "object (self)" << endl;
1004
  indent(f_service_i_) <<
1005
    "class processor : iface ->" << endl << indent() << "object" << endl;
1006
  indent_up();
1007
 
1008
  f_service_ <<
1009
     indent() << "inherit Processor.t" << endl <<
1010
    endl;
1011
  f_service_i_ <<
1012
     indent() << "inherit Processor.t" << endl <<
1013
    endl;
1014
  string extends = "";
1015
 
1016
  if (tservice->get_extends() != NULL) {
1017
    extends = type_name(tservice->get_extends());
1018
    indent(f_service_) << "inherit " + extends + ".processor (handler :> " + extends + ".iface)" << endl;
1019
    indent(f_service_i_) << "inherit " + extends + ".processor" << endl;
1020
  }
1021
 
1022
  if (extends.empty()) {
1023
    indent(f_service_) << "val processMap = Hashtbl.create " << functions.size() << endl;
1024
  }
1025
  indent(f_service_i_) << "val processMap : (string, int * Protocol.t * Protocol.t -> unit) Hashtbl.t" << endl;
1026
 
1027
  // Generate the server implementation
1028
  indent(f_service_) <<
1029
    "method process iprot oprot =" << endl;
1030
  indent(f_service_i_) <<
1031
    "method process : Protocol.t -> Protocol.t -> bool" << endl;
1032
  indent_up();
1033
 
1034
  f_service_ <<
1035
    indent() << "let (name, typ, seqid)  = iprot#readMessageBegin in" << endl;
1036
  indent_up();
1037
  // TODO(mcslee): validate message
1038
 
1039
  // HOT: dictionary function lookup
1040
  f_service_ <<
1041
    indent() << "if Hashtbl.mem processMap name then" << endl <<
1042
    indent() << "  (Hashtbl.find processMap name) (seqid, iprot, oprot)" << endl <<
1043
    indent() << "else (" << endl <<
1044
    indent() << "  iprot#skip(Protocol.T_STRUCT);" << endl <<
1045
    indent() << "  iprot#readMessageEnd;" << endl <<
1046
    indent() << "  let x = Application_Exn.create Application_Exn.UNKNOWN_METHOD (\"Unknown function \"^name) in" << endl <<
1047
    indent() << "    oprot#writeMessageBegin(name, Protocol.EXCEPTION, seqid);" << endl <<
1048
    indent() << "    x#write oprot;" << endl <<
1049
    indent() << "    oprot#writeMessageEnd;" << endl <<
1050
    indent() << "    oprot#getTransport#flush" << endl <<
1051
    indent() << ");" << endl;
1052
 
1053
  // Read end of args field, the T_STOP, and the struct close
1054
  f_service_ <<
1055
    indent() << "true" << endl;
1056
  indent_down();
1057
  indent_down();
1058
  // Generate the process subfunctions
1059
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
1060
    generate_process_function(tservice, *f_iter);
1061
  }
1062
 
1063
  indent(f_service_) << "initializer" << endl;
1064
  indent_up();
1065
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
1066
    f_service_ <<
1067
      indent() << "Hashtbl.add processMap \"" << (*f_iter)->get_name() << "\" self#process_" << (*f_iter)->get_name() << ";" << endl;
1068
  }
1069
  indent_down();
1070
 
1071
  indent_down();
1072
  indent(f_service_) << "end" << endl << endl;
1073
  indent(f_service_i_) << "end" << endl << endl;
1074
}
1075
 
1076
/**
1077
 * Generates a process function definition.
1078
 *
1079
 * @param tfunction The function to write a dispatcher for
1080
 */
1081
void t_ocaml_generator::generate_process_function(t_service* tservice,
1082
                                               t_function* tfunction) {
1083
  // Open function
1084
  indent(f_service_) <<
1085
    "method private process_" << tfunction->get_name() <<
1086
    " (seqid, iprot, oprot) =" << endl;
1087
  indent_up();
1088
 
1089
  string argsname = decapitalize(tfunction->get_name()) + "_args";
1090
  string resultname = decapitalize(tfunction->get_name()) + "_result";
1091
 
1092
  // Generate the function call
1093
  t_struct* arg_struct = tfunction->get_arglist();
1094
  const std::vector<t_field*>& fields = arg_struct->get_members();
1095
  vector<t_field*>::const_iterator f_iter;
1096
 
1097
  string args = "args";
1098
  if(fields.size() == 0){
1099
    args="_";
1100
  }
1101
 
1102
  f_service_ <<
1103
    indent() << "let "<<args<<" = read_" << argsname << " iprot in" << endl;
1104
  indent_up();
1105
  f_service_ <<
1106
    indent() << "iprot#readMessageEnd;" << endl;
1107
 
1108
  t_struct* xs = tfunction->get_xceptions();
1109
  const std::vector<t_field*>& xceptions = xs->get_members();
1110
  vector<t_field*>::const_iterator x_iter;
1111
 
1112
  // Declare result for non oneway function
1113
  if (!tfunction->is_oneway()) {
1114
    f_service_ <<
1115
      indent() << "let result = new " << resultname << " in" << endl;
1116
    indent_up();
1117
  }
1118
 
1119
  // Try block for a function with exceptions
1120
  if (xceptions.size() > 0) {
1121
    f_service_ <<
1122
      indent() << "(try" << endl;
1123
    indent_up();
1124
  }
1125
 
1126
 
1127
 
1128
 
1129
  f_service_ << indent();
1130
  if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
1131
    f_service_ << "result#set_success ";
1132
  }
1133
  f_service_ <<
1134
    "(handler#" << tfunction->get_name();
1135
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1136
    f_service_ <<  " args#get_" << (*f_iter)->get_name();
1137
  }
1138
  f_service_ << ");" << endl;
1139
 
1140
 
1141
  if (xceptions.size() > 0) {
1142
    indent_down();
1143
    indent(f_service_) << "with" <<endl;
1144
    indent_up();
1145
    for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
1146
      f_service_ <<
1147
        indent() << "| " << capitalize(type_name((*x_iter)->get_type())) << " " << (*x_iter)->get_name() << " -> " << endl;
1148
      indent_up();
1149
      indent_up();
1150
      if(!tfunction->is_oneway()){
1151
           f_service_ <<
1152
             indent() << "result#set_" << (*x_iter)->get_name() << " " << (*x_iter)->get_name() << endl;
1153
      } else {
1154
        indent(f_service_) << "()";
1155
      }
1156
      indent_down();
1157
      indent_down();
1158
    }
1159
    indent_down();
1160
    f_service_ << indent() << ");" << endl;
1161
  }
1162
 
1163
 
1164
 
1165
  // Shortcut out here for oneway functions
1166
  if (tfunction->is_oneway()) {
1167
    f_service_ <<
1168
      indent() << "()" << endl;
1169
    indent_down();
1170
    indent_down();
1171
    return;
1172
  }
1173
 
1174
  f_service_ <<
1175
    indent() << "oprot#writeMessageBegin (\"" << tfunction->get_name() << "\", Protocol.REPLY, seqid);" << endl <<
1176
    indent() << "result#write oprot;" << endl <<
1177
    indent() << "oprot#writeMessageEnd;" << endl <<
1178
    indent() << "oprot#getTransport#flush" << endl;
1179
 
1180
  // Close function
1181
  indent_down();
1182
  indent_down();
1183
  indent_down();
1184
}
1185
 
1186
/**
1187
 * Deserializes a field of any type.
1188
 */
1189
void t_ocaml_generator::generate_deserialize_field(ofstream &out,
1190
                                                   t_field* tfield,
1191
                                                   string prefix){
1192
  t_type* type = tfield->get_type();
1193
 
1194
 
1195
  string name = decapitalize(tfield->get_name());
1196
  indent(out) << prefix << "#set_"<<name << " ";
1197
  generate_deserialize_type(out,type);
1198
  out << endl;
1199
}
1200
 
1201
 
1202
/**
1203
 * Deserializes a field of any type.
1204
 */
1205
void t_ocaml_generator::generate_deserialize_type(ofstream &out,
1206
                                                   t_type* type){
1207
  type = get_true_type(type);
1208
 
1209
  if (type->is_void()) {
1210
    throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE";
1211
  }
1212
 
1213
 
1214
  if (type->is_struct() || type->is_xception()) {
1215
    generate_deserialize_struct(out,
1216
                                (t_struct*)type);
1217
  } else if (type->is_container()) {
1218
    generate_deserialize_container(out, type);
1219
  } else if (type->is_base_type()) {
1220
    out << "iprot#";
1221
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1222
    switch (tbase) {
1223
    case t_base_type::TYPE_VOID:
1224
      throw "compiler error: cannot serialize void field in a struct";
1225
      break;
1226
    case t_base_type::TYPE_STRING:
1227
      out << "readString";
1228
      break;
1229
    case t_base_type::TYPE_BOOL:
1230
      out << "readBool";
1231
      break;
1232
    case t_base_type::TYPE_BYTE:
1233
      out << "readByte";
1234
      break;
1235
    case t_base_type::TYPE_I16:
1236
      out << "readI16";
1237
      break;
1238
    case t_base_type::TYPE_I32:
1239
      out << "readI32";
1240
      break;
1241
    case t_base_type::TYPE_I64:
1242
      out << "readI64";
1243
      break;
1244
    case t_base_type::TYPE_DOUBLE:
1245
      out << "readDouble";
1246
      break;
1247
    default:
1248
      throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
1249
    }
1250
  } else if (type->is_enum()) {
1251
    string ename = capitalize(type->get_name());
1252
    out << "(" <<ename << ".of_i iprot#readI32)";
1253
  } else {
1254
    printf("DO NOT KNOW HOW TO DESERIALIZE TYPE '%s'\n",
1255
           type->get_name().c_str());
1256
  }
1257
}
1258
 
1259
 
1260
/**
1261
 * Generates an unserializer for a struct, calling read()
1262
 */
1263
void t_ocaml_generator::generate_deserialize_struct(ofstream &out,
1264
                                                  t_struct* tstruct) {
1265
  string name = decapitalize(tstruct->get_name());
1266
  out << "(read_" << name << " iprot)";
1267
 
1268
}
1269
 
1270
/**
1271
 * Serialize a container by writing out the header followed by
1272
 * data and then a footer.
1273
 */
1274
void t_ocaml_generator::generate_deserialize_container(ofstream &out,
1275
                                                    t_type* ttype) {
1276
  string size = tmp("_size");
1277
  string ktype = tmp("_ktype");
1278
  string vtype = tmp("_vtype");
1279
  string etype = tmp("_etype");
1280
  string con = tmp("_con");
1281
 
1282
  t_field fsize(g_type_i32, size);
1283
  t_field fktype(g_type_byte, ktype);
1284
  t_field fvtype(g_type_byte, vtype);
1285
  t_field fetype(g_type_byte, etype);
1286
 
1287
  out << endl;
1288
  indent_up();
1289
  // Declare variables, read header
1290
  if (ttype->is_map()) {
1291
    indent(out) << "(let ("<<ktype<<","<<vtype<<","<<size<<") = iprot#readMapBegin in" << endl;
1292
    indent(out) << "let "<<con<<" = Hashtbl.create "<<size<<" in" << endl;
1293
    indent_up();
1294
    indent(out) << "for i = 1 to "<<size<<" do" <<endl;
1295
    indent_up();
1296
    indent(out) << "let _k = ";
1297
    generate_deserialize_type(out,((t_map*)ttype)->get_key_type());
1298
    out << " in" << endl;
1299
    indent(out) << "let _v = ";
1300
    generate_deserialize_type(out,((t_map*)ttype)->get_val_type());
1301
    out << " in" << endl;
1302
    indent_up();
1303
    indent(out) << "Hashtbl.add "<<con<< " _k _v" << endl;
1304
    indent_down();
1305
    indent_down();
1306
    indent(out) << "done; iprot#readMapEnd; "<<con<<")";
1307
    indent_down();
1308
  } else if (ttype->is_set()) {
1309
    indent(out) << "(let ("<<etype<<","<<size<<") = iprot#readSetBegin in" << endl;
1310
    indent(out) << "let "<<con<<" = Hashtbl.create "<<size<<" in" << endl;
1311
    indent_up();
1312
    indent(out) << "for i = 1 to "<<size<<" do" <<endl;
1313
    indent_up();
1314
    indent(out) << "Hashtbl.add "<<con<<" ";
1315
    generate_deserialize_type(out,((t_set*)ttype)->get_elem_type());
1316
    out << " true" << endl;
1317
    indent_down();
1318
    indent(out) << "done; iprot#readSetEnd; "<<con<<")";
1319
    indent_down();
1320
  } else if (ttype->is_list()) {
1321
    indent(out) << "(let ("<<etype<<","<<size<<") = iprot#readListBegin in" << endl;
1322
    indent_up();
1323
    indent(out) << "let "<<con<<" = (Array.to_list (Array.init "<<size<<" (fun _ -> ";
1324
    generate_deserialize_type(out,((t_list*)ttype)->get_elem_type());
1325
    out << "))) in" << endl;
1326
    indent_up();
1327
    indent(out) << "iprot#readListEnd; "<<con<<")";
1328
    indent_down();
1329
    indent_down();
1330
  }
1331
  indent_down();
1332
}
1333
 
1334
 
1335
 
1336
/**
1337
 * Serializes a field of any type.
1338
 *
1339
 * @param tfield The field to serialize
1340
 * @param prefix Name to prepend to field name
1341
 */
1342
void t_ocaml_generator::generate_serialize_field(ofstream &out,
1343
                                                 t_field* tfield,
1344
                                                 string name) {
1345
  t_type* type = get_true_type(tfield->get_type());
1346
 
1347
  // Do nothing for void types
1348
  if (type->is_void()) {
1349
    throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " +
1350
      tfield->get_name();
1351
  }
1352
 
1353
  if(name.length() == 0){
1354
    name = decapitalize(tfield->get_name());
1355
  }
1356
 
1357
  if (type->is_struct() || type->is_xception()) {
1358
    generate_serialize_struct(out,
1359
                              (t_struct*)type,
1360
                              name);
1361
  } else if (type->is_container()) {
1362
    generate_serialize_container(out,
1363
                                 type,
1364
                                 name);
1365
  } else if (type->is_base_type() || type->is_enum()) {
1366
 
1367
 
1368
    indent(out) <<
1369
      "oprot#";
1370
 
1371
    if (type->is_base_type()) {
1372
      t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1373
      switch (tbase) {
1374
      case t_base_type::TYPE_VOID:
1375
        throw
1376
          "compiler error: cannot serialize void field in a struct: " + name;
1377
        break;
1378
      case t_base_type::TYPE_STRING:
1379
        out << "writeString(" << name << ")";
1380
        break;
1381
      case t_base_type::TYPE_BOOL:
1382
        out << "writeBool(" << name << ")";
1383
       break;
1384
      case t_base_type::TYPE_BYTE:
1385
        out << "writeByte(" << name << ")";
1386
        break;
1387
      case t_base_type::TYPE_I16:
1388
        out << "writeI16(" << name << ")";
1389
        break;
1390
      case t_base_type::TYPE_I32:
1391
        out << "writeI32(" << name << ")";
1392
        break;
1393
      case t_base_type::TYPE_I64:
1394
        out << "writeI64(" << name << ")";
1395
        break;
1396
      case t_base_type::TYPE_DOUBLE:
1397
        out << "writeDouble(" << name << ")";
1398
        break;
1399
      default:
1400
        throw "compiler error: no ocaml name for base type " + t_base_type::t_base_name(tbase);
1401
      }
1402
    } else if (type->is_enum()) {
1403
      string ename = capitalize(type->get_name());
1404
      out << "writeI32("<<ename<<".to_i " << name << ")";
1405
    }
1406
 
1407
  } else {
1408
    printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
1409
           tfield->get_name().c_str(),
1410
           type->get_name().c_str());
1411
  }
1412
  out << ";" << endl;
1413
}
1414
 
1415
/**
1416
 * Serializes all the members of a struct.
1417
 *
1418
 * @param tstruct The struct to serialize
1419
 * @param prefix  String prefix to attach to all fields
1420
 */
1421
void t_ocaml_generator::generate_serialize_struct(ofstream &out,
1422
                                               t_struct* tstruct,
1423
                                               string prefix) {
1424
  indent(out) << prefix << "#write(oprot)";
1425
}
1426
 
1427
void t_ocaml_generator::generate_serialize_container(ofstream &out,
1428
                                                  t_type* ttype,
1429
                                                  string prefix) {
1430
  if (ttype->is_map()) {
1431
    indent(out) << "oprot#writeMapBegin("<< type_to_enum(((t_map*)ttype)->get_key_type()) << ",";
1432
    out << type_to_enum(((t_map*)ttype)->get_val_type()) << ",";
1433
    out << "Hashtbl.length " << prefix << ");" << endl;
1434
  } else if (ttype->is_set()) {
1435
    indent(out) <<
1436
      "oprot#writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type()) << ",";
1437
    out << "Hashtbl.length " << prefix << ");" << endl;
1438
  } else if (ttype->is_list()) {
1439
    indent(out) <<
1440
      "oprot#writeListBegin(" << type_to_enum(((t_list*)ttype)->get_elem_type()) << ",";
1441
    out << "List.length " << prefix << ");" << endl;
1442
  }
1443
 
1444
  if (ttype->is_map()) {
1445
    string kiter = tmp("_kiter");
1446
    string viter = tmp("_viter");
1447
    indent(out) << "Hashtbl.iter (fun "<<kiter<<" -> fun " << viter << " -> " << endl;
1448
    indent_up();
1449
    generate_serialize_map_element(out, (t_map*)ttype, kiter, viter);
1450
    indent_down();
1451
    indent(out) << ") " << prefix << ";" << endl;
1452
  } else if (ttype->is_set()) {
1453
    string iter = tmp("_iter");
1454
    indent(out) << "Hashtbl.iter (fun "<<iter<<" -> fun _ -> ";
1455
    indent_up();
1456
    generate_serialize_set_element(out, (t_set*)ttype, iter);
1457
    indent_down();
1458
    indent(out) << ") " << prefix << ";" << endl;
1459
  } else if (ttype->is_list()) {
1460
    string iter = tmp("_iter");
1461
    indent(out) << "List.iter (fun "<<iter<<" -> ";
1462
    indent_up();
1463
    generate_serialize_list_element(out, (t_list*)ttype, iter);
1464
    indent_down();
1465
    indent(out) << ") " << prefix << ";" <<  endl;
1466
  }
1467
 
1468
  if (ttype->is_map()) {
1469
    indent(out) <<
1470
      "oprot#writeMapEnd";
1471
  } else if (ttype->is_set()) {
1472
    indent(out) <<
1473
      "oprot#writeSetEnd";
1474
  } else if (ttype->is_list()) {
1475
    indent(out) <<
1476
      "oprot#writeListEnd";
1477
  }
1478
}
1479
 
1480
/**
1481
 * Serializes the members of a map.
1482
 *
1483
 */
1484
void t_ocaml_generator::generate_serialize_map_element(ofstream &out,
1485
                                                     t_map* tmap,
1486
                                                     string kiter,
1487
                                                     string viter) {
1488
  t_field kfield(tmap->get_key_type(), kiter);
1489
  generate_serialize_field(out, &kfield);
1490
 
1491
  t_field vfield(tmap->get_val_type(), viter);
1492
  generate_serialize_field(out, &vfield);
1493
}
1494
 
1495
/**
1496
 * Serializes the members of a set.
1497
 */
1498
void t_ocaml_generator::generate_serialize_set_element(ofstream &out,
1499
                                                     t_set* tset,
1500
                                                     string iter) {
1501
  t_field efield(tset->get_elem_type(), iter);
1502
  generate_serialize_field(out, &efield);
1503
}
1504
 
1505
/**
1506
 * Serializes the members of a list.
1507
 */
1508
void t_ocaml_generator::generate_serialize_list_element(ofstream &out,
1509
                                                      t_list* tlist,
1510
                                                      string iter) {
1511
  t_field efield(tlist->get_elem_type(), iter);
1512
  generate_serialize_field(out, &efield);
1513
}
1514
 
1515
 
1516
 
1517
/**
1518
 * Renders a function signature of the form 'name args'
1519
 *
1520
 * @param tfunction Function definition
1521
 * @return String of rendered function definition
1522
 */
1523
string t_ocaml_generator::function_signature(t_function* tfunction,
1524
                                           string prefix) {
1525
  return
1526
    prefix + decapitalize(tfunction->get_name()) +
1527
    " " +  argument_list(tfunction->get_arglist());
1528
}
1529
 
1530
string t_ocaml_generator::function_type(t_function* tfunc, bool method, bool options){
1531
  string result="";
1532
 
1533
  const vector<t_field*>& fields = tfunc->get_arglist()->get_members();
1534
  vector<t_field*>::const_iterator f_iter;
1535
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1536
    result += render_ocaml_type((*f_iter)->get_type());
1537
    if(options)
1538
      result += " option";
1539
    result += " -> ";
1540
  }
1541
  if(fields.empty() && !method){
1542
    result += "unit -> ";
1543
  }
1544
  result += render_ocaml_type(tfunc->get_returntype());
1545
  return result;
1546
}
1547
 
1548
/**
1549
 * Renders a field list
1550
 */
1551
string t_ocaml_generator::argument_list(t_struct* tstruct) {
1552
  string result = "";
1553
 
1554
  const vector<t_field*>& fields = tstruct->get_members();
1555
  vector<t_field*>::const_iterator f_iter;
1556
  bool first = true;
1557
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
1558
    if (first) {
1559
      first = false;
1560
    } else {
1561
      result += " ";
1562
    }
1563
    result += (*f_iter)->get_name();
1564
  }
1565
  return result;
1566
}
1567
 
1568
string t_ocaml_generator::type_name(t_type* ttype) {
1569
  string prefix = "";
1570
  t_program* program = ttype->get_program();
1571
  if (program != NULL && program != program_) {
1572
    if (!ttype->is_service()) {
1573
      prefix = capitalize(program->get_name()) + "_types.";
1574
    }
1575
  }
1576
 
1577
  string name = ttype->get_name();
1578
  if(ttype->is_service()){
1579
    name = capitalize(name);
1580
  } else {
1581
    name = decapitalize(name);
1582
  }
1583
  return prefix + name;
1584
}
1585
 
1586
/**
1587
 * Converts the parse type to a Protocol.t_type enum
1588
 */
1589
string t_ocaml_generator::type_to_enum(t_type* type) {
1590
  type = get_true_type(type);
1591
 
1592
  if (type->is_base_type()) {
1593
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1594
    switch (tbase) {
1595
    case t_base_type::TYPE_VOID:
1596
      return "Protocol.T_VOID";
1597
    case t_base_type::TYPE_STRING:
1598
      return "Protocol.T_STRING";
1599
    case t_base_type::TYPE_BOOL:
1600
      return "Protocol.T_BOOL";
1601
    case t_base_type::TYPE_BYTE:
1602
      return "Protocol.T_BYTE";
1603
    case t_base_type::TYPE_I16:
1604
      return "Protocol.T_I16";
1605
    case t_base_type::TYPE_I32:
1606
      return "Protocol.T_I32";
1607
    case t_base_type::TYPE_I64:
1608
      return "Protocol.T_I64";
1609
    case t_base_type::TYPE_DOUBLE:
1610
      return "Protocol.T_DOUBLE";
1611
    }
1612
  } else if (type->is_enum()) {
1613
    return "Protocol.T_I32";
1614
  } else if (type->is_struct() || type->is_xception()) {
1615
    return "Protocol.T_STRUCT";
1616
  } else if (type->is_map()) {
1617
    return "Protocol.T_MAP";
1618
  } else if (type->is_set()) {
1619
    return "Protocol.T_SET";
1620
  } else if (type->is_list()) {
1621
    return "Protocol.T_LIST";
1622
  }
1623
 
1624
  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
1625
}
1626
 
1627
/**
1628
 * Converts the parse type to an ocaml type
1629
 */
1630
string t_ocaml_generator::render_ocaml_type(t_type* type) {
1631
  type = get_true_type(type);
1632
 
1633
  if (type->is_base_type()) {
1634
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
1635
    switch (tbase) {
1636
    case t_base_type::TYPE_VOID:
1637
      return "unit";
1638
    case t_base_type::TYPE_STRING:
1639
      return "string";
1640
    case t_base_type::TYPE_BOOL:
1641
      return "bool";
1642
    case t_base_type::TYPE_BYTE:
1643
      return "int";
1644
    case t_base_type::TYPE_I16:
1645
      return "int";
1646
    case t_base_type::TYPE_I32:
1647
      return "int";
1648
    case t_base_type::TYPE_I64:
1649
      return "Int64.t";
1650
    case t_base_type::TYPE_DOUBLE:
1651
      return "float";
1652
    }
1653
  } else if (type->is_enum()) {
1654
    return capitalize(((t_enum*)type)->get_name())+".t";
1655
  } else if (type->is_struct() || type->is_xception()) {
1656
    return type_name((t_struct*)type);
1657
  } else if (type->is_map()) {
1658
    t_type* ktype = ((t_map*)type)->get_key_type();
1659
    t_type* vtype = ((t_map*)type)->get_val_type();
1660
    return "("+render_ocaml_type(ktype)+","+render_ocaml_type(vtype)+") Hashtbl.t";
1661
  } else if (type->is_set()) {
1662
    t_type* etype = ((t_set*)type)->get_elem_type();
1663
    return "("+render_ocaml_type(etype)+",bool) Hashtbl.t";
1664
  } else if (type->is_list()) {
1665
    t_type* etype = ((t_list*)type)->get_elem_type();
1666
    return render_ocaml_type(etype)+" list";
1667
  }
1668
 
1669
  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
1670
}
1671
 
1672
 
1673
THRIFT_REGISTER_GENERATOR(ocaml, "OCaml", "");