blob: ba88ae385feef3adb5c5b0f61d6de9ab93515694 [file] [log] [blame]
Mark Sleee9ce01c2007-05-16 02:29:53 +00001// Copyright (c) 2006- Facebook
2// Distributed under the Thrift Software License
3//
4// See accompanying file LICENSE or visit the Thrift site at:
5// http://developers.facebook.com/thrift/
6
Mark Slee31985722006-05-24 21:45:31 +00007/**
8 * thrift - a lightweight cross-language rpc/serialization tool
9 *
10 * This file contains the main compiler engine for Thrift, which invokes the
11 * scanner/parser to build the thrift object tree. The interface generation
Mark Sleef5377b32006-10-10 01:42:59 +000012 * code for each language lives in a file by the language name under the
13 * generate/ folder, and all parse structures live in parse/
Mark Slee31985722006-05-24 21:45:31 +000014 *
15 * @author Mark Slee <mcslee@facebook.com>
16 */
17
18#include <stdlib.h>
19#include <stdio.h>
20#include <stdarg.h>
21#include <string>
Mark Sleef0712dc2006-10-25 19:03:57 +000022#include <sys/types.h>
23#include <sys/stat.h>
Mark Slee31985722006-05-24 21:45:31 +000024
Mark Sleef0712dc2006-10-25 19:03:57 +000025// Careful: must include globals first for extern definitions
Mark Slee31985722006-05-24 21:45:31 +000026#include "globals.h"
27
28#include "main.h"
29#include "parse/t_program.h"
Mark Sleef0712dc2006-10-25 19:03:57 +000030#include "parse/t_scope.h"
Mark Slee31985722006-05-24 21:45:31 +000031#include "generate/t_cpp_generator.h"
Mark Sleeb15a68b2006-06-07 06:46:24 +000032#include "generate/t_java_generator.h"
Mark Slee6e536442006-06-30 18:28:50 +000033#include "generate/t_php_generator.h"
Mark Sleefc89d392006-09-04 00:04:39 +000034#include "generate/t_py_generator.h"
Mark Slee6d7d5952007-01-27 01:44:22 +000035#include "generate/t_rb_generator.h"
Mark Slee0e0ff7e2007-01-18 22:59:59 +000036#include "generate/t_xsd_generator.h"
Mark Slee2c44d202007-05-16 02:18:07 +000037#include "generate/t_perl_generator.h"
iproctor9a41a0c2007-07-16 21:59:24 +000038#include "generate/t_ocaml_generator.h"
Christopher Piro2f5afce2007-06-29 07:17:33 +000039#include "generate/t_erl_generator.h"
iproctorff8eb922007-07-25 19:06:13 +000040#include "generate/t_hs_generator.h"
Mark Slee31985722006-05-24 21:45:31 +000041
42using namespace std;
43
Mark Sleef5377b32006-10-10 01:42:59 +000044/**
45 * Global program tree
46 */
Mark Slee31985722006-05-24 21:45:31 +000047t_program* g_program;
48
Mark Sleef5377b32006-10-10 01:42:59 +000049/**
Mark Sleef0712dc2006-10-25 19:03:57 +000050 * Global types
51 */
52
53t_type* g_type_void;
54t_type* g_type_string;
Mark Slee8d725a22007-04-13 01:57:12 +000055t_type* g_type_binary;
Mark Sleeb6200d82007-01-19 19:14:36 +000056t_type* g_type_slist;
Mark Sleef0712dc2006-10-25 19:03:57 +000057t_type* g_type_bool;
58t_type* g_type_byte;
59t_type* g_type_i16;
60t_type* g_type_i32;
61t_type* g_type_i64;
62t_type* g_type_double;
63
64/**
65 * Global scope
66 */
67t_scope* g_scope;
68
69/**
70 * Parent scope to also parse types
71 */
72t_scope* g_parent_scope;
73
74/**
75 * Prefix for putting types in parent scope
76 */
77string g_parent_prefix;
78
79/**
80 * Parsing pass
81 */
82PARSE_MODE g_parse_mode;
83
84/**
85 * Current directory of file being parsed
86 */
87string g_curdir;
88
89/**
90 * Current file being parsed
91 */
92string g_curpath;
93
94/**
Martin Kraemer32c66e12006-11-09 00:06:36 +000095 * Search path for inclusions
96 */
Mark Slee2329a832006-11-09 00:23:30 +000097vector<string> g_incl_searchpath;
Martin Kraemer32c66e12006-11-09 00:06:36 +000098
99/**
Mark Sleef5377b32006-10-10 01:42:59 +0000100 * Global debug state
101 */
Mark Slee31985722006-05-24 21:45:31 +0000102int g_debug = 0;
103
Mark Sleef5377b32006-10-10 01:42:59 +0000104/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000105 * Warning level
106 */
107int g_warn = 1;
108
109/**
110 * Verbose output
111 */
112int g_verbose = 0;
113
114/**
Mark Sleef5377b32006-10-10 01:42:59 +0000115 * Global time string
116 */
Mark Slee31985722006-05-24 21:45:31 +0000117char* g_time_str;
118
Mark Slee31985722006-05-24 21:45:31 +0000119/**
David Reisscbd4bac2007-08-14 17:12:33 +0000120 * The last parsed doctext comment.
121 */
122char* g_doctext;
123
124/**
125 * The location of the last parsed doctext comment.
126 */
127int g_doctext_lineno;
128
129/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000130 * Flags to control code generation
131 */
132bool gen_cpp = false;
133bool gen_java = false;
Mark Slee6d7d5952007-01-27 01:44:22 +0000134bool gen_rb = false;
Mark Sleef0712dc2006-10-25 19:03:57 +0000135bool gen_py = false;
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000136bool gen_xsd = false;
Mark Sleef0712dc2006-10-25 19:03:57 +0000137bool gen_php = false;
138bool gen_phpi = false;
Mark Slee756b1d12007-07-06 00:30:21 +0000139bool gen_rest = false;
Mark Slee2c44d202007-05-16 02:18:07 +0000140bool gen_perl = false;
iproctor9a41a0c2007-07-16 21:59:24 +0000141bool gen_ocaml = false;
Christopher Piro2f5afce2007-06-29 07:17:33 +0000142bool gen_erl = false;
iproctorff8eb922007-07-25 19:06:13 +0000143bool gen_hs = false;
Mark Sleef0712dc2006-10-25 19:03:57 +0000144bool gen_recurse = false;
145
146/**
Mark Slee31985722006-05-24 21:45:31 +0000147 * Report an error to the user. This is called yyerror for historical
148 * reasons (lex and yacc expect the error reporting routine to be called
149 * this). Call this function to report any errors to the user.
150 * yyerror takes printf style arguments.
151 *
152 * @param fmt C format string followed by additional arguments
153 */
154void yyerror(char* fmt, ...) {
155 va_list args;
156 fprintf(stderr,
Mark Sleef0712dc2006-10-25 19:03:57 +0000157 "[ERROR:%s:%d] (last token was '%s')\n",
158 g_curpath.c_str(),
Mark Slee31985722006-05-24 21:45:31 +0000159 yylineno,
160 yytext);
Mark Slee31985722006-05-24 21:45:31 +0000161
162 va_start(args, fmt);
163 vfprintf(stderr, fmt, args);
164 va_end(args);
165
166 fprintf(stderr, "\n");
167}
168
169/**
170 * Prints a debug message from the parser.
171 *
172 * @param fmt C format string followed by additional arguments
173 */
174void pdebug(char* fmt, ...) {
175 if (g_debug == 0) {
176 return;
177 }
178 va_list args;
Mark Slee30152872006-11-28 01:24:07 +0000179 printf("[PARSE:%d] ", yylineno);
Mark Sleef0712dc2006-10-25 19:03:57 +0000180 va_start(args, fmt);
181 vprintf(fmt, args);
182 va_end(args);
183 printf("\n");
184}
185
186/**
187 * Prints a verbose output mode message
188 *
189 * @param fmt C format string followed by additional arguments
190 */
191void pverbose(char* fmt, ...) {
192 if (g_verbose == 0) {
193 return;
194 }
195 va_list args;
196 va_start(args, fmt);
197 vprintf(fmt, args);
198 va_end(args);
199}
200
201/**
202 * Prints a warning message
203 *
204 * @param fmt C format string followed by additional arguments
205 */
206void pwarning(int level, char* fmt, ...) {
207 if (g_warn < level) {
208 return;
209 }
210 va_list args;
211 printf("[WARNING:%s:%d] ", g_curpath.c_str(), yylineno);
Mark Slee31985722006-05-24 21:45:31 +0000212 va_start(args, fmt);
213 vprintf(fmt, args);
214 va_end(args);
215 printf("\n");
216}
217
218/**
219 * Prints a failure message and exits
220 *
221 * @param fmt C format string followed by additional arguments
222 */
Mark Slee30152872006-11-28 01:24:07 +0000223void failure(const char* fmt, ...) {
Mark Slee2c44d202007-05-16 02:18:07 +0000224 va_list args;
Mark Sleef0712dc2006-10-25 19:03:57 +0000225 fprintf(stderr, "[FAILURE:%s:%d] ", g_curpath.c_str(), yylineno);
Mark Slee31985722006-05-24 21:45:31 +0000226 va_start(args, fmt);
227 vfprintf(stderr, fmt, args);
228 va_end(args);
229 printf("\n");
230 exit(1);
231}
232
233/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000234 * Converts a string filename into a thrift program name
235 */
236string program_name(string filename) {
237 string::size_type slash = filename.rfind("/");
238 if (slash != string::npos) {
239 filename = filename.substr(slash+1);
240 }
241 string::size_type dot = filename.rfind(".");
242 if (dot != string::npos) {
243 filename = filename.substr(0, dot);
244 }
245 return filename;
246}
247
248/**
249 * Gets the directory path of a filename
250 */
251string directory_name(string filename) {
252 string::size_type slash = filename.rfind("/");
253 // No slash, just use the current directory
254 if (slash == string::npos) {
255 return ".";
256 }
257 return filename.substr(0, slash);
258}
259
260/**
261 * Finds the appropriate file path for the given filename
262 */
263string include_file(string filename) {
264 // Absolute path? Just try that
Martin Kraemer32c66e12006-11-09 00:06:36 +0000265 if (filename[0] == '/') {
266 // Realpath!
267 char rp[PATH_MAX];
268 if (realpath(filename.c_str(), rp) == NULL) {
269 pwarning(0, "Cannot open include file %s\n", filename.c_str());
270 return std::string();
271 }
Mark Slee2c44d202007-05-16 02:18:07 +0000272
273 // Stat this file
Martin Kraemer32c66e12006-11-09 00:06:36 +0000274 struct stat finfo;
275 if (stat(rp, &finfo) == 0) {
276 return rp;
277 }
278 } else { // relative path, start searching
279 // new search path with current dir global
280 vector<string> sp = g_incl_searchpath;
281 sp.insert(sp.begin(), g_curdir);
Mark Slee2c44d202007-05-16 02:18:07 +0000282
Martin Kraemer32c66e12006-11-09 00:06:36 +0000283 // iterate through paths
284 vector<string>::iterator it;
285 for (it = sp.begin(); it != sp.end(); it++) {
286 string sfilename = *(it) + "/" + filename;
Mark Slee2c44d202007-05-16 02:18:07 +0000287
Martin Kraemer32c66e12006-11-09 00:06:36 +0000288 // Realpath!
289 char rp[PATH_MAX];
290 if (realpath(sfilename.c_str(), rp) == NULL) {
291 continue;
292 }
Mark Slee2c44d202007-05-16 02:18:07 +0000293
Martin Kraemer32c66e12006-11-09 00:06:36 +0000294 // Stat this files
295 struct stat finfo;
296 if (stat(rp, &finfo) == 0) {
297 return rp;
298 }
299 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000300 }
Mark Slee2c44d202007-05-16 02:18:07 +0000301
Mark Sleef0712dc2006-10-25 19:03:57 +0000302 // Uh oh
303 pwarning(0, "Could not find include file %s\n", filename.c_str());
304 return std::string();
305}
306
307/**
David Reisscbd4bac2007-08-14 17:12:33 +0000308 * Clears any previously stored doctext string.
309 * Also prints a warning if we are discarding information.
310 */
311void clear_doctext() {
312 if (g_doctext != NULL) {
313 pwarning(2, "Uncaptured doctext at on line %d.", g_doctext_lineno);
314 }
315 free(g_doctext);
316 g_doctext = NULL;
317}
318
319/**
David Reiss1ac05802007-07-30 22:00:27 +0000320 * Cleans up text commonly found in doxygen-like comments
321 *
322 * Warning: if you mix tabs and spaces in a non-uniform way,
323 * you will get what you deserve.
324 */
325char* clean_up_doctext(char* doctext) {
326 // Convert to C++ string, and remove Windows's carriage returns.
327 string docstring = doctext;
328 docstring.erase(
329 remove(docstring.begin(), docstring.end(), '\r'),
330 docstring.end());
331
332 // Separate into lines.
333 vector<string> lines;
334 string::size_type pos = string::npos;
335 string::size_type last;
336 while (true) {
337 last = (pos == string::npos) ? 0 : pos+1;
338 pos = docstring.find('\n', last);
339 if (pos == string::npos) {
340 // First bit of cleaning. If the last line is only whitespace, drop it.
341 string::size_type nonwhite = docstring.find_first_not_of(" \t", last);
342 if (nonwhite != string::npos) {
343 lines.push_back(docstring.substr(last));
344 }
345 break;
346 }
347 lines.push_back(docstring.substr(last, pos-last));
348 }
349
350 // A very profound docstring.
351 if (lines.empty()) {
352 return NULL;
353 }
354
355 // Clear leading whitespace from the first line.
356 pos = lines.front().find_first_not_of(" \t");
357 lines.front().erase(0, pos);
358
359 // If every nonblank line after the first has the same number of spaces/tabs,
360 // then a star, remove them.
361 bool have_prefix = true;
362 bool found_prefix = false;
363 string::size_type prefix_len = 0;
364 vector<string>::iterator l_iter;
365 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
366 if (l_iter->empty()) {
367 continue;
368 }
369
370 pos = l_iter->find_first_not_of(" \t");
371 if (!found_prefix) {
372 if (pos != string::npos) {
373 if (l_iter->at(pos) == '*') {
374 found_prefix = true;
375 prefix_len = pos;
376 } else {
377 have_prefix = false;
378 break;
379 }
380 } else {
381 // Whitespace-only line. Truncate it.
382 l_iter->clear();
383 }
384 } else if (l_iter->size() > pos
385 && l_iter->at(pos) == '*'
386 && pos == prefix_len) {
387 // Business as usual.
388 } else if (pos == string::npos) {
389 // Whitespace-only line. Let's truncate it for them.
390 l_iter->clear();
391 } else {
392 // The pattern has been broken.
393 have_prefix = false;
394 break;
395 }
396 }
397
398 // If our prefix survived, delete it from every line.
399 if (have_prefix) {
400 // Get the star too.
401 prefix_len++;
402 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
403 l_iter->erase(0, prefix_len);
404 }
405 }
406
407 // Now delete the minimum amount of leading whitespace from each line.
408 prefix_len = string::npos;
409 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
410 if (l_iter->empty()) {
411 continue;
412 }
413 pos = l_iter->find_first_not_of(" \t");
414 if (pos != string::npos
415 && (prefix_len == string::npos || pos < prefix_len)) {
416 prefix_len = pos;
417 }
418 }
419
420 // If our prefix survived, delete it from every line.
421 if (prefix_len != string::npos) {
422 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
423 l_iter->erase(0, prefix_len);
424 }
425 }
426
427 // Remove trailing whitespace from every line.
428 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
429 pos = l_iter->find_last_not_of(" \t");
430 if (pos != string::npos && pos != l_iter->length()-1) {
431 l_iter->erase(pos+1);
432 }
433 }
434
435 // If the first line is empty, remove it.
436 // Don't do this earlier because a lot of steps skip the first line.
437 if (lines.front().empty()) {
438 lines.erase(lines.begin());
439 }
440
441 // Now rejoin the lines and copy them back into doctext.
442 docstring.clear();
443 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
444 docstring += *l_iter;
445 docstring += '\n';
446 }
447
448 assert(docstring.length() <= strlen(doctext));
449 strcpy(doctext, docstring.c_str());
450 return doctext;
451}
452
453/** Set to true to debug docstring parsing */
454static bool dump_docs = false;
455
456/**
457 * Dumps docstrings to stdout
David Reisscdffe262007-08-14 17:12:31 +0000458 * Only works for top-level definitions and the whole program doc
459 * (i.e., not enum constants, struct fields, or functions.
David Reiss1ac05802007-07-30 22:00:27 +0000460 */
461void dump_docstrings(t_program* program) {
David Reisscdffe262007-08-14 17:12:31 +0000462 string progdoc = program->get_doc();
David Reissc2532a92007-07-30 23:46:11 +0000463 if (!progdoc.empty()) {
464 printf("Whole program doc:\n%s\n", progdoc.c_str());
465 }
David Reiss1ac05802007-07-30 22:00:27 +0000466 const vector<t_typedef*>& typedefs = program->get_typedefs();
467 vector<t_typedef*>::const_iterator t_iter;
468 for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {
469 t_typedef* td = *t_iter;
470 if (td->has_doc()) {
David Reisscdffe262007-08-14 17:12:31 +0000471 printf("typedef %s:\n%s\n", td->get_name().c_str(), td->get_doc().c_str());
472 }
473 }
474 const vector<t_enum*>& enums = program->get_enums();
475 vector<t_enum*>::const_iterator e_iter;
476 for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {
477 t_enum* en = *e_iter;
478 if (en->has_doc()) {
479 printf("enum %s:\n%s\n", en->get_name().c_str(), en->get_doc().c_str());
480 }
481 }
482 const vector<t_const*>& consts = program->get_consts();
483 vector<t_const*>::const_iterator c_iter;
484 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
485 t_const* co = *c_iter;
486 if (co->has_doc()) {
487 printf("const %s:\n%s\n", co->get_name().c_str(), co->get_doc().c_str());
488 }
489 }
490 const vector<t_struct*>& structs = program->get_structs();
491 vector<t_struct*>::const_iterator s_iter;
492 for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
493 t_struct* st = *s_iter;
494 if (st->has_doc()) {
495 printf("struct %s:\n%s\n", st->get_name().c_str(), st->get_doc().c_str());
496 }
497 }
498 const vector<t_struct*>& xceptions = program->get_xceptions();
499 vector<t_struct*>::const_iterator x_iter;
500 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
501 t_struct* xn = *x_iter;
502 if (xn->has_doc()) {
503 printf("xception %s:\n%s\n", xn->get_name().c_str(), xn->get_doc().c_str());
504 }
505 }
506 const vector<t_service*>& services = program->get_services();
507 vector<t_service*>::const_iterator v_iter;
508 for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
509 t_service* sv = *v_iter;
510 if (sv->has_doc()) {
511 printf("service %s:\n%s\n", sv->get_name().c_str(), sv->get_doc().c_str());
David Reiss1ac05802007-07-30 22:00:27 +0000512 }
513 }
514}
515
516/**
Mark Slee31985722006-05-24 21:45:31 +0000517 * Diplays the usage message and then exits with an error code.
518 */
519void usage() {
Mark Sleeb15a68b2006-06-07 06:46:24 +0000520 fprintf(stderr, "Usage: thrift [options] file\n");
521 fprintf(stderr, "Options:\n");
Mark Slee2329a832006-11-09 00:23:30 +0000522 fprintf(stderr, " -cpp Generate C++ output files\n");
523 fprintf(stderr, " -java Generate Java output files\n");
524 fprintf(stderr, " -php Generate PHP output files\n");
525 fprintf(stderr, " -phpi Generate PHP inlined files\n");
526 fprintf(stderr, " -py Generate Python output files\n");
ccheeverf53b5cf2007-02-05 20:33:11 +0000527 fprintf(stderr, " -rb Generate Ruby output files\n");
528 fprintf(stderr, " -xsd Generate XSD output files\n");
Mark Slee2c44d202007-05-16 02:18:07 +0000529 fprintf(stderr, " -perl Generate Perl output files\n");
iproctor9a41a0c2007-07-16 21:59:24 +0000530 fprintf(stderr, " -ocaml Generate OCaml output files\n");
Christopher Piro2f5afce2007-06-29 07:17:33 +0000531 fprintf(stderr, " -erl Generate Erlang output files\n");
iproctorff8eb922007-07-25 19:06:13 +0000532 fprintf(stderr, " -hs Generate Haskell output files\n");
Mark Slee227ac2c2007-03-07 05:46:50 +0000533 fprintf(stderr, " -I dir Add a directory to the list of directories \n");
534 fprintf(stderr, " searched for include directives\n");
Mark Slee2329a832006-11-09 00:23:30 +0000535 fprintf(stderr, " -nowarn Suppress all compiler warnings (BAD!)\n");
536 fprintf(stderr, " -strict Strict compiler warnings on\n");
537 fprintf(stderr, " -v[erbose] Verbose mode\n");
538 fprintf(stderr, " -r[ecurse] Also generate included files\n");
539 fprintf(stderr, " -debug Parse debug trace to stdout\n");
Mark Slee31985722006-05-24 21:45:31 +0000540 exit(1);
541}
542
543/**
Mark Slee30152872006-11-28 01:24:07 +0000544 * You know, when I started working on Thrift I really thought it wasn't going
545 * to become a programming language because it was just a generator and it
546 * wouldn't need runtime type information and all that jazz. But then we
547 * decided to add constants, and all of a sudden that means runtime type
548 * validation and inference, except the "runtime" is the code generator
549 * runtime. Shit. I've been had.
550 */
551void validate_const_rec(std::string name, t_type* type, t_const_value* value) {
552 if (type->is_void()) {
553 throw "type error: cannot declare a void const: " + name;
554 }
555
556 if (type->is_base_type()) {
557 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
558 switch (tbase) {
559 case t_base_type::TYPE_STRING:
560 if (value->get_type() != t_const_value::CV_STRING) {
561 throw "type error: const \"" + name + "\" was declared as string";
562 }
563 break;
564 case t_base_type::TYPE_BOOL:
565 if (value->get_type() != t_const_value::CV_INTEGER) {
566 throw "type error: const \"" + name + "\" was declared as bool";
567 }
568 break;
569 case t_base_type::TYPE_BYTE:
570 if (value->get_type() != t_const_value::CV_INTEGER) {
571 throw "type error: const \"" + name + "\" was declared as byte";
572 }
573 break;
574 case t_base_type::TYPE_I16:
575 if (value->get_type() != t_const_value::CV_INTEGER) {
576 throw "type error: const \"" + name + "\" was declared as i16";
577 }
578 break;
579 case t_base_type::TYPE_I32:
580 if (value->get_type() != t_const_value::CV_INTEGER) {
581 throw "type error: const \"" + name + "\" was declared as i32";
582 }
583 break;
584 case t_base_type::TYPE_I64:
585 if (value->get_type() != t_const_value::CV_INTEGER) {
586 throw "type error: const \"" + name + "\" was declared as i64";
587 }
588 break;
589 case t_base_type::TYPE_DOUBLE:
590 if (value->get_type() != t_const_value::CV_INTEGER &&
591 value->get_type() != t_const_value::CV_DOUBLE) {
592 throw "type error: const \"" + name + "\" was declared as double";
593 }
594 break;
595 default:
596 throw "compiler error: no const of base type " + tbase + name;
597 }
598 } else if (type->is_enum()) {
599 if (value->get_type() != t_const_value::CV_INTEGER) {
600 throw "type error: const \"" + name + "\" was declared as enum";
601 }
602 } else if (type->is_struct() || type->is_xception()) {
603 if (value->get_type() != t_const_value::CV_MAP) {
604 throw "type error: const \"" + name + "\" was declared as struct/xception";
605 }
606 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
607 vector<t_field*>::const_iterator f_iter;
608
609 const map<t_const_value*, t_const_value*>& val = value->get_map();
610 map<t_const_value*, t_const_value*>::const_iterator v_iter;
611 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
612 if (v_iter->first->get_type() != t_const_value::CV_STRING) {
613 throw "type error: " + name + " struct key must be string";
614 }
615 t_type* field_type = NULL;
616 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
617 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
618 field_type = (*f_iter)->get_type();
619 }
620 }
621 if (field_type == NULL) {
622 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
623 }
624
625 validate_const_rec(name + "." + v_iter->first->get_string(), field_type, v_iter->second);
626 }
627 } else if (type->is_map()) {
628 t_type* k_type = ((t_map*)type)->get_key_type();
629 t_type* v_type = ((t_map*)type)->get_val_type();
630 const map<t_const_value*, t_const_value*>& val = value->get_map();
631 map<t_const_value*, t_const_value*>::const_iterator v_iter;
632 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
633 validate_const_rec(name + "<key>", k_type, v_iter->first);
634 validate_const_rec(name + "<val>", v_type, v_iter->second);
Mark Slee2c44d202007-05-16 02:18:07 +0000635 }
Mark Slee30152872006-11-28 01:24:07 +0000636 } else if (type->is_list() || type->is_set()) {
637 t_type* e_type;
638 if (type->is_list()) {
639 e_type = ((t_list*)type)->get_elem_type();
640 } else {
641 e_type = ((t_set*)type)->get_elem_type();
642 }
643 const vector<t_const_value*>& val = value->get_list();
644 vector<t_const_value*>::const_iterator v_iter;
645 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
646 validate_const_rec(name + "<elem>", e_type, *v_iter);
647 }
648 }
649}
650
651/**
652 * Check the type of the parsed const information against its declared type
653 */
654void validate_const_type(t_const* c) {
655 validate_const_rec(c->get_name(), c->get_type(), c->get_value());
656}
657
658/**
Mark Slee7ff32452007-02-01 05:26:18 +0000659 * Check the type of a default value assigned to a field.
660 */
661void validate_field_value(t_field* field, t_const_value* cv) {
662 validate_const_rec(field->get_name(), field->get_type(), cv);
663}
664
665/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000666 * Parses a program
667 */
Mark Slee2c44d202007-05-16 02:18:07 +0000668void parse(t_program* program, t_program* parent_program) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000669 // Get scope file path
670 string path = program->get_path();
Mark Slee2c44d202007-05-16 02:18:07 +0000671
Mark Sleef0712dc2006-10-25 19:03:57 +0000672 // Set current dir global, which is used in the include_file function
673 g_curdir = directory_name(path);
674 g_curpath = path;
675
676 // Open the file
677 yyin = fopen(path.c_str(), "r");
678 if (yyin == 0) {
679 failure("Could not open input file: \"%s\"", path.c_str());
680 }
681
682 // Create new scope and scan for includes
683 pverbose("Scanning %s for includes\n", path.c_str());
Mark Slee2c44d202007-05-16 02:18:07 +0000684 g_parse_mode = INCLUDES;
Mark Sleef0712dc2006-10-25 19:03:57 +0000685 g_program = program;
686 g_scope = program->scope();
Mark Slee30152872006-11-28 01:24:07 +0000687 try {
Mark Slee36bfa2e2007-01-19 20:09:51 +0000688 yylineno = 1;
Mark Slee30152872006-11-28 01:24:07 +0000689 if (yyparse() != 0) {
690 failure("Parser error during include pass.");
691 }
692 } catch (string x) {
693 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000694 }
695 fclose(yyin);
696
697 // Recursively parse all the include programs
698 vector<t_program*>& includes = program->get_includes();
699 vector<t_program*>::iterator iter;
700 for (iter = includes.begin(); iter != includes.end(); ++iter) {
701 parse(*iter, program);
702 }
703
704 // Parse the program the file
705 g_parse_mode = PROGRAM;
706 g_program = program;
707 g_scope = program->scope();
708 g_parent_scope = (parent_program != NULL) ? parent_program->scope() : NULL;
709 g_parent_prefix = program->get_name() + ".";
710 g_curpath = path;
711 yyin = fopen(path.c_str(), "r");
712 if (yyin == 0) {
713 failure("Could not open input file: \"%s\"", path.c_str());
714 }
715 pverbose("Parsing %s for types\n", path.c_str());
Mark Slee36bfa2e2007-01-19 20:09:51 +0000716 yylineno = 1;
David Reiss877237a2007-07-27 00:40:19 +0000717 try {
718 if (yyparse() != 0) {
719 failure("Parser error during types pass.");
720 }
721 } catch (string x) {
722 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000723 }
724 fclose(yyin);
725}
726
727/**
728 * Generate code
729 */
730void generate(t_program* program) {
731 // Oooohh, recursive code generation, hot!!
732 if (gen_recurse) {
733 const vector<t_program*>& includes = program->get_includes();
734 for (size_t i = 0; i < includes.size(); ++i) {
735 generate(includes[i]);
736 }
737 }
738
739 // Generate code!
740 try {
741 pverbose("Program: %s\n", program->get_path().c_str());
742
743 if (gen_cpp) {
744 pverbose("Generating C++\n");
745 t_cpp_generator* cpp = new t_cpp_generator(program);
746 cpp->generate_program();
747 delete cpp;
748 }
749
750 if (gen_java) {
751 pverbose("Generating Java\n");
752 t_java_generator* java = new t_java_generator(program);
753 java->generate_program();
754 delete java;
755 }
756
757 if (gen_php) {
758 pverbose("Generating PHP\n");
Mark Slee756b1d12007-07-06 00:30:21 +0000759 t_php_generator* php = new t_php_generator(program, false, gen_rest);
Mark Sleef0712dc2006-10-25 19:03:57 +0000760 php->generate_program();
761 delete php;
762 }
763
764 if (gen_phpi) {
765 pverbose("Generating PHP-inline\n");
Mark Slee756b1d12007-07-06 00:30:21 +0000766 t_php_generator* phpi = new t_php_generator(program, true, gen_rest);
Mark Sleef0712dc2006-10-25 19:03:57 +0000767 phpi->generate_program();
768 delete phpi;
769 }
770
771 if (gen_py) {
772 pverbose("Generating Python\n");
773 t_py_generator* py = new t_py_generator(program);
774 py->generate_program();
775 delete py;
776 }
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000777
Mark Slee6d7d5952007-01-27 01:44:22 +0000778 if (gen_rb) {
779 pverbose("Generating Ruby\n");
780 t_rb_generator* rb = new t_rb_generator(program);
781 rb->generate_program();
782 delete rb;
783 }
784
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000785 if (gen_xsd) {
786 pverbose("Generating XSD\n");
787 t_xsd_generator* xsd = new t_xsd_generator(program);
788 xsd->generate_program();
789 delete xsd;
790 }
791
Mark Slee2c44d202007-05-16 02:18:07 +0000792 if (gen_perl) {
793 pverbose("Generating PERL\n");
794 t_perl_generator* perl = new t_perl_generator(program);
795 perl->generate_program();
796 delete perl;
797 }
798
iproctor9a41a0c2007-07-16 21:59:24 +0000799 if (gen_ocaml) {
800 pverbose("Generating OCaml\n");
801 t_ocaml_generator* ocaml = new t_ocaml_generator(program);
802 ocaml->generate_program();
803 delete ocaml;
804 }
805
Christopher Piro2f5afce2007-06-29 07:17:33 +0000806 if (gen_erl) {
807 pverbose("Generating Erlang\n");
808 t_erl_generator* erl = new t_erl_generator(program);
809 erl->generate_program();
810 delete erl;
811 }
iproctorff8eb922007-07-25 19:06:13 +0000812 if (gen_hs) {
813 pverbose("Generating Haskell\n");
814 t_hs_generator* hs = new t_hs_generator(program);
815 hs->generate_program();
816 delete hs;
817 }
David Reiss1ac05802007-07-30 22:00:27 +0000818 if (dump_docs) {
819 dump_docstrings(program);
820 }
iproctor9a41a0c2007-07-16 21:59:24 +0000821
Mark Sleef0712dc2006-10-25 19:03:57 +0000822 } catch (string s) {
823 printf("Error: %s\n", s.c_str());
824 } catch (const char* exc) {
825 printf("Error: %s\n", exc);
826 }
827
828}
829
830/**
Mark Sleef5377b32006-10-10 01:42:59 +0000831 * Parse it up.. then spit it back out, in pretty much every language. Alright
832 * not that many languages, but the cool ones that we care about.
Mark Slee31985722006-05-24 21:45:31 +0000833 */
834int main(int argc, char** argv) {
835 int i;
Mark Sleef5377b32006-10-10 01:42:59 +0000836
Mark Sleeb15a68b2006-06-07 06:46:24 +0000837 // Setup time string
838 time_t now = time(NULL);
839 g_time_str = ctime(&now);
Mark Slee31985722006-05-24 21:45:31 +0000840
Mark Sleef0712dc2006-10-25 19:03:57 +0000841 // Check for necessary arguments, you gotta have at least a filename and
842 // an output language flag
Mark Sleeb15a68b2006-06-07 06:46:24 +0000843 if (argc < 2) {
844 usage();
845 }
Mark Slee31985722006-05-24 21:45:31 +0000846
Mark Sleef5377b32006-10-10 01:42:59 +0000847 // Hacky parameter handling... I didn't feel like using a library sorry!
Mark Slee31985722006-05-24 21:45:31 +0000848 for (i = 1; i < argc-1; i++) {
Mark Sleefdbee812006-09-27 18:50:48 +0000849 char* arg;
Mark Slee2329a832006-11-09 00:23:30 +0000850
Mark Sleefdbee812006-09-27 18:50:48 +0000851 arg = strtok(argv[i], " ");
852 while (arg != NULL) {
Mark Slee2329a832006-11-09 00:23:30 +0000853 // Treat double dashes as single dashes
Mark Slee52cb2232006-11-10 22:32:07 +0000854 if (arg[0] == '-' && arg[1] == '-') {
Mark Slee2329a832006-11-09 00:23:30 +0000855 ++arg;
856 }
857
858 if (strcmp(arg, "-debug") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000859 g_debug = 1;
Mark Slee2329a832006-11-09 00:23:30 +0000860 } else if (strcmp(arg, "-nowarn") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000861 g_warn = 0;
Mark Slee2329a832006-11-09 00:23:30 +0000862 } else if (strcmp(arg, "-strict") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000863 g_warn = 2;
Mark Slee2329a832006-11-09 00:23:30 +0000864 } else if (strcmp(arg, "-v") == 0 || strcmp(arg, "-verbose") == 0 ) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000865 g_verbose = 1;
Mark Slee2329a832006-11-09 00:23:30 +0000866 } else if (strcmp(arg, "-r") == 0 || strcmp(arg, "-recurse") == 0 ) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000867 gen_recurse = true;
Mark Slee2329a832006-11-09 00:23:30 +0000868 } else if (strcmp(arg, "-cpp") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000869 gen_cpp = true;
Mark Slee2329a832006-11-09 00:23:30 +0000870 } else if (strcmp(arg, "-java") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000871 gen_java = true;
Mark Slee2329a832006-11-09 00:23:30 +0000872 } else if (strcmp(arg, "-php") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000873 gen_php = true;
Mark Slee2329a832006-11-09 00:23:30 +0000874 } else if (strcmp(arg, "-phpi") == 0) {
Mark Sleef5377b32006-10-10 01:42:59 +0000875 gen_phpi = true;
Mark Slee756b1d12007-07-06 00:30:21 +0000876 } else if (strcmp(arg, "-rest") == 0) {
877 gen_rest = true;
Mark Slee2329a832006-11-09 00:23:30 +0000878 } else if (strcmp(arg, "-py") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000879 gen_py = true;
Mark Slee6d7d5952007-01-27 01:44:22 +0000880 } else if (strcmp(arg, "-rb") == 0) {
881 gen_rb = true;
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000882 } else if (strcmp(arg, "-xsd") == 0) {
883 gen_xsd = true;
Mark Slee2c44d202007-05-16 02:18:07 +0000884 } else if (strcmp(arg, "-perl") == 0) {
885 gen_perl = true;
iproctor9a41a0c2007-07-16 21:59:24 +0000886 } else if (strcmp(arg, "-ocaml") == 0) {
887 gen_ocaml = true;
Christopher Piro2f5afce2007-06-29 07:17:33 +0000888 } else if (strcmp(arg, "-erl") == 0) {
889 gen_erl = true;
iproctorff8eb922007-07-25 19:06:13 +0000890 } else if (strcmp(arg, "-hs") == 0) {
891 gen_hs = true;
Martin Kraemer32c66e12006-11-09 00:06:36 +0000892 } else if (strcmp(arg, "-I") == 0) {
893 // An argument of "-I\ asdf" is invalid and has unknown results
894 arg = argv[++i];
895
896 if (arg == NULL) {
897 fprintf(stderr, "!!! Missing Include directory");
898 usage();
899 }
900 g_incl_searchpath.push_back(arg);
Mark Sleefdbee812006-09-27 18:50:48 +0000901 } else {
902 fprintf(stderr, "!!! Unrecognized option: %s\n", arg);
903 usage();
904 }
905
906 // Tokenize more
907 arg = strtok(NULL, " ");
Mark Slee31985722006-05-24 21:45:31 +0000908 }
909 }
Mark Slee2c44d202007-05-16 02:18:07 +0000910
Mark Sleef0712dc2006-10-25 19:03:57 +0000911 // You gotta generate something!
iproctorff8eb922007-07-25 19:06:13 +0000912 if (!gen_cpp && !gen_java && !gen_php && !gen_phpi && !gen_py && !gen_rb && !gen_xsd && !gen_perl && !gen_ocaml && !gen_erl && !gen_hs) {
Mark Sleeb15a68b2006-06-07 06:46:24 +0000913 fprintf(stderr, "!!! No output language(s) specified\n\n");
914 usage();
915 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000916
917 // Real-pathify it
918 char rp[PATH_MAX];
919 if (realpath(argv[i], rp) == NULL) {
920 failure("Could not open input file: %s", argv[i]);
Mark Slee31985722006-05-24 21:45:31 +0000921 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000922 string input_file(rp);
923
Mark Sleef5377b32006-10-10 01:42:59 +0000924 // Instance of the global parse tree
Mark Sleef0712dc2006-10-25 19:03:57 +0000925 t_program* program = new t_program(input_file);
926
927 // Initialize global types
928 g_type_void = new t_base_type("void", t_base_type::TYPE_VOID);
929 g_type_string = new t_base_type("string", t_base_type::TYPE_STRING);
Mark Slee8d725a22007-04-13 01:57:12 +0000930 g_type_binary = new t_base_type("string", t_base_type::TYPE_STRING);
931 ((t_base_type*)g_type_binary)->set_binary(true);
Mark Sleeb6200d82007-01-19 19:14:36 +0000932 g_type_slist = new t_base_type("string", t_base_type::TYPE_STRING);
933 ((t_base_type*)g_type_slist)->set_string_list(true);
Mark Sleef0712dc2006-10-25 19:03:57 +0000934 g_type_bool = new t_base_type("bool", t_base_type::TYPE_BOOL);
935 g_type_byte = new t_base_type("byte", t_base_type::TYPE_BYTE);
936 g_type_i16 = new t_base_type("i16", t_base_type::TYPE_I16);
937 g_type_i32 = new t_base_type("i32", t_base_type::TYPE_I32);
938 g_type_i64 = new t_base_type("i64", t_base_type::TYPE_I64);
939 g_type_double = new t_base_type("double", t_base_type::TYPE_DOUBLE);
Mark Sleee8540632006-05-30 09:24:40 +0000940
Mark Sleef5377b32006-10-10 01:42:59 +0000941 // Parse it!
Mark Sleef0712dc2006-10-25 19:03:57 +0000942 parse(program, NULL);
Mark Slee31985722006-05-24 21:45:31 +0000943
Mark Sleef0712dc2006-10-25 19:03:57 +0000944 // Generate it!
945 generate(program);
Mark Sleeb15a68b2006-06-07 06:46:24 +0000946
Mark Sleef0712dc2006-10-25 19:03:57 +0000947 // Clean up. Who am I kidding... this program probably orphans heap memory
948 // all over the place, but who cares because it is about to exit and it is
949 // all referenced and used by this wacky parse tree up until now anyways.
Mark Sleeb15a68b2006-06-07 06:46:24 +0000950
Mark Sleef0712dc2006-10-25 19:03:57 +0000951 delete program;
952 delete g_type_void;
953 delete g_type_string;
954 delete g_type_bool;
955 delete g_type_byte;
956 delete g_type_i16;
957 delete g_type_i32;
958 delete g_type_i64;
959 delete g_type_double;
Mark Slee31985722006-05-24 21:45:31 +0000960
961 // Finished
Mark Slee31985722006-05-24 21:45:31 +0000962 return 0;
963}