allow to call a function defined later in the source
[bosc.git] / src / main.cpp
blob77f0bff401bef64fdb513cf056180b4209534070
1 #include <cstdio>
2 #include <cstdlib>
4 #include <stdexcept>
6 #include "ast.h"
7 #include "logging.h"
8 #include "compiler.h"
11 using namespace std;
13 extern "C"
15 int yyparse(void);
16 int yylex(void);
17 int yyparse(void);
18 int yyerror(const char*);
19 extern FILE* yyin;
22 extern Block *root;
24 static char _filename_to_del[PATH_MAX];
25 void kill_at_exit(void)
27 unlink(_filename_to_del);
30 /// Preprocess a file and return a pointer to the preprocessed data
31 FILE* preprocess_file(const char* filename)
33 char tmp[L_tmpnam+1];
34 char *ptr;
35 char cmdline[L_tmpnam+strlen(filename)+16];
36 char tmp2[PATH_MAX];
38 ptr = tmpnam(tmp);
39 if (!ptr)
40 throw runtime_error("unable to allocate temporary file");
41 if (getenv("TEMP")) {
42 strcpy(tmp2, getenv("TEMP"));
43 strcat(tmp2, ptr);
44 ptr = tmp2;
46 sprintf(cmdline, "cpp \"%s\" -o \"%s\"", filename, ptr);
47 LOG("running cpp: %s\n", cmdline);
48 if (system(cmdline) != 0)
49 throw runtime_error("unable to call cpp");
50 strcpy(_filename_to_del, ptr);
51 atexit(kill_at_exit);
52 return fopen(ptr, "r");
55 int main(int argc, char** argv)
57 try {
58 if (argc > 2)
59 throw runtime_error("bad command line, usage: bosc <filename>");
60 else if (argc == 2) {
61 if (strcmp("--", argv[1]) == 0)
62 yyin = stdin;
63 else {
64 FILE* test = fopen(argv[1], "r");
65 if (test) fclose(test);
66 else throw runtime_error("cannot open input file");
67 yyin = preprocess_file(argv[1]);
68 if (!yyin)
69 throw runtime_error("cannot run cpp");
72 else
73 yyin = stdin;
74 } catch(const runtime_error& e) {
75 fprintf(stderr, "runtime error: %s\n", e.what());
76 fclose(yyin);
77 return 1;
79 int retval = yyparse();
80 fclose(yyin);
81 simplify_ast(root);
82 constant_expression_optimization(root);
83 if (!tree_check_parents(root)) {
84 EPRINTF("internal error: AST check failed\n");
85 printf("%s", root->toString().c_str());
86 return 255;
88 parse_info pi;
89 validate_tree(pi, root);
90 if (pi.errors != 0) {
91 EPRINTF("%d error(s), compilation aborted\n", pi.errors);
92 return 1;
94 printf("%s", root->toString().c_str());
95 return retval;