6b23b49fd59ad3b5835eb6c217598d8e5f61e321
[ccc.git] / splc.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <getopt.h>
4
5 #include "ast.h"
6 #include "gen.h"
7 #include "parse.h"
8 #include "scan.h"
9 #include "type.h"
10 extern int yylex_destroy(void);
11
12 void usage(FILE *out, char *arg0)
13 {
14 fprintf(out,
15 "Usage: %s [OPTS] [FILE]\n"
16 "\n"
17 "Compile an spl file. If FILE is not specified stdin is used.\n"
18 "\n"
19 "Options:\n"
20 "\t-p\tPretty print the parsed abstract syntax tree\n"
21 "\t-t\tPretty print the typed abstract syntax tree\n"
22 "\t-h\tShow this help\n"
23 , arg0);
24 }
25
26 int main(int argc, char *argv[])
27 {
28 int opt;
29 bool pparse = false, ptype = false;
30
31 while ((opt = getopt(argc, argv, "hpt")) != -1) {
32 switch (opt) {
33 case 'p':
34 pparse = true;
35 break;
36 case 't':
37 ptype = true;
38 break;
39 case 'h':
40 usage(stdout, argv[0]);
41 return 0;
42 default:
43 usage(stderr, argv[0]);
44 return 1;
45 }
46 }
47 if (optind + 1 == argc && strcmp(argv[optind], "-") != 0)
48 if ((yyin = fopen(argv[optind], "r")) == NULL)
49 pdie("fopen");
50
51 struct ast *result = NULL;
52 int r = yyparse(&result);
53 if (r != 0)
54 return 1;
55 yylex_destroy();
56 if (pparse)
57 ast_print(result, stdout);
58 if ((result = type(result)) == NULL) {
59 r = 1;
60 goto end;
61 }
62 if (ptype)
63 ast_print(result, stdout);
64 if (!gen(result)) {
65 r = 1;
66 goto end;
67 }
68 ast_free(result);
69 end:
70 if (yyin == stdin)
71 if (fclose(yyin) == -1)
72 perror("fclose");
73 return r;
74 }