more work on hlc

This commit is contained in:
sfja 2026-11-27 02:35:44 +01:00
parent 2bddf34798
commit 6519cff69d

347
src/hlc.c
View File

@ -1,6 +1,7 @@
#include <assert.h> #include <assert.h>
#include <stdarg.h> #include <stdarg.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -56,24 +57,54 @@ static void print_info(Loc loc, const char *format, ...)
#define print_error_exit(LOC, ...) \ #define print_error_exit(LOC, ...) \
(print_error((LOC), __VA_ARGS__), \ (print_error((LOC), __VA_ARGS__), \
fprintf(stderr, \ fprintf(stderr, \
"exitted at %s:%d in %s()\n", \ "exited at %s:%d in %s()\n", \
__FILE__, \ __FILE__, \
__LINE__, \ __LINE__, \
__func__), \ __func__), \
exit(1)) exit(1))
typedef struct {
char **strs;
size_t strs_cap;
size_t strs_size;
} StrPool;
void strpool_init(StrPool *p, size_t cap)
{
*p = (StrPool) {
.strs = calloc(cap, sizeof(char)),
.strs_cap = cap,
.strs_size = 0,
};
}
void strpool_destroy(StrPool *p)
{
for (size_t i = 0; i < p->strs_size; ++i)
free(p->strs[i]);
free(p->strs);
}
size_t strpool_intern_idx(StrPool *p, const char *str)
{
size_t i = 0;
for (; i < p->strs_size; ++i)
if (strcmp(str, p->strs[i]) == 0)
break;
if (i >= p->strs_size) {
assert(i < p->strs_cap);
p->strs[i] = strdup(str);
p->strs_size += 1;
}
return i;
}
constexpr size_t ident_max_len = 64; constexpr size_t ident_max_len = 64;
constexpr size_t string_max_len = 128; constexpr size_t string_max_len = 128;
constexpr size_t int_max_len = 32; constexpr size_t int_max_len = 32;
constexpr size_t interned_idents_cap = 256;
static size_t interned_idents_size = 0;
static char *interned_idents[interned_idents_cap];
constexpr size_t interned_strings_cap = 128;
static size_t interned_strings_size = 0;
static char *interned_strings[interned_strings_cap];
#define TOK_LIST \ #define TOK_LIST \
X(Eof, ) \ X(Eof, ) \
X(Ident, ) \ X(Ident, ) \
@ -82,6 +113,9 @@ static char *interned_strings[interned_strings_cap];
X(Bin, ) \ X(Bin, ) \
X(Char, ) \ X(Char, ) \
X(Str, ) \ X(Str, ) \
X(Or, ) \
X(And, ) \
X(Not, ) \
X(Fn, ) \ X(Fn, ) \
X(Return, ) \ X(Return, ) \
X(If, ) \ X(If, ) \
@ -130,42 +164,41 @@ typedef enum {
typedef struct { typedef struct {
Loc loc; Loc loc;
int64_t val;
TokTy ty; TokTy ty;
int val;
} Tok; } Tok;
typedef struct { typedef struct {
StrPool *ident_pool;
StrPool *string_pool;
Loc loc; Loc loc;
FILE *file; FILE *file;
int ch; int ch;
bool error_occured; bool error_occured;
} Lexer; } Lexer;
static const char *keyword_strs[] = { #define KEYWORD_LIST \
"fn", X(Or, "or") \
"return", X(And, "and") \
"if", X(Not, "not") \
"else", X(Fn, "fn") \
"while", X(Return, "return") \
"break", X(If, "if") \
"continue", X(Else, "else") \
"let", X(While, "while") \
"static", X(Break, "break") \
"const", X(Continue, "continue") \
}; X(Let, "let") \
X(Static, "static") \
X(Continue, "continue")
static const TokTy keyword_tys[] = { #define X(NAME, STR) STR,
Tok_Fn, static const char *keyword_strs[] = { KEYWORD_LIST };
Tok_Return, #undef X
Tok_If,
Tok_Else, #define X(NAME, STR) Tok_##NAME,
Tok_While, static const TokTy keyword_tys[] = { KEYWORD_LIST };
Tok_Break, #undef X
Tok_Continue,
Tok_Let,
Tok_Static,
Tok_Continue,
};
constexpr size_t keyword_count = sizeof(keyword_strs) / sizeof(keyword_strs[0]); constexpr size_t keyword_count = sizeof(keyword_strs) / sizeof(keyword_strs[0]);
static_assert(keyword_count == sizeof(keyword_tys) / sizeof(keyword_tys[0])); static_assert(keyword_count == sizeof(keyword_tys) / sizeof(keyword_tys[0]));
@ -181,10 +214,10 @@ static void lexer_step(Lexer *l)
l->ch = fgetc(l->file); l->ch = fgetc(l->file);
} }
static Tok lexer_tok(Lexer *l, Loc loc, TokTy ty, int val) static Tok lexer_tok(Lexer *l, Loc loc, TokTy ty, int64_t val)
{ {
(void)l; (void)l;
return (Tok) { loc, ty, val }; return (Tok) { loc, val, ty };
} }
static bool char_is_ident_start(int ch) static bool char_is_ident_start(int ch)
@ -227,18 +260,8 @@ static Tok lexer_lex_ident(Lexer *l)
if (ty != Tok_Ident) if (ty != Tok_Ident)
return lexer_tok(l, loc, ty, 0); return lexer_tok(l, loc, ty, 0);
size_t ident_idx = 0; size_t ident_idx = strpool_intern_idx(l->ident_pool, ident);
for (; ident_idx < interned_idents_size; ++ident_idx) return lexer_tok(l, loc, ty, ident_idx);
if (strcmp(ident, interned_idents[ident_idx]) == 0)
break;
if (ident_idx >= interned_idents_size) {
assert(ident_idx < interned_idents_cap);
interned_idents[ident_idx] = strdup(ident);
interned_idents_size += 1;
}
return lexer_tok(l, loc, ty, (int)ident_idx);
} }
static int lexer_lex_literal_char(Lexer *l) static int lexer_lex_literal_char(Lexer *l)
@ -285,18 +308,8 @@ static Tok lexer_lex_string(Lexer *l)
assert(l->ch == '"'); assert(l->ch == '"');
lexer_step(l); lexer_step(l);
size_t string_idx = 0; size_t string_idx = strpool_intern_idx(l->string_pool, string);
for (; string_idx < interned_strings_size; ++string_idx) return lexer_tok(l, loc, Tok_Str, string_idx);
if (strcmp(string, interned_strings[string_idx]) == 0)
break;
if (string_idx >= interned_strings_size) {
assert(string_idx < interned_strings_cap);
interned_idents[string_idx] = strdup(string);
interned_idents_size += 1;
}
return lexer_tok(l, loc, Tok_Str, (int)string_idx);
} }
static Tok lexer_lex_number(Lexer *l) static Tok lexer_lex_number(Lexer *l)
@ -455,6 +468,7 @@ bool type_eq(const Type *a, const Type *b)
case Type_Ptr: case Type_Ptr:
return type_eq(a->ptr_inner, b->ptr_inner); return type_eq(a->ptr_inner, b->ptr_inner);
} }
assert(false);
} }
const Type *intern_type(Type type) const Type *intern_type(Type type)
@ -462,10 +476,10 @@ const Type *intern_type(Type type)
for (size_t i = 0; i < interned_types_size; ++i) for (size_t i = 0; i < interned_types_size; ++i)
if (type_eq(&type, &interned_types[i])) if (type_eq(&type, &interned_types[i]))
return &interned_types[i]; return &interned_types[i];
assert(interned_idents_size < interned_types_cap); assert(interned_types_size < interned_types_cap);
interned_types[interned_idents_size] = type; interned_types[interned_types_size] = type;
interned_idents_size += 1; interned_types_size += 1;
return &interned_types[interned_idents_size]; return &interned_types[interned_types_size];
} }
constexpr size_t fndef_params_cap = 8; constexpr size_t fndef_params_cap = 8;
@ -507,10 +521,14 @@ constexpr size_t syms_cap = 256;
static size_t syms_size = 0; static size_t syms_size = 0;
static Sym syms[syms_cap] = { }; static Sym syms[syms_cap] = { };
static int sym_level = 0;
typedef struct { typedef struct {
Lexer *lexer; Lexer *lexer;
Tok tok; Tok tok;
bool is_scout_pass; const char **idents;
const char **strings;
FILE *out;
} Parser; } Parser;
static void parser_step(Parser *p) static void parser_step(Parser *p)
@ -522,7 +540,9 @@ static const Type *parse_type(Parser *p)
{ {
Loc loc = p->tok.loc; Loc loc = p->tok.loc;
if (p->tok.ty == Tok_Ident) { if (p->tok.ty == Tok_Ident) {
if (strcmp(interned_idents[p->tok.val], "u16") == 0) const char *ident = p->idents[p->tok.val];
parser_step(p);
if (strcmp(ident, "u16") == 0)
return intern_type((Type) { .ty = Type_U16 }); return intern_type((Type) { .ty = Type_U16 });
assert(false); assert(false);
} else { } else {
@ -530,12 +550,140 @@ static const Type *parse_type(Parser *p)
} }
} }
static void parse_stmt(Parser *p);
typedef enum { RVal, LVal } ValTy;
static ValTy parse_operand(Parser *p)
{
Loc loc = p->tok.loc;
if (p->tok.ty == Tok_Ident) {
const char *ident = p->idents[p->tok.val];
parser_step(p);
fprintf(p->out, " LoadImm %s\n", ident);
return RVal;
} else {
print_error_exit(loc, "expected expression");
}
}
static ValTy parse_prec_expr(Parser *p, int prec)
{
if (prec <= 8
&& (p->tok.ty == Tok_Not || p->tok.ty == '!' || p->tok.ty == '-'
|| p->tok.ty == '*' || p->tok.ty == '&')) {
TokTy ty = p->tok.ty;
parser_step(p);
Loc inner_loc = p->tok.loc;
ValTy inner = parse_prec_expr(p, prec);
switch (p->tok.ty) {
case Tok_Not:
fprintf(p->out, " CmpZero\n");
return RVal;
case '!':
fprintf(p->out, " Not\n");
return RVal;
case '-':
fprintf(p->out, " Negate\n");
return RVal;
case '&':
if (inner != LVal)
print_error_exit(inner_loc, "expected l-value");
return RVal;
case '*':
assert(false);
default:
assert(false);
}
}
ValTy lhs = parse_operand(p);
while (true) {
if (prec <= 1 && p->tok.ty == Tok_Or) {
parser_step(p);
ValTy rhs = parse_prec_expr(p, 2);
continue;
}
if (prec <= 2 && p->tok.ty == Tok_And) {
parser_step(p);
parse_prec_expr(p, 3);
continue;
}
if (prec <= 3
&& (p->tok.ty == Tok_EqEq || p->tok.ty == Tok_ExclEq
|| p->tok.ty == Tok_Lt || p->tok.ty == Tok_Gt
|| p->tok.ty == Tok_LtEq || p->tok.ty == Tok_GtEq)) {
parser_step(p);
parse_prec_expr(p, 4);
break;
}
if (prec <= 4 && p->tok.ty == '|') {
parser_step(p);
parse_prec_expr(p, 5);
continue;
}
if (prec <= 5 && p->tok.ty == '&') {
parser_step(p);
parse_prec_expr(p, 6);
continue;
}
if (prec <= 6 && (p->tok.ty == Tok_LtLt || p->tok.ty == Tok_GtGt)) {
parser_step(p);
parse_prec_expr(p, 7);
continue;
}
if (prec <= 7 && (p->tok.ty == '+' || p->tok.ty == '-')) {
parser_step(p);
parse_prec_expr(p, 8);
fprintf(p->out, " Add\n");
continue;
}
if (prec <= 9 && (p->tok.ty == '(' || p->tok.ty == '[')) {
assert(false);
}
break;
}
return lhs;
}
static void parse_expr(Parser *p)
{
parse_prec_expr(p, 0);
}
static void parse_block(Parser *p)
{
assert(p->tok.ty == '{');
parser_step(p);
while (p->tok.ty != Tok_Eof && p->tok.ty != '}') {
if (p->tok.ty == Tok_Fn) {
parse_stmt(p);
continue;
}
parse_expr(p);
if (p->tok.ty != ';')
break;
parser_step(p);
fprintf(p->out, " pop\n");
}
if (p->tok.ty != '}')
print_error_exit(p->tok.loc, "expected '}'");
parser_step(p);
}
static FnParam parse_fn_param(Parser *p) static FnParam parse_fn_param(Parser *p)
{ {
FnParam fnparam = { .loc = p->tok.loc }; FnParam fnparam = { .loc = p->tok.loc };
if (p->tok.ty != Tok_Ident) if (p->tok.ty != Tok_Ident)
print_error_exit(p->tok.loc, "expected identifier"); print_error_exit(p->tok.loc, "expected identifier");
fnparam.ident = interned_idents[p->tok.val]; fnparam.ident = p->idents[p->tok.val];
parser_step(p);
if (p->tok.ty == ':') { if (p->tok.ty == ':') {
parser_step(p); parser_step(p);
fnparam.type = parse_type(p); fnparam.type = parse_type(p);
@ -545,36 +693,63 @@ static FnParam parse_fn_param(Parser *p)
static void parse_fn(Parser *p) static void parse_fn(Parser *p)
{ {
FnDef fndef = { }; assert(fndefs_size < fndefs_cap);
FnDef *fndef = &fndefs[fndefs_size];
fndefs_size += 1;
assert(syms_size < syms_cap);
Sym *sym = &syms[syms_size];
syms_size += 1;
Loc loc = p->tok.loc; Loc loc = p->tok.loc;
fndef.loc = loc; fndef->loc = loc;
parser_step(p); parser_step(p);
if (p->tok.ty != Tok_Ident) if (p->tok.ty != Tok_Ident)
print_error_exit(p->tok.loc, "expected identifier"); print_error_exit(p->tok.loc, "expected identifier");
fndef.ident = interned_idents[p->tok.val]; fndef->ident = p->idents[p->tok.val];
parser_step(p); parser_step(p);
if (p->tok.ty != '(') if (p->tok.ty != '(')
print_error_exit(p->tok.loc, "expected '('"); print_error_exit(p->tok.loc, "expected '('");
parser_step(p); parser_step(p);
while (p->tok.ty != Tok_Eof && p->tok.ty != ')') { while (p->tok.ty != Tok_Eof && p->tok.ty != ')') {
assert(fndef.params_size < fndef_params_cap); assert(fndef->params_size < fndef_params_cap);
fndef.params[fndef.params_size] = parse_fn_param(p); fndef->params[fndef->params_size] = parse_fn_param(p);
fndef.params_size += 1; fndef->params_size += 1;
if (p->tok.ty == ',') if (p->tok.ty == ',')
parser_step(p); parser_step(p);
} }
if (p->tok.ty != ')') if (p->tok.ty != ')')
print_error_exit(p->tok.loc, "expected ')'"); print_error_exit(p->tok.loc, "expected ')'");
parser_step(p);
if (p->tok.ty == Tok_MinusGt) { if (p->tok.ty == Tok_MinusGt) {
parser_step(p); parser_step(p);
fndef.ret_type = parse_type(p); fndef->ret_type = parse_type(p);
}
} }
static void parse_top_decl(Parser *p) *sym = (Sym) {
.ident = fndef->ident,
.fndef = fndef,
.ty = Sym_FnDef,
.level = sym_level,
};
if (p->tok.ty == ';') {
parser_step(p);
return;
}
fprintf(p->out, "%s:\n", fndef->ident);
if (p->tok.ty != '{')
print_error_exit(p->tok.loc, "expected '{' or ';'");
parse_block(p);
fprintf(p->out, " Return\n");
}
static void parse_stmt(Parser *p)
{ {
Loc loc = p->tok.loc; Loc loc = p->tok.loc;
@ -585,10 +760,10 @@ static void parse_top_decl(Parser *p)
} }
} }
void parse_file_decls(Parser *p) void parse_file(Parser *p)
{ {
while (p->tok.ty != Tok_Eof) { while (p->tok.ty != Tok_Eof) {
parse_top_decl(p); parse_stmt(p);
} }
} }
@ -624,7 +799,15 @@ int main(int argc, char *argv[])
FILE *input_file = fopen(input_filename, "rb"); FILE *input_file = fopen(input_filename, "rb");
assert(input_file); assert(input_file);
StrPool ident_pool;
strpool_init(&ident_pool, 256);
StrPool string_pool;
strpool_init(&string_pool, 128);
Lexer lexer = { Lexer lexer = {
.ident_pool = &ident_pool,
.string_pool = &string_pool,
.loc = { .filename = input_filename, .line = 1, .col = 1 }, .loc = { .filename = input_filename, .line = 1, .col = 1 },
.file = input_file, .file = input_file,
.ch = fgetc(input_file), .ch = fgetc(input_file),
@ -634,10 +817,14 @@ int main(int argc, char *argv[])
Parser parser = { Parser parser = {
.lexer = &lexer, .lexer = &lexer,
.tok = lexer_next(&lexer), .tok = lexer_next(&lexer),
.is_scout_pass = true, .idents = (const char **)ident_pool.strs,
.strings = (const char **)ident_pool.strs,
.out = stdout,
}; };
parse_file_decls(&parser); parse_file(&parser);
fclose(input_file); fclose(input_file);
strpool_destroy(&ident_pool);
strpool_destroy(&string_pool);
} }