fix pretty printing and make commandline interface
[ccc.git] / splc.c
diff --git a/splc.c b/splc.c
new file mode 100644 (file)
index 0000000..8d7174c
--- /dev/null
+++ b/splc.c
@@ -0,0 +1,70 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <getopt.h>
+
+#include "ast.h"
+#include "parse.h"
+#include "scan.h"
+extern int yylex_destroy(void);
+
+void usage(FILE *out, char *arg0)
+{
+       fprintf(out,
+               "Usage: %s [OPTS] [FILE]\n"
+               "\n"
+               "Compile an spl file. If FILE is not specified stdin is used.\n"
+               "\n"
+               "Options:\n"
+               "\t-p\tJust parse and pretty print\n"
+               "\t-t\tJust parse and typecheck\n"
+               "\t-c\tparse, typecheck and compile (default)\n"
+               "\t-h\tShow this help\n"
+               , arg0);
+}
+
+enum mode {parse,type,compile};
+
+int main(int argc, char *argv[])
+{
+       int opt;
+       enum mode mode = compile;
+
+       while ((opt = getopt(argc, argv, "hptc")) != -1) {
+               switch (opt) {
+               case 'p':
+                       mode = parse;
+                       break;
+               case 't':
+                       mode = type;
+                       break;
+               case 'c':
+                       mode = compile;
+                       break;
+               case 'h':
+                       usage(stdout, argv[0]);
+                       return 0;
+               default:
+                       usage(stderr, argv[0]);
+                       return 1;
+               }
+       }
+       if (optind + 1 == argc && strcmp(argv[optind], "-") != 0)
+               if ((yyin = fopen(argv[optind], "r")) == NULL)
+                       pdie("fopen");
+
+       struct ast *result = NULL;
+        int r = yyparse(&result);
+       if (r != 0)
+               return 1;
+       yylex_destroy();
+       if (mode == parse) {
+               ast_print(result, stdout);
+               goto end;
+       }
+end:
+       ast_free(result);
+       if (yyin == stdin)
+               if (fclose(yyin) == -1)
+                       perror("fclose");
+       return 0;
+}