100 lines
2.9 KiB
C
100 lines
2.9 KiB
C
#include "runner.h"
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
|
char *check_input;
|
|
int token;
|
|
FILE *output;
|
|
|
|
if (argc == 1 || argc > 3) {
|
|
fprintf(stderr, "invalid input with 1, >3, or non .alpha arg \n");
|
|
return -1; //no alpha file or too many args
|
|
} else if (argc == 2) {
|
|
if (is_help(argv[1])) {
|
|
return 0;
|
|
} else if (is_alpha_file(argv[1], strlen(argv[1])) != 0) {
|
|
return -1;
|
|
}
|
|
arg = NO_ARG; //no argument but valid input
|
|
yyin = fopen(argv[1], "r");
|
|
} else {
|
|
check_input = is_tok(argc, argv);
|
|
if (strcmp(CHECK_OTHER, check_input) == 0 || strcmp(INVALID_ARG, check_input) == 0) {
|
|
fprintf(stderr, "check_other or invalid_arg \n");
|
|
return -1; //invalid argument (need to update as we add more valid arguments)
|
|
}
|
|
output = fopen(check_input, "w");
|
|
arg = TOK_ARG; //it is a -tok arg with a valid alpha file at argv[2]
|
|
yyin = fopen(argv[2], "r");
|
|
}
|
|
while (0 != (token = yylex())) {
|
|
if (arg == TOK_ARG) {
|
|
fprintf(output, "%d %d %3d \"%s\"\n", line_number, column_number, token, yytext);
|
|
}
|
|
if(token == COMMENT){
|
|
for (int i = 0; i < yyleng; i++) {
|
|
if(yytext[i] == '\n'){
|
|
line_number++;
|
|
column_number = 0;
|
|
}
|
|
column_number++;
|
|
}
|
|
continue;
|
|
}
|
|
column_number += yyleng;
|
|
}
|
|
|
|
if (yyin != NULL) {
|
|
fclose(yyin);
|
|
}
|
|
if (output != NULL && arg == TOK_ARG) {
|
|
fclose(output);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
bool is_help(char * input) {
|
|
if (strcmp(input, "-help") == 0) {
|
|
printf("HELP:\nHow to run the alpha compiler:\n./alpha [options] program\nValid options:\n-tok output the token number, token, line number, and column number for each of the tokens to the .tok file\n");
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
char *is_tok(int argc, char *argv[]) {
|
|
if (argc == 3 && strcmp("-tok", argv[1]) == 0) {
|
|
char *input_prog = argv[2];
|
|
int file_len = strlen(input_prog);
|
|
//check that input program is a .alpha file
|
|
if (is_alpha_file(input_prog, file_len) != 0) {
|
|
return INVALID_ARG;
|
|
}
|
|
|
|
const char *basename = input_prog;
|
|
const char *slash = strrchr(input_prog, '/');
|
|
if (slash != NULL) {
|
|
basename = slash + 1;
|
|
}
|
|
|
|
// Calculate lengths
|
|
int basename_len = strlen(basename);
|
|
char* FILE_tok = calloc(basename_len - ALPHA_OFFSET + TOK_LEN + 2, sizeof(char));
|
|
|
|
// Copy filename and add .tok extension
|
|
strncpy(FILE_tok, basename, basename_len - ALPHA_OFFSET);
|
|
//fprintf(stderr, "hello");
|
|
strcat(FILE_tok, ".tok");
|
|
|
|
return FILE_tok;
|
|
}
|
|
return CHECK_OTHER;
|
|
}
|
|
|
|
int is_alpha_file(char *file, int file_len) {
|
|
if (strcmp(".alpha", file + sizeof(char) * (file_len - ALPHA_OFFSET)) != 0) {
|
|
return -1; //not alpha file
|
|
}
|
|
return 0; //is alpha file
|
|
}
|
|
|