compiler/main_hosted.c
2025-02-23 15:55:42 -06:00

100 lines
2.1 KiB
C

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "lexer.h"
int read_file(const char * filename, uint8_t ** buf)
{
FILE * file = fopen(filename, "rb");
if (file == NULL) {
fprintf(stderr, "fopen(\"%s\", \"rb\"): %s\n", filename, strerror(errno));
return -1;
}
int ret;
ret = fseek(file, 0L, SEEK_END);
if (ret < 0) {
fprintf(stderr, "fseek(SEEK_END)");
return -1;
}
int offset = ftell(file);
if (offset < 0) {
fprintf(stderr, "ftell");
return -1;
}
int size = offset;
ret = fseek(file, 0L, SEEK_SET);
if (ret < 0) {
fprintf(stderr, "fseek(SEEK_SET)");
return -1;
}
fprintf(stderr, "read_file: %s size %d\n", filename, size);
*buf = (uint8_t *)malloc(size);
int fread_size = fread(*buf, 1, size, file);
if (fread_size != size) {
fprintf(stderr, "fread `%s` short read: %d ; expected: %d\n", filename, fread_size, size);
return -1;
}
ret = fclose(file);
if (ret < 0) {
fprintf(stderr, "fclose");
return -1;
}
return size;
}
const char * token_str[] = {
[TOKEN_INVALID] = "TOKEN_INVALID",
[TOKEN_EOF] = "TOKEN_EOF",
[TOKEN_IDENTIFIER] = "TOKEN_IDENTIFIER",
[TOKEN_CONSTANT] = "TOKEN_CONSTANT",
[TOKEN_INT] = "TOKEN_INT",
[TOKEN_VOID] = "TOKEN_VOID",
[TOKEN_RETURN] = "TOKEN_RETURN",
[TOKEN_LPAREN] = "TOKEN_LPAREN",
[TOKEN_RPAREN] = "TOKEN_RPAREN",
[TOKEN_LBRACE] = "TOKEN_LBRACE",
[TOKEN_RBRACE] = "TOKEN_RBRACE",
[TOKEN_SEMICOLON] = "TOKEN_SEMICOLON",
};
int main(int argc, char * argv[])
{
if (argc != 3) {
fprintf(stderr, "argc != 3 %d %s\n", argc, argv[1]);
return EXIT_FAILURE;
}
// --lex
// --parse
// --codegen
uint8_t * buf;
int size = read_file(argv[2], &buf);
if (size < 0) {
return EXIT_FAILURE;
}
struct lexer_state lexer_state;
lexer_state.buf = buf;
lexer_state.offset = 0;
lexer_state.size = size;
while (true) {
struct token token = lexer_next_token(&lexer_state);
printf("%s\n", token_str[token.type]);
if (token.type == TOKEN_INVALID)
return EXIT_FAILURE;
if (token.type == TOKEN_EOF)
break;
}
return EXIT_SUCCESS;
}