blob: b070b3b9a67ba1df366f394ac3dbf452495bc0f0 [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/**
David Reiss18bf22d2007-08-28 20:49:17 +0000517 * Call generate_fingerprint for every structure.
518 */
519void generate_all_fingerprints(t_program* program) {
520 const vector<t_struct*>& structs = program->get_structs();
521 vector<t_struct*>::const_iterator s_iter;
522 for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
523 t_struct* st = *s_iter;
524 st->generate_fingerprint();
525 }
526
527 // If you want to generate fingerprints for implicit structures, start here.
528 /*
529 const vector<t_service*>& services = program->get_services();
530 vector<t_service*>::const_iterator v_iter;
531 for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
532 t_service* sv = *v_iter;
533 }
534 */
535}
536
537/**
Mark Slee31985722006-05-24 21:45:31 +0000538 * Diplays the usage message and then exits with an error code.
539 */
540void usage() {
Mark Sleeb15a68b2006-06-07 06:46:24 +0000541 fprintf(stderr, "Usage: thrift [options] file\n");
542 fprintf(stderr, "Options:\n");
Mark Slee2329a832006-11-09 00:23:30 +0000543 fprintf(stderr, " -cpp Generate C++ output files\n");
544 fprintf(stderr, " -java Generate Java output files\n");
545 fprintf(stderr, " -php Generate PHP output files\n");
546 fprintf(stderr, " -phpi Generate PHP inlined files\n");
547 fprintf(stderr, " -py Generate Python output files\n");
ccheeverf53b5cf2007-02-05 20:33:11 +0000548 fprintf(stderr, " -rb Generate Ruby output files\n");
549 fprintf(stderr, " -xsd Generate XSD output files\n");
Mark Slee2c44d202007-05-16 02:18:07 +0000550 fprintf(stderr, " -perl Generate Perl output files\n");
iproctor9a41a0c2007-07-16 21:59:24 +0000551 fprintf(stderr, " -ocaml Generate OCaml output files\n");
Christopher Piro2f5afce2007-06-29 07:17:33 +0000552 fprintf(stderr, " -erl Generate Erlang output files\n");
iproctorff8eb922007-07-25 19:06:13 +0000553 fprintf(stderr, " -hs Generate Haskell output files\n");
Mark Slee227ac2c2007-03-07 05:46:50 +0000554 fprintf(stderr, " -I dir Add a directory to the list of directories \n");
555 fprintf(stderr, " searched for include directives\n");
Mark Slee2329a832006-11-09 00:23:30 +0000556 fprintf(stderr, " -nowarn Suppress all compiler warnings (BAD!)\n");
557 fprintf(stderr, " -strict Strict compiler warnings on\n");
558 fprintf(stderr, " -v[erbose] Verbose mode\n");
559 fprintf(stderr, " -r[ecurse] Also generate included files\n");
560 fprintf(stderr, " -debug Parse debug trace to stdout\n");
Mark Slee31985722006-05-24 21:45:31 +0000561 exit(1);
562}
563
564/**
Mark Slee30152872006-11-28 01:24:07 +0000565 * You know, when I started working on Thrift I really thought it wasn't going
566 * to become a programming language because it was just a generator and it
567 * wouldn't need runtime type information and all that jazz. But then we
568 * decided to add constants, and all of a sudden that means runtime type
569 * validation and inference, except the "runtime" is the code generator
570 * runtime. Shit. I've been had.
571 */
572void validate_const_rec(std::string name, t_type* type, t_const_value* value) {
573 if (type->is_void()) {
574 throw "type error: cannot declare a void const: " + name;
575 }
576
577 if (type->is_base_type()) {
578 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
579 switch (tbase) {
580 case t_base_type::TYPE_STRING:
581 if (value->get_type() != t_const_value::CV_STRING) {
582 throw "type error: const \"" + name + "\" was declared as string";
583 }
584 break;
585 case t_base_type::TYPE_BOOL:
586 if (value->get_type() != t_const_value::CV_INTEGER) {
587 throw "type error: const \"" + name + "\" was declared as bool";
588 }
589 break;
590 case t_base_type::TYPE_BYTE:
591 if (value->get_type() != t_const_value::CV_INTEGER) {
592 throw "type error: const \"" + name + "\" was declared as byte";
593 }
594 break;
595 case t_base_type::TYPE_I16:
596 if (value->get_type() != t_const_value::CV_INTEGER) {
597 throw "type error: const \"" + name + "\" was declared as i16";
598 }
599 break;
600 case t_base_type::TYPE_I32:
601 if (value->get_type() != t_const_value::CV_INTEGER) {
602 throw "type error: const \"" + name + "\" was declared as i32";
603 }
604 break;
605 case t_base_type::TYPE_I64:
606 if (value->get_type() != t_const_value::CV_INTEGER) {
607 throw "type error: const \"" + name + "\" was declared as i64";
608 }
609 break;
610 case t_base_type::TYPE_DOUBLE:
611 if (value->get_type() != t_const_value::CV_INTEGER &&
612 value->get_type() != t_const_value::CV_DOUBLE) {
613 throw "type error: const \"" + name + "\" was declared as double";
614 }
615 break;
616 default:
David Reissdd7796f2007-08-28 21:09:06 +0000617 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase) + name;
Mark Slee30152872006-11-28 01:24:07 +0000618 }
619 } else if (type->is_enum()) {
620 if (value->get_type() != t_const_value::CV_INTEGER) {
621 throw "type error: const \"" + name + "\" was declared as enum";
622 }
623 } else if (type->is_struct() || type->is_xception()) {
624 if (value->get_type() != t_const_value::CV_MAP) {
625 throw "type error: const \"" + name + "\" was declared as struct/xception";
626 }
627 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
628 vector<t_field*>::const_iterator f_iter;
629
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 if (v_iter->first->get_type() != t_const_value::CV_STRING) {
634 throw "type error: " + name + " struct key must be string";
635 }
636 t_type* field_type = NULL;
637 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
638 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
639 field_type = (*f_iter)->get_type();
640 }
641 }
642 if (field_type == NULL) {
643 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
644 }
645
646 validate_const_rec(name + "." + v_iter->first->get_string(), field_type, v_iter->second);
647 }
648 } else if (type->is_map()) {
649 t_type* k_type = ((t_map*)type)->get_key_type();
650 t_type* v_type = ((t_map*)type)->get_val_type();
651 const map<t_const_value*, t_const_value*>& val = value->get_map();
652 map<t_const_value*, t_const_value*>::const_iterator v_iter;
653 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
654 validate_const_rec(name + "<key>", k_type, v_iter->first);
655 validate_const_rec(name + "<val>", v_type, v_iter->second);
Mark Slee2c44d202007-05-16 02:18:07 +0000656 }
Mark Slee30152872006-11-28 01:24:07 +0000657 } else if (type->is_list() || type->is_set()) {
658 t_type* e_type;
659 if (type->is_list()) {
660 e_type = ((t_list*)type)->get_elem_type();
661 } else {
662 e_type = ((t_set*)type)->get_elem_type();
663 }
664 const vector<t_const_value*>& val = value->get_list();
665 vector<t_const_value*>::const_iterator v_iter;
666 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
667 validate_const_rec(name + "<elem>", e_type, *v_iter);
668 }
669 }
670}
671
672/**
673 * Check the type of the parsed const information against its declared type
674 */
675void validate_const_type(t_const* c) {
676 validate_const_rec(c->get_name(), c->get_type(), c->get_value());
677}
678
679/**
Mark Slee7ff32452007-02-01 05:26:18 +0000680 * Check the type of a default value assigned to a field.
681 */
682void validate_field_value(t_field* field, t_const_value* cv) {
683 validate_const_rec(field->get_name(), field->get_type(), cv);
684}
685
686/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000687 * Parses a program
688 */
Mark Slee2c44d202007-05-16 02:18:07 +0000689void parse(t_program* program, t_program* parent_program) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000690 // Get scope file path
691 string path = program->get_path();
Mark Slee2c44d202007-05-16 02:18:07 +0000692
Mark Sleef0712dc2006-10-25 19:03:57 +0000693 // Set current dir global, which is used in the include_file function
694 g_curdir = directory_name(path);
695 g_curpath = path;
696
697 // Open the file
698 yyin = fopen(path.c_str(), "r");
699 if (yyin == 0) {
700 failure("Could not open input file: \"%s\"", path.c_str());
701 }
702
703 // Create new scope and scan for includes
704 pverbose("Scanning %s for includes\n", path.c_str());
Mark Slee2c44d202007-05-16 02:18:07 +0000705 g_parse_mode = INCLUDES;
Mark Sleef0712dc2006-10-25 19:03:57 +0000706 g_program = program;
707 g_scope = program->scope();
Mark Slee30152872006-11-28 01:24:07 +0000708 try {
Mark Slee36bfa2e2007-01-19 20:09:51 +0000709 yylineno = 1;
Mark Slee30152872006-11-28 01:24:07 +0000710 if (yyparse() != 0) {
711 failure("Parser error during include pass.");
712 }
713 } catch (string x) {
714 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000715 }
716 fclose(yyin);
717
718 // Recursively parse all the include programs
719 vector<t_program*>& includes = program->get_includes();
720 vector<t_program*>::iterator iter;
721 for (iter = includes.begin(); iter != includes.end(); ++iter) {
722 parse(*iter, program);
723 }
724
725 // Parse the program the file
726 g_parse_mode = PROGRAM;
727 g_program = program;
728 g_scope = program->scope();
729 g_parent_scope = (parent_program != NULL) ? parent_program->scope() : NULL;
730 g_parent_prefix = program->get_name() + ".";
731 g_curpath = path;
732 yyin = fopen(path.c_str(), "r");
733 if (yyin == 0) {
734 failure("Could not open input file: \"%s\"", path.c_str());
735 }
736 pverbose("Parsing %s for types\n", path.c_str());
Mark Slee36bfa2e2007-01-19 20:09:51 +0000737 yylineno = 1;
David Reiss877237a2007-07-27 00:40:19 +0000738 try {
739 if (yyparse() != 0) {
740 failure("Parser error during types pass.");
741 }
742 } catch (string x) {
743 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000744 }
745 fclose(yyin);
746}
747
748/**
749 * Generate code
750 */
751void generate(t_program* program) {
752 // Oooohh, recursive code generation, hot!!
753 if (gen_recurse) {
754 const vector<t_program*>& includes = program->get_includes();
755 for (size_t i = 0; i < includes.size(); ++i) {
756 generate(includes[i]);
757 }
758 }
759
760 // Generate code!
761 try {
762 pverbose("Program: %s\n", program->get_path().c_str());
763
David Reiss18bf22d2007-08-28 20:49:17 +0000764 // Compute fingerprints.
765 generate_all_fingerprints(program);
766
Mark Sleef0712dc2006-10-25 19:03:57 +0000767 if (gen_cpp) {
768 pverbose("Generating C++\n");
769 t_cpp_generator* cpp = new t_cpp_generator(program);
770 cpp->generate_program();
771 delete cpp;
772 }
773
774 if (gen_java) {
775 pverbose("Generating Java\n");
776 t_java_generator* java = new t_java_generator(program);
777 java->generate_program();
778 delete java;
779 }
780
781 if (gen_php) {
782 pverbose("Generating PHP\n");
Mark Slee756b1d12007-07-06 00:30:21 +0000783 t_php_generator* php = new t_php_generator(program, false, gen_rest);
Mark Sleef0712dc2006-10-25 19:03:57 +0000784 php->generate_program();
785 delete php;
786 }
787
788 if (gen_phpi) {
789 pverbose("Generating PHP-inline\n");
Mark Slee756b1d12007-07-06 00:30:21 +0000790 t_php_generator* phpi = new t_php_generator(program, true, gen_rest);
Mark Sleef0712dc2006-10-25 19:03:57 +0000791 phpi->generate_program();
792 delete phpi;
793 }
794
795 if (gen_py) {
796 pverbose("Generating Python\n");
797 t_py_generator* py = new t_py_generator(program);
798 py->generate_program();
799 delete py;
800 }
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000801
Mark Slee6d7d5952007-01-27 01:44:22 +0000802 if (gen_rb) {
803 pverbose("Generating Ruby\n");
804 t_rb_generator* rb = new t_rb_generator(program);
805 rb->generate_program();
806 delete rb;
807 }
808
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000809 if (gen_xsd) {
810 pverbose("Generating XSD\n");
811 t_xsd_generator* xsd = new t_xsd_generator(program);
812 xsd->generate_program();
813 delete xsd;
814 }
815
Mark Slee2c44d202007-05-16 02:18:07 +0000816 if (gen_perl) {
817 pverbose("Generating PERL\n");
818 t_perl_generator* perl = new t_perl_generator(program);
819 perl->generate_program();
820 delete perl;
821 }
822
iproctor9a41a0c2007-07-16 21:59:24 +0000823 if (gen_ocaml) {
824 pverbose("Generating OCaml\n");
825 t_ocaml_generator* ocaml = new t_ocaml_generator(program);
826 ocaml->generate_program();
827 delete ocaml;
828 }
829
Christopher Piro2f5afce2007-06-29 07:17:33 +0000830 if (gen_erl) {
831 pverbose("Generating Erlang\n");
832 t_erl_generator* erl = new t_erl_generator(program);
833 erl->generate_program();
834 delete erl;
835 }
iproctorff8eb922007-07-25 19:06:13 +0000836 if (gen_hs) {
837 pverbose("Generating Haskell\n");
838 t_hs_generator* hs = new t_hs_generator(program);
839 hs->generate_program();
840 delete hs;
841 }
David Reiss1ac05802007-07-30 22:00:27 +0000842 if (dump_docs) {
843 dump_docstrings(program);
844 }
iproctor9a41a0c2007-07-16 21:59:24 +0000845
Mark Sleef0712dc2006-10-25 19:03:57 +0000846 } catch (string s) {
847 printf("Error: %s\n", s.c_str());
848 } catch (const char* exc) {
849 printf("Error: %s\n", exc);
850 }
851
852}
853
854/**
Mark Sleef5377b32006-10-10 01:42:59 +0000855 * Parse it up.. then spit it back out, in pretty much every language. Alright
856 * not that many languages, but the cool ones that we care about.
Mark Slee31985722006-05-24 21:45:31 +0000857 */
858int main(int argc, char** argv) {
859 int i;
Mark Sleef5377b32006-10-10 01:42:59 +0000860
Mark Sleeb15a68b2006-06-07 06:46:24 +0000861 // Setup time string
862 time_t now = time(NULL);
863 g_time_str = ctime(&now);
Mark Slee31985722006-05-24 21:45:31 +0000864
Mark Sleef0712dc2006-10-25 19:03:57 +0000865 // Check for necessary arguments, you gotta have at least a filename and
866 // an output language flag
Mark Sleeb15a68b2006-06-07 06:46:24 +0000867 if (argc < 2) {
868 usage();
869 }
Mark Slee31985722006-05-24 21:45:31 +0000870
Mark Sleef5377b32006-10-10 01:42:59 +0000871 // Hacky parameter handling... I didn't feel like using a library sorry!
Mark Slee31985722006-05-24 21:45:31 +0000872 for (i = 1; i < argc-1; i++) {
Mark Sleefdbee812006-09-27 18:50:48 +0000873 char* arg;
Mark Slee2329a832006-11-09 00:23:30 +0000874
Mark Sleefdbee812006-09-27 18:50:48 +0000875 arg = strtok(argv[i], " ");
876 while (arg != NULL) {
Mark Slee2329a832006-11-09 00:23:30 +0000877 // Treat double dashes as single dashes
Mark Slee52cb2232006-11-10 22:32:07 +0000878 if (arg[0] == '-' && arg[1] == '-') {
Mark Slee2329a832006-11-09 00:23:30 +0000879 ++arg;
880 }
881
882 if (strcmp(arg, "-debug") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000883 g_debug = 1;
Mark Slee2329a832006-11-09 00:23:30 +0000884 } else if (strcmp(arg, "-nowarn") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000885 g_warn = 0;
Mark Slee2329a832006-11-09 00:23:30 +0000886 } else if (strcmp(arg, "-strict") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000887 g_warn = 2;
Mark Slee2329a832006-11-09 00:23:30 +0000888 } else if (strcmp(arg, "-v") == 0 || strcmp(arg, "-verbose") == 0 ) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000889 g_verbose = 1;
Mark Slee2329a832006-11-09 00:23:30 +0000890 } else if (strcmp(arg, "-r") == 0 || strcmp(arg, "-recurse") == 0 ) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000891 gen_recurse = true;
Mark Slee2329a832006-11-09 00:23:30 +0000892 } else if (strcmp(arg, "-cpp") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000893 gen_cpp = true;
Mark Slee2329a832006-11-09 00:23:30 +0000894 } else if (strcmp(arg, "-java") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000895 gen_java = true;
Mark Slee2329a832006-11-09 00:23:30 +0000896 } else if (strcmp(arg, "-php") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000897 gen_php = true;
Mark Slee2329a832006-11-09 00:23:30 +0000898 } else if (strcmp(arg, "-phpi") == 0) {
Mark Sleef5377b32006-10-10 01:42:59 +0000899 gen_phpi = true;
Mark Slee756b1d12007-07-06 00:30:21 +0000900 } else if (strcmp(arg, "-rest") == 0) {
901 gen_rest = true;
Mark Slee2329a832006-11-09 00:23:30 +0000902 } else if (strcmp(arg, "-py") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +0000903 gen_py = true;
Mark Slee6d7d5952007-01-27 01:44:22 +0000904 } else if (strcmp(arg, "-rb") == 0) {
905 gen_rb = true;
Mark Slee0e0ff7e2007-01-18 22:59:59 +0000906 } else if (strcmp(arg, "-xsd") == 0) {
907 gen_xsd = true;
Mark Slee2c44d202007-05-16 02:18:07 +0000908 } else if (strcmp(arg, "-perl") == 0) {
909 gen_perl = true;
iproctor9a41a0c2007-07-16 21:59:24 +0000910 } else if (strcmp(arg, "-ocaml") == 0) {
911 gen_ocaml = true;
Christopher Piro2f5afce2007-06-29 07:17:33 +0000912 } else if (strcmp(arg, "-erl") == 0) {
913 gen_erl = true;
iproctorff8eb922007-07-25 19:06:13 +0000914 } else if (strcmp(arg, "-hs") == 0) {
915 gen_hs = true;
Martin Kraemer32c66e12006-11-09 00:06:36 +0000916 } else if (strcmp(arg, "-I") == 0) {
917 // An argument of "-I\ asdf" is invalid and has unknown results
918 arg = argv[++i];
919
920 if (arg == NULL) {
921 fprintf(stderr, "!!! Missing Include directory");
922 usage();
923 }
924 g_incl_searchpath.push_back(arg);
Mark Sleefdbee812006-09-27 18:50:48 +0000925 } else {
926 fprintf(stderr, "!!! Unrecognized option: %s\n", arg);
927 usage();
928 }
929
930 // Tokenize more
931 arg = strtok(NULL, " ");
Mark Slee31985722006-05-24 21:45:31 +0000932 }
933 }
Mark Slee2c44d202007-05-16 02:18:07 +0000934
Mark Sleef0712dc2006-10-25 19:03:57 +0000935 // You gotta generate something!
iproctorff8eb922007-07-25 19:06:13 +0000936 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 +0000937 fprintf(stderr, "!!! No output language(s) specified\n\n");
938 usage();
939 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000940
941 // Real-pathify it
942 char rp[PATH_MAX];
943 if (realpath(argv[i], rp) == NULL) {
944 failure("Could not open input file: %s", argv[i]);
Mark Slee31985722006-05-24 21:45:31 +0000945 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000946 string input_file(rp);
947
Mark Sleef5377b32006-10-10 01:42:59 +0000948 // Instance of the global parse tree
Mark Sleef0712dc2006-10-25 19:03:57 +0000949 t_program* program = new t_program(input_file);
950
951 // Initialize global types
952 g_type_void = new t_base_type("void", t_base_type::TYPE_VOID);
953 g_type_string = new t_base_type("string", t_base_type::TYPE_STRING);
Mark Slee8d725a22007-04-13 01:57:12 +0000954 g_type_binary = new t_base_type("string", t_base_type::TYPE_STRING);
955 ((t_base_type*)g_type_binary)->set_binary(true);
Mark Sleeb6200d82007-01-19 19:14:36 +0000956 g_type_slist = new t_base_type("string", t_base_type::TYPE_STRING);
957 ((t_base_type*)g_type_slist)->set_string_list(true);
Mark Sleef0712dc2006-10-25 19:03:57 +0000958 g_type_bool = new t_base_type("bool", t_base_type::TYPE_BOOL);
959 g_type_byte = new t_base_type("byte", t_base_type::TYPE_BYTE);
960 g_type_i16 = new t_base_type("i16", t_base_type::TYPE_I16);
961 g_type_i32 = new t_base_type("i32", t_base_type::TYPE_I32);
962 g_type_i64 = new t_base_type("i64", t_base_type::TYPE_I64);
963 g_type_double = new t_base_type("double", t_base_type::TYPE_DOUBLE);
Mark Sleee8540632006-05-30 09:24:40 +0000964
Mark Sleef5377b32006-10-10 01:42:59 +0000965 // Parse it!
Mark Sleef0712dc2006-10-25 19:03:57 +0000966 parse(program, NULL);
Mark Slee31985722006-05-24 21:45:31 +0000967
Mark Sleef0712dc2006-10-25 19:03:57 +0000968 // Generate it!
969 generate(program);
Mark Sleeb15a68b2006-06-07 06:46:24 +0000970
Mark Sleef0712dc2006-10-25 19:03:57 +0000971 // Clean up. Who am I kidding... this program probably orphans heap memory
972 // all over the place, but who cares because it is about to exit and it is
973 // all referenced and used by this wacky parse tree up until now anyways.
Mark Sleeb15a68b2006-06-07 06:46:24 +0000974
Mark Sleef0712dc2006-10-25 19:03:57 +0000975 delete program;
976 delete g_type_void;
977 delete g_type_string;
978 delete g_type_bool;
979 delete g_type_byte;
980 delete g_type_i16;
981 delete g_type_i32;
982 delete g_type_i64;
983 delete g_type_double;
Mark Slee31985722006-05-24 21:45:31 +0000984
985 // Finished
Mark Slee31985722006-05-24 21:45:31 +0000986 return 0;
987}