diff options
| author | Mustafa Quraish <[email protected]> | 2022-01-28 22:40:28 -0500 |
|---|---|---|
| committer | Mustafa Quraish <[email protected]> | 2022-01-28 22:40:28 -0500 |
| commit | 9645de3a44c1d0ad424872a27e1f148feb8f1860 (patch) | |
| tree | f3a8b2129b111f0bdc31d90ecce6dd1ecde2979b | |
| parent | Examples: Add example for unary ops, remove type hints (diff) | |
| download | cup-9645de3a44c1d0ad424872a27e1f148feb8f1860.tar.xz cup-9645de3a44c1d0ad424872a27e1f148feb8f1860.zip | |
Add some basic args parsing so we can test stuff from the CLI
| -rw-r--r-- | cup/main.c | 89 |
1 files changed, 66 insertions, 23 deletions
@@ -6,34 +6,77 @@ #include "generator.h" #include "unistd.h" +char *filename = NULL; +char *source = NULL; +i64 source_len = 0; +bool dump_ast = false; + +#define MAX_STDIN_SOURCE_LEN 2048 + +void usage(int exit_status) +{ + printf("Usage: cup [options] <file>\n"); + printf("Options:\n"); + printf(" -c <code> Code to compile\n"); + printf(" -h Show this help\n"); + printf(" -d Dump AST to stdout\n"); + printf("Output file will be named `output.nasm`\n"); + exit(exit_status); +} + +void parse_args(int argc, char **argv) +{ + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-c") == 0) { + source_len = strlen(argv[i+1]); + source = calloc(source_len + 1, 1); + strcpy(source, argv[i+1]); + i++; + filename = "CLI"; + } else if (strcmp(argv[i], "-h") == 0) { + usage(0); + } else if (strcmp(argv[i], "-d") == 0) { + dump_ast = true; + } else if (filename == NULL) { + if (strcmp(argv[i], "-") == 0) { + filename = "stdin"; + source = calloc(MAX_STDIN_SOURCE_LEN, 1); + source_len = fread(source, 1, MAX_STDIN_SOURCE_LEN, stdin); + if (source_len == MAX_STDIN_SOURCE_LEN) { + fprintf(stderr, "Source too long to use through stdin\n"); + exit(1); + } + } else { + filename = argv[i]; + // Read entire file into memory + FILE *fp = fopen(filename, "r"); + fseek(fp, 0, SEEK_END); + source_len = ftell(fp); + fseek(fp, 0, SEEK_SET); + source = malloc(source_len + 1); + fread(source, source_len, 1, fp); + source[source_len] = 0; + fclose(fp); + } + } else { + usage(1); + } + } +} + int main(int argc, char**argv) { - char *filename = argc > 1 ? argv[1] : "./examples/return-0.cup"; - - // Read entoire file into memory - FILE *fp = fopen(filename, "r"); - fseek(fp, 0, SEEK_END); - long fsize = ftell(fp); - fseek(fp, 0, SEEK_SET); - char *source = malloc(fsize + 1); - fread(source, fsize, 1, fp); - source[fsize] = 0; - fclose(fp); - - // Lexer - Lexer lexer = Lexer_new(filename, source, fsize); + parse_args(argc, argv); + + Lexer lexer = Lexer_new(filename, source, source_len); Node *ast = parse_program(&lexer); - - print_ast(ast); + + if (dump_ast) + print_ast(ast); FILE *f = fopen("output.nasm", "w"); generate_asm(ast, f); - // Token token; - // while ( (token = Lexer_next(&lexer)).type != TOKEN_EOF) { - // Token_print(stdout, &token); - // printf("\n"); - // } - + free(source); return 0; -}
\ No newline at end of file +} |