r1317@opsdev009 (orig r70384): mcslee | 2007-11-16 16:32:36 -0800
[amiethrift.git] / compiler / cpp / src / main.cc
blob0b904ea4032721566d90da350466ac6b87280f40
1 // 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/
7 /**
8 * thrift - a lightweight cross-language rpc/serialization tool
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
12 * code for each language lives in a file by the language name under the
13 * generate/ folder, and all parse structures live in parse/
15 * @author Mark Slee <mcslee@facebook.com>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <stdarg.h>
21 #include <string>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <errno.h>
26 // Careful: must include globals first for extern definitions
27 #include "globals.h"
29 #include "main.h"
30 #include "parse/t_program.h"
31 #include "parse/t_scope.h"
32 #include "generate/t_cpp_generator.h"
33 #include "generate/t_java_generator.h"
34 #include "generate/t_php_generator.h"
35 #include "generate/t_py_generator.h"
36 #include "generate/t_rb_generator.h"
37 #include "generate/t_xsd_generator.h"
38 #include "generate/t_perl_generator.h"
39 #include "generate/t_erl_generator.h"
40 #include "generate/t_ocaml_generator.h"
41 #include "generate/t_hs_generator.h"
42 #include "generate/t_cocoa_generator.h"
44 using namespace std;
46 /**
47 * Global program tree
49 t_program* g_program;
51 /**
52 * Global types
55 t_type* g_type_void;
56 t_type* g_type_string;
57 t_type* g_type_binary;
58 t_type* g_type_slist;
59 t_type* g_type_bool;
60 t_type* g_type_byte;
61 t_type* g_type_i16;
62 t_type* g_type_i32;
63 t_type* g_type_i64;
64 t_type* g_type_double;
66 /**
67 * Global scope
69 t_scope* g_scope;
71 /**
72 * Parent scope to also parse types
74 t_scope* g_parent_scope;
76 /**
77 * Prefix for putting types in parent scope
79 string g_parent_prefix;
81 /**
82 * Parsing pass
84 PARSE_MODE g_parse_mode;
86 /**
87 * Current directory of file being parsed
89 string g_curdir;
91 /**
92 * Current file being parsed
94 string g_curpath;
96 /**
97 * Search path for inclusions
99 vector<string> g_incl_searchpath;
102 * Global debug state
104 int g_debug = 0;
107 * Warning level
109 int g_warn = 1;
112 * Verbose output
114 int g_verbose = 0;
117 * Global time string
119 char* g_time_str;
122 * The last parsed doctext comment.
124 char* g_doctext;
127 * The location of the last parsed doctext comment.
129 int g_doctext_lineno;
132 * Flags to control code generation
134 bool gen_cpp = false;
135 bool gen_java = false;
136 bool gen_javabean = false;
137 bool gen_rb = false;
138 bool gen_py = false;
139 bool gen_xsd = false;
140 bool gen_php = false;
141 bool gen_phpi = false;
142 bool gen_phps = true;
143 bool gen_phpa = false;
144 bool gen_rest = false;
145 bool gen_perl = false;
146 bool gen_erl = false;
147 bool gen_ocaml = false;
148 bool gen_hs = false;
149 bool gen_cocoa = false;
150 bool gen_dense = false;
151 bool gen_recurse = false;
154 * Report an error to the user. This is called yyerror for historical
155 * reasons (lex and yacc expect the error reporting routine to be called
156 * this). Call this function to report any errors to the user.
157 * yyerror takes printf style arguments.
159 * @param fmt C format string followed by additional arguments
161 void yyerror(char* fmt, ...) {
162 va_list args;
163 fprintf(stderr,
164 "[ERROR:%s:%d] (last token was '%s')\n",
165 g_curpath.c_str(),
166 yylineno,
167 yytext);
169 va_start(args, fmt);
170 vfprintf(stderr, fmt, args);
171 va_end(args);
173 fprintf(stderr, "\n");
177 * Prints a debug message from the parser.
179 * @param fmt C format string followed by additional arguments
181 void pdebug(char* fmt, ...) {
182 if (g_debug == 0) {
183 return;
185 va_list args;
186 printf("[PARSE:%d] ", yylineno);
187 va_start(args, fmt);
188 vprintf(fmt, args);
189 va_end(args);
190 printf("\n");
194 * Prints a verbose output mode message
196 * @param fmt C format string followed by additional arguments
198 void pverbose(char* fmt, ...) {
199 if (g_verbose == 0) {
200 return;
202 va_list args;
203 va_start(args, fmt);
204 vprintf(fmt, args);
205 va_end(args);
209 * Prints a warning message
211 * @param fmt C format string followed by additional arguments
213 void pwarning(int level, char* fmt, ...) {
214 if (g_warn < level) {
215 return;
217 va_list args;
218 printf("[WARNING:%s:%d] ", g_curpath.c_str(), yylineno);
219 va_start(args, fmt);
220 vprintf(fmt, args);
221 va_end(args);
222 printf("\n");
226 * Prints a failure message and exits
228 * @param fmt C format string followed by additional arguments
230 void failure(const char* fmt, ...) {
231 va_list args;
232 fprintf(stderr, "[FAILURE:%s:%d] ", g_curpath.c_str(), yylineno);
233 va_start(args, fmt);
234 vfprintf(stderr, fmt, args);
235 va_end(args);
236 printf("\n");
237 exit(1);
241 * Converts a string filename into a thrift program name
243 string program_name(string filename) {
244 string::size_type slash = filename.rfind("/");
245 if (slash != string::npos) {
246 filename = filename.substr(slash+1);
248 string::size_type dot = filename.rfind(".");
249 if (dot != string::npos) {
250 filename = filename.substr(0, dot);
252 return filename;
256 * Gets the directory path of a filename
258 string directory_name(string filename) {
259 string::size_type slash = filename.rfind("/");
260 // No slash, just use the current directory
261 if (slash == string::npos) {
262 return ".";
264 return filename.substr(0, slash);
268 * Finds the appropriate file path for the given filename
270 string include_file(string filename) {
271 // Absolute path? Just try that
272 if (filename[0] == '/') {
273 // Realpath!
274 char rp[PATH_MAX];
275 if (realpath(filename.c_str(), rp) == NULL) {
276 pwarning(0, "Cannot open include file %s\n", filename.c_str());
277 return std::string();
280 // Stat this file
281 struct stat finfo;
282 if (stat(rp, &finfo) == 0) {
283 return rp;
285 } else { // relative path, start searching
286 // new search path with current dir global
287 vector<string> sp = g_incl_searchpath;
288 sp.insert(sp.begin(), g_curdir);
290 // iterate through paths
291 vector<string>::iterator it;
292 for (it = sp.begin(); it != sp.end(); it++) {
293 string sfilename = *(it) + "/" + filename;
295 // Realpath!
296 char rp[PATH_MAX];
297 if (realpath(sfilename.c_str(), rp) == NULL) {
298 continue;
301 // Stat this files
302 struct stat finfo;
303 if (stat(rp, &finfo) == 0) {
304 return rp;
309 // Uh oh
310 pwarning(0, "Could not find include file %s\n", filename.c_str());
311 return std::string();
315 * Clears any previously stored doctext string.
316 * Also prints a warning if we are discarding information.
318 void clear_doctext() {
319 if (g_doctext != NULL) {
320 pwarning(2, "Uncaptured doctext at on line %d.", g_doctext_lineno);
322 free(g_doctext);
323 g_doctext = NULL;
327 * Cleans up text commonly found in doxygen-like comments
329 * Warning: if you mix tabs and spaces in a non-uniform way,
330 * you will get what you deserve.
332 char* clean_up_doctext(char* doctext) {
333 // Convert to C++ string, and remove Windows's carriage returns.
334 string docstring = doctext;
335 docstring.erase(
336 remove(docstring.begin(), docstring.end(), '\r'),
337 docstring.end());
339 // Separate into lines.
340 vector<string> lines;
341 string::size_type pos = string::npos;
342 string::size_type last;
343 while (true) {
344 last = (pos == string::npos) ? 0 : pos+1;
345 pos = docstring.find('\n', last);
346 if (pos == string::npos) {
347 // First bit of cleaning. If the last line is only whitespace, drop it.
348 string::size_type nonwhite = docstring.find_first_not_of(" \t", last);
349 if (nonwhite != string::npos) {
350 lines.push_back(docstring.substr(last));
352 break;
354 lines.push_back(docstring.substr(last, pos-last));
357 // A very profound docstring.
358 if (lines.empty()) {
359 return NULL;
362 // Clear leading whitespace from the first line.
363 pos = lines.front().find_first_not_of(" \t");
364 lines.front().erase(0, pos);
366 // If every nonblank line after the first has the same number of spaces/tabs,
367 // then a star, remove them.
368 bool have_prefix = true;
369 bool found_prefix = false;
370 string::size_type prefix_len = 0;
371 vector<string>::iterator l_iter;
372 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
373 if (l_iter->empty()) {
374 continue;
377 pos = l_iter->find_first_not_of(" \t");
378 if (!found_prefix) {
379 if (pos != string::npos) {
380 if (l_iter->at(pos) == '*') {
381 found_prefix = true;
382 prefix_len = pos;
383 } else {
384 have_prefix = false;
385 break;
387 } else {
388 // Whitespace-only line. Truncate it.
389 l_iter->clear();
391 } else if (l_iter->size() > pos
392 && l_iter->at(pos) == '*'
393 && pos == prefix_len) {
394 // Business as usual.
395 } else if (pos == string::npos) {
396 // Whitespace-only line. Let's truncate it for them.
397 l_iter->clear();
398 } else {
399 // The pattern has been broken.
400 have_prefix = false;
401 break;
405 // If our prefix survived, delete it from every line.
406 if (have_prefix) {
407 // Get the star too.
408 prefix_len++;
409 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
410 l_iter->erase(0, prefix_len);
414 // Now delete the minimum amount of leading whitespace from each line.
415 prefix_len = string::npos;
416 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
417 if (l_iter->empty()) {
418 continue;
420 pos = l_iter->find_first_not_of(" \t");
421 if (pos != string::npos
422 && (prefix_len == string::npos || pos < prefix_len)) {
423 prefix_len = pos;
427 // If our prefix survived, delete it from every line.
428 if (prefix_len != string::npos) {
429 for (l_iter = lines.begin()+1; l_iter != lines.end(); ++l_iter) {
430 l_iter->erase(0, prefix_len);
434 // Remove trailing whitespace from every line.
435 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
436 pos = l_iter->find_last_not_of(" \t");
437 if (pos != string::npos && pos != l_iter->length()-1) {
438 l_iter->erase(pos+1);
442 // If the first line is empty, remove it.
443 // Don't do this earlier because a lot of steps skip the first line.
444 if (lines.front().empty()) {
445 lines.erase(lines.begin());
448 // Now rejoin the lines and copy them back into doctext.
449 docstring.clear();
450 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
451 docstring += *l_iter;
452 docstring += '\n';
455 assert(docstring.length() <= strlen(doctext));
456 strcpy(doctext, docstring.c_str());
457 return doctext;
460 /** Set to true to debug docstring parsing */
461 static bool dump_docs = false;
464 * Dumps docstrings to stdout
465 * Only works for top-level definitions and the whole program doc
466 * (i.e., not enum constants, struct fields, or functions.
468 void dump_docstrings(t_program* program) {
469 string progdoc = program->get_doc();
470 if (!progdoc.empty()) {
471 printf("Whole program doc:\n%s\n", progdoc.c_str());
473 const vector<t_typedef*>& typedefs = program->get_typedefs();
474 vector<t_typedef*>::const_iterator t_iter;
475 for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {
476 t_typedef* td = *t_iter;
477 if (td->has_doc()) {
478 printf("typedef %s:\n%s\n", td->get_name().c_str(), td->get_doc().c_str());
481 const vector<t_enum*>& enums = program->get_enums();
482 vector<t_enum*>::const_iterator e_iter;
483 for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {
484 t_enum* en = *e_iter;
485 if (en->has_doc()) {
486 printf("enum %s:\n%s\n", en->get_name().c_str(), en->get_doc().c_str());
489 const vector<t_const*>& consts = program->get_consts();
490 vector<t_const*>::const_iterator c_iter;
491 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
492 t_const* co = *c_iter;
493 if (co->has_doc()) {
494 printf("const %s:\n%s\n", co->get_name().c_str(), co->get_doc().c_str());
497 const vector<t_struct*>& structs = program->get_structs();
498 vector<t_struct*>::const_iterator s_iter;
499 for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
500 t_struct* st = *s_iter;
501 if (st->has_doc()) {
502 printf("struct %s:\n%s\n", st->get_name().c_str(), st->get_doc().c_str());
505 const vector<t_struct*>& xceptions = program->get_xceptions();
506 vector<t_struct*>::const_iterator x_iter;
507 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
508 t_struct* xn = *x_iter;
509 if (xn->has_doc()) {
510 printf("xception %s:\n%s\n", xn->get_name().c_str(), xn->get_doc().c_str());
513 const vector<t_service*>& services = program->get_services();
514 vector<t_service*>::const_iterator v_iter;
515 for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
516 t_service* sv = *v_iter;
517 if (sv->has_doc()) {
518 printf("service %s:\n%s\n", sv->get_name().c_str(), sv->get_doc().c_str());
524 * Call generate_fingerprint for every structure.
526 void generate_all_fingerprints(t_program* program) {
527 const vector<t_struct*>& structs = program->get_structs();
528 vector<t_struct*>::const_iterator s_iter;
529 for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
530 t_struct* st = *s_iter;
531 st->generate_fingerprint();
534 const vector<t_struct*>& xceptions = program->get_xceptions();
535 vector<t_struct*>::const_iterator x_iter;
536 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
537 t_struct* st = *x_iter;
538 st->generate_fingerprint();
541 g_type_void->generate_fingerprint();
543 // If you want to generate fingerprints for implicit structures, start here.
545 const vector<t_service*>& services = program->get_services();
546 vector<t_service*>::const_iterator v_iter;
547 for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
548 t_service* sv = *v_iter;
554 * Diplays the usage message and then exits with an error code.
556 void usage() {
557 fprintf(stderr, "Usage: thrift [options] file\n");
558 fprintf(stderr, "Options:\n");
559 fprintf(stderr, " -cpp Generate C++ output files\n");
560 fprintf(stderr, " -java Generate Java output files\n");
561 fprintf(stderr, " -javabean Generate Java bean-style output files\n");
562 fprintf(stderr, " -php Generate PHP output files\n");
563 fprintf(stderr, " -phpi Generate PHP inlined files\n");
564 fprintf(stderr, " -phps Generate PHP server stubs (with -php)\n");
565 fprintf(stderr, " -phpl Generate PHP-lite (with -php)\n");
566 fprintf(stderr, " -phpa Generate PHP with autoload (with -php)\n");
567 fprintf(stderr, " -py Generate Python output files\n");
568 fprintf(stderr, " -rb Generate Ruby output files\n");
569 fprintf(stderr, " -xsd Generate XSD output files\n");
570 fprintf(stderr, " -perl Generate Perl output files\n");
571 fprintf(stderr, " -erl Generate Erlang output files\n");
572 fprintf(stderr, " -ocaml Generate OCaml output files\n");
573 fprintf(stderr, " -hs Generate Haskell output files\n");
574 fprintf(stderr, " -cocoa Generate Cocoa/Objective-C output files\n");
575 fprintf(stderr, " -o dir Set the output directory for gen-* packages\n");
576 fprintf(stderr, " (default: current directory)\n");
577 fprintf(stderr, " -I dir Add a directory to the list of directories\n");
578 fprintf(stderr, " searched for include directives\n");
579 fprintf(stderr, " -dense Generate metadata for TDenseProtocol (C++)\n");
580 fprintf(stderr, " -rest Generate PHP REST processors (with -php)\n");
581 fprintf(stderr, " -nowarn Suppress all compiler warnings (BAD!)\n");
582 fprintf(stderr, " -strict Strict compiler warnings on\n");
583 fprintf(stderr, " -v[erbose] Verbose mode\n");
584 fprintf(stderr, " -r[ecurse] Also generate included files\n");
585 fprintf(stderr, " -debug Parse debug trace to stdout\n");
586 exit(1);
590 * You know, when I started working on Thrift I really thought it wasn't going
591 * to become a programming language because it was just a generator and it
592 * wouldn't need runtime type information and all that jazz. But then we
593 * decided to add constants, and all of a sudden that means runtime type
594 * validation and inference, except the "runtime" is the code generator
595 * runtime. Shit. I've been had.
597 void validate_const_rec(std::string name, t_type* type, t_const_value* value) {
598 if (type->is_void()) {
599 throw "type error: cannot declare a void const: " + name;
602 if (type->is_base_type()) {
603 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
604 switch (tbase) {
605 case t_base_type::TYPE_STRING:
606 if (value->get_type() != t_const_value::CV_STRING) {
607 throw "type error: const \"" + name + "\" was declared as string";
609 break;
610 case t_base_type::TYPE_BOOL:
611 if (value->get_type() != t_const_value::CV_INTEGER) {
612 throw "type error: const \"" + name + "\" was declared as bool";
614 break;
615 case t_base_type::TYPE_BYTE:
616 if (value->get_type() != t_const_value::CV_INTEGER) {
617 throw "type error: const \"" + name + "\" was declared as byte";
619 break;
620 case t_base_type::TYPE_I16:
621 if (value->get_type() != t_const_value::CV_INTEGER) {
622 throw "type error: const \"" + name + "\" was declared as i16";
624 break;
625 case t_base_type::TYPE_I32:
626 if (value->get_type() != t_const_value::CV_INTEGER) {
627 throw "type error: const \"" + name + "\" was declared as i32";
629 break;
630 case t_base_type::TYPE_I64:
631 if (value->get_type() != t_const_value::CV_INTEGER) {
632 throw "type error: const \"" + name + "\" was declared as i64";
634 break;
635 case t_base_type::TYPE_DOUBLE:
636 if (value->get_type() != t_const_value::CV_INTEGER &&
637 value->get_type() != t_const_value::CV_DOUBLE) {
638 throw "type error: const \"" + name + "\" was declared as double";
640 break;
641 default:
642 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase) + name;
644 } else if (type->is_enum()) {
645 if (value->get_type() != t_const_value::CV_INTEGER) {
646 throw "type error: const \"" + name + "\" was declared as enum";
648 } else if (type->is_struct() || type->is_xception()) {
649 if (value->get_type() != t_const_value::CV_MAP) {
650 throw "type error: const \"" + name + "\" was declared as struct/xception";
652 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
653 vector<t_field*>::const_iterator f_iter;
655 const map<t_const_value*, t_const_value*>& val = value->get_map();
656 map<t_const_value*, t_const_value*>::const_iterator v_iter;
657 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
658 if (v_iter->first->get_type() != t_const_value::CV_STRING) {
659 throw "type error: " + name + " struct key must be string";
661 t_type* field_type = NULL;
662 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
663 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
664 field_type = (*f_iter)->get_type();
667 if (field_type == NULL) {
668 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
671 validate_const_rec(name + "." + v_iter->first->get_string(), field_type, v_iter->second);
673 } else if (type->is_map()) {
674 t_type* k_type = ((t_map*)type)->get_key_type();
675 t_type* v_type = ((t_map*)type)->get_val_type();
676 const map<t_const_value*, t_const_value*>& val = value->get_map();
677 map<t_const_value*, t_const_value*>::const_iterator v_iter;
678 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
679 validate_const_rec(name + "<key>", k_type, v_iter->first);
680 validate_const_rec(name + "<val>", v_type, v_iter->second);
682 } else if (type->is_list() || type->is_set()) {
683 t_type* e_type;
684 if (type->is_list()) {
685 e_type = ((t_list*)type)->get_elem_type();
686 } else {
687 e_type = ((t_set*)type)->get_elem_type();
689 const vector<t_const_value*>& val = value->get_list();
690 vector<t_const_value*>::const_iterator v_iter;
691 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
692 validate_const_rec(name + "<elem>", e_type, *v_iter);
698 * Check the type of the parsed const information against its declared type
700 void validate_const_type(t_const* c) {
701 validate_const_rec(c->get_name(), c->get_type(), c->get_value());
705 * Check the type of a default value assigned to a field.
707 void validate_field_value(t_field* field, t_const_value* cv) {
708 validate_const_rec(field->get_name(), field->get_type(), cv);
712 * Parses a program
714 void parse(t_program* program, t_program* parent_program) {
715 // Get scope file path
716 string path = program->get_path();
718 // Set current dir global, which is used in the include_file function
719 g_curdir = directory_name(path);
720 g_curpath = path;
722 // Open the file
723 yyin = fopen(path.c_str(), "r");
724 if (yyin == 0) {
725 failure("Could not open input file: \"%s\"", path.c_str());
728 // Create new scope and scan for includes
729 pverbose("Scanning %s for includes\n", path.c_str());
730 g_parse_mode = INCLUDES;
731 g_program = program;
732 g_scope = program->scope();
733 try {
734 yylineno = 1;
735 if (yyparse() != 0) {
736 failure("Parser error during include pass.");
738 } catch (string x) {
739 failure(x.c_str());
741 fclose(yyin);
743 // Recursively parse all the include programs
744 vector<t_program*>& includes = program->get_includes();
745 vector<t_program*>::iterator iter;
746 for (iter = includes.begin(); iter != includes.end(); ++iter) {
747 parse(*iter, program);
750 // Parse the program the file
751 g_parse_mode = PROGRAM;
752 g_program = program;
753 g_scope = program->scope();
754 g_parent_scope = (parent_program != NULL) ? parent_program->scope() : NULL;
755 g_parent_prefix = program->get_name() + ".";
756 g_curpath = path;
757 yyin = fopen(path.c_str(), "r");
758 if (yyin == 0) {
759 failure("Could not open input file: \"%s\"", path.c_str());
761 pverbose("Parsing %s for types\n", path.c_str());
762 yylineno = 1;
763 try {
764 if (yyparse() != 0) {
765 failure("Parser error during types pass.");
767 } catch (string x) {
768 failure(x.c_str());
770 fclose(yyin);
774 * Generate code
776 void generate(t_program* program) {
777 // Oooohh, recursive code generation, hot!!
778 if (gen_recurse) {
779 const vector<t_program*>& includes = program->get_includes();
780 for (size_t i = 0; i < includes.size(); ++i) {
781 // Propogate output path from parent to child programs
782 includes[i]->set_out_path(program->get_out_path());
784 generate(includes[i]);
788 // Generate code!
789 try {
790 pverbose("Program: %s\n", program->get_path().c_str());
792 // Compute fingerprints.
793 generate_all_fingerprints(program);
795 if (gen_cpp) {
796 pverbose("Generating C++\n");
797 t_cpp_generator* cpp = new t_cpp_generator(program, gen_dense);
798 cpp->generate_program();
799 delete cpp;
802 if (gen_java) {
803 pverbose("Generating Java\n");
804 t_java_generator* java = new t_java_generator(program, false);
805 java->generate_program();
806 delete java;
809 if (gen_javabean) {
810 pverbose("Generating Java Beans\n");
811 t_java_generator* java = new t_java_generator(program, true);
812 java->generate_program();
813 delete java;
816 if (gen_php) {
817 pverbose("Generating PHP\n");
818 t_php_generator* php = new t_php_generator(program, false, gen_rest, gen_phps, gen_phpa);
819 php->generate_program();
820 delete php;
823 if (gen_phpi) {
824 pverbose("Generating PHP-inline\n");
825 t_php_generator* phpi = new t_php_generator(program, true, gen_rest);
826 phpi->generate_program();
827 delete phpi;
830 if (gen_py) {
831 pverbose("Generating Python\n");
832 t_py_generator* py = new t_py_generator(program);
833 py->generate_program();
834 delete py;
837 if (gen_rb) {
838 pverbose("Generating Ruby\n");
839 t_rb_generator* rb = new t_rb_generator(program);
840 rb->generate_program();
841 delete rb;
844 if (gen_xsd) {
845 pverbose("Generating XSD\n");
846 t_xsd_generator* xsd = new t_xsd_generator(program);
847 xsd->generate_program();
848 delete xsd;
851 if (gen_perl) {
852 pverbose("Generating PERL\n");
853 t_perl_generator* perl = new t_perl_generator(program);
854 perl->generate_program();
855 delete perl;
858 if (gen_erl) {
859 pverbose("Generating Erlang\n");
860 t_erl_generator* erl = new t_erl_generator(program);
861 erl->generate_program();
862 delete erl;
865 if (gen_ocaml) {
866 pverbose("Generating OCaml\n");
867 t_ocaml_generator* ocaml = new t_ocaml_generator(program);
868 ocaml->generate_program();
869 delete ocaml;
872 if (gen_hs) {
873 pverbose("Generating Haskell\n");
874 t_hs_generator* hs = new t_hs_generator(program);
875 hs->generate_program();
876 delete hs;
879 if (gen_cocoa) {
880 pverbose("Generating Cocoa/Objective-C\n");
881 t_cocoa_generator* cocoa = new t_cocoa_generator(program);
882 cocoa->generate_program();
883 delete cocoa;
886 if (dump_docs) {
887 dump_docstrings(program);
889 } catch (string s) {
890 printf("Error: %s\n", s.c_str());
891 } catch (const char* exc) {
892 printf("Error: %s\n", exc);
898 * Parse it up.. then spit it back out, in pretty much every language. Alright
899 * not that many languages, but the cool ones that we care about.
901 int main(int argc, char** argv) {
902 int i;
903 std::string out_path;
905 // Setup time string
906 time_t now = time(NULL);
907 g_time_str = ctime(&now);
909 // Check for necessary arguments, you gotta have at least a filename and
910 // an output language flag
911 if (argc < 2) {
912 usage();
915 // Hacky parameter handling... I didn't feel like using a library sorry!
916 for (i = 1; i < argc-1; i++) {
917 char* arg;
919 arg = strtok(argv[i], " ");
920 while (arg != NULL) {
921 // Treat double dashes as single dashes
922 if (arg[0] == '-' && arg[1] == '-') {
923 ++arg;
926 if (strcmp(arg, "-debug") == 0) {
927 g_debug = 1;
928 } else if (strcmp(arg, "-nowarn") == 0) {
929 g_warn = 0;
930 } else if (strcmp(arg, "-strict") == 0) {
931 g_warn = 2;
932 } else if (strcmp(arg, "-v") == 0 || strcmp(arg, "-verbose") == 0 ) {
933 g_verbose = 1;
934 } else if (strcmp(arg, "-r") == 0 || strcmp(arg, "-recurse") == 0 ) {
935 gen_recurse = true;
936 } else if (strcmp(arg, "-dense") == 0) {
937 gen_dense = true;
938 } else if (strcmp(arg, "-cpp") == 0) {
939 gen_cpp = true;
940 } else if (strcmp(arg, "-javabean") == 0) {
941 gen_javabean = true;
942 } else if (strcmp(arg, "-java") == 0) {
943 gen_java = true;
944 } else if (strcmp(arg, "-php") == 0) {
945 gen_php = true;
946 } else if (strcmp(arg, "-phpi") == 0) {
947 gen_phpi = true;
948 } else if (strcmp(arg, "-phps") == 0) {
949 if (!gen_php) {
950 gen_php = true;
952 gen_phps = true;
953 } else if (strcmp(arg, "-phpl") == 0) {
954 if (!gen_php) {
955 gen_php = true;
957 gen_phps = false;
958 } else if (strcmp(arg, "-phpa") == 0) {
959 if (!gen_php) {
960 gen_php = true;
961 gen_phps = false;
963 gen_phpa = true;
964 } else if (strcmp(arg, "-rest") == 0) {
965 gen_rest = true;
966 } else if (strcmp(arg, "-py") == 0) {
967 gen_py = true;
968 } else if (strcmp(arg, "-rb") == 0) {
969 gen_rb = true;
970 } else if (strcmp(arg, "-xsd") == 0) {
971 gen_xsd = true;
972 } else if (strcmp(arg, "-perl") == 0) {
973 gen_perl = true;
974 } else if (strcmp(arg, "-erl") == 0) {
975 gen_erl = true;
976 } else if (strcmp(arg, "-ocaml") == 0) {
977 gen_ocaml = true;
978 } else if (strcmp(arg, "-hs") == 0) {
979 gen_hs = true;
980 } else if (strcmp(arg, "-cocoa") == 0) {
981 gen_cocoa = true;
982 } else if (strcmp(arg, "-I") == 0) {
983 // An argument of "-I\ asdf" is invalid and has unknown results
984 arg = argv[++i];
986 if (arg == NULL) {
987 fprintf(stderr, "!!! Missing Include directory");
988 usage();
990 g_incl_searchpath.push_back(arg);
991 } else if (strcmp(arg, "-o") == 0) {
992 arg = argv[++i];
993 if (arg == NULL) {
994 fprintf(stderr, "-o: missing output directory");
995 usage();
997 out_path = arg;
998 struct stat sb;
999 if (stat(out_path.c_str(), &sb) < 0) {
1000 fprintf(stderr, "Output directory %s is unusable: %s\n", out_path.c_str(), strerror(errno));
1001 return -1;
1003 if (! S_ISDIR(sb.st_mode)) {
1004 fprintf(stderr, "Output directory %s exists but is not a directory\n", out_path.c_str());
1005 return -1;
1007 } else {
1008 fprintf(stderr, "!!! Unrecognized option: %s\n", arg);
1009 usage();
1012 // Tokenize more
1013 arg = strtok(NULL, " ");
1017 // You gotta generate something!
1018 if (!gen_cpp && !gen_java && !gen_javabean && !gen_php && !gen_phpi && !gen_py && !gen_rb && !gen_xsd && !gen_perl && !gen_erl && !gen_ocaml && !gen_hs && !gen_cocoa) {
1019 fprintf(stderr, "!!! No output language(s) specified\n\n");
1020 usage();
1023 // Real-pathify it
1024 char rp[PATH_MAX];
1025 if (realpath(argv[i], rp) == NULL) {
1026 failure("Could not open input file: %s", argv[i]);
1028 string input_file(rp);
1030 // Instance of the global parse tree
1031 t_program* program = new t_program(input_file);
1032 if (out_path.size()) {
1033 program->set_out_path(out_path);
1036 // Initialize global types
1037 g_type_void = new t_base_type("void", t_base_type::TYPE_VOID);
1038 g_type_string = new t_base_type("string", t_base_type::TYPE_STRING);
1039 g_type_binary = new t_base_type("string", t_base_type::TYPE_STRING);
1040 ((t_base_type*)g_type_binary)->set_binary(true);
1041 g_type_slist = new t_base_type("string", t_base_type::TYPE_STRING);
1042 ((t_base_type*)g_type_slist)->set_string_list(true);
1043 g_type_bool = new t_base_type("bool", t_base_type::TYPE_BOOL);
1044 g_type_byte = new t_base_type("byte", t_base_type::TYPE_BYTE);
1045 g_type_i16 = new t_base_type("i16", t_base_type::TYPE_I16);
1046 g_type_i32 = new t_base_type("i32", t_base_type::TYPE_I32);
1047 g_type_i64 = new t_base_type("i64", t_base_type::TYPE_I64);
1048 g_type_double = new t_base_type("double", t_base_type::TYPE_DOUBLE);
1050 // Parse it!
1051 parse(program, NULL);
1053 // Generate it!
1054 generate(program);
1056 // Clean up. Who am I kidding... this program probably orphans heap memory
1057 // all over the place, but who cares because it is about to exit and it is
1058 // all referenced and used by this wacky parse tree up until now anyways.
1060 delete program;
1061 delete g_type_void;
1062 delete g_type_string;
1063 delete g_type_bool;
1064 delete g_type_byte;
1065 delete g_type_i16;
1066 delete g_type_i32;
1067 delete g_type_i64;
1068 delete g_type_double;
1070 // Finished
1071 return 0;