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