cusel/compiler/main.c
2026-11-21 00:46:50 +02:00

71 lines
1.3 KiB
C

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "error.h"
#include "vector.h"
#include "tokenizer.h"
DECL_VEC(char);
[[noreturn]] static void usage(void);
static void read_into_vec(VEC(char) *, FILE *);
int main(int argc, char **argv) {
argv0 = argv[0];
// TODO: proper argument parsing
if (argc != 2) {
usage();
}
auto path = argv[1];
FILE *f = fopen(path, "r");
if (!f) {
die("cannot open file \"%s\"", path);
}
VEC(char) buffer = {};
read_into_vec(&buffer, f);
if (ferror(f)) {
die("failure reading file \"%s\"", path);
}
auto tokens = tokenize(VEC_AS_SPAN(char, buffer));
for (size_t i = 0; i < LENGTH(tokens); i++) {
auto tok = AT(tokens, i);
printf("%zu:%zu %i ", tok.at.line, tok.at.column, tok.id);
for (size_t j = 0; j < tok.length; j++) {
putchar(AT(buffer, tok.at.offset + j));
}
printf("\n");
}
}
static void usage(void) {
fprintf(stderr, "usage: %s file\n", argv0);
exit(1);
}
static void read_into_vec(
VEC(char) *buffer,
FILE *f
) {
for (;;) {
VEC_ENSURE_FREE_SPACE(*buffer);
auto free_space = VEC_FREE_SPACE(char, *buffer);
auto bytes_read = fread(&AT(free_space, 0), 1, LENGTH(free_space), f);
if (bytes_read == 0) {
break;
}
VEC_RESIZE(*buffer, LENGTH(*buffer) + bytes_read);
}
}