vm-translator/main.c

81 lines
1.6 KiB
C
Raw Normal View History

2020-10-29 20:22:03 -04:00
#include <stdio.h>
#include <string.h>
#include <errno.h>
2020-10-31 18:00:09 -04:00
#include <stdlib.h>
2020-10-29 20:22:03 -04:00
#include "parser.h"
2020-10-30 13:06:02 -04:00
#include "translator.h"
2020-10-29 20:22:03 -04:00
2020-10-31 18:00:09 -04:00
char* verfname(char* fname) {
int len = strlen(fname);
if(len > 3) {
int extind = len - 3;
char* extstr = fname + (sizeof(char)*extind);
if(strcmp(extstr, ".vm") == 0) {
int startind = 0;
for(int i = extind-1; i >= 0; i--) {
if(fname[i] == '/') {
startind = i+1;
break;
}
}
2020-10-31 19:25:00 -04:00
int size = sizeof(char)*(extind - startind + 1);
2020-10-31 18:00:09 -04:00
char* startstr = fname + (sizeof(char)*startind);
char* retstr = (char*)malloc(size);
2020-10-31 19:25:00 -04:00
snprintf(retstr, size, "%s", startstr);
2020-10-31 18:00:09 -04:00
return retstr;
}
}
fprintf(stderr, "Name format must be Xxx.vm\n");
exit(1);
}
2020-11-01 17:11:11 -05:00
char* getoutname(char* fname) {
int len = strlen(fname);
int sz = sizeof(char)*(len+2);
char* outname = (char*)malloc(sz);
strcpy(outname, fname);
int ind = len-2;
char* ext = sizeof(char)*ind+outname;
snprintf(ext, 4, "asm");
return outname;
}
2020-10-29 20:22:03 -04:00
int main(int argc, char* argv[]) {
if(argc < 2) {
fprintf(stderr, "Usage: %s {file}\n", argv[0]);
return 1;
}
2020-10-31 18:00:09 -04:00
// file name validating
char* fname = verfname(argv[1]);
2020-10-29 20:22:03 -04:00
FILE* input = fopen(argv[1], "r");
if(input == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
return errno;
}
2020-10-29 21:06:33 -04:00
// parsing
2020-11-01 08:53:20 -05:00
struct Parser* p = mkparser(input);
parse(p);
2020-10-30 13:06:02 -04:00
// translating
2020-11-01 08:53:20 -05:00
struct Translator* t = mktranslator(p->lns, fname);
translate(t);
freeparser(p);
2020-11-01 17:11:11 -05:00
free(fname);
// output
char* outname = getoutname(argv[1]);
2020-10-29 20:22:03 -04:00
2020-11-01 17:11:11 -05:00
FILE* output = fopen(outname, "w");
printasmlns(t, output);
fclose(output);
2020-10-29 20:22:03 -04:00
2020-11-01 17:11:11 -05:00
// freeing rest
free(outname);
2020-11-01 08:53:20 -05:00
freetranslator(t);
2020-10-29 21:06:33 -04:00
2020-10-29 20:22:03 -04:00
return 0;
}