diff --git a/src/hlc.c b/src/hlc.c index d841b1a..8f830cd 100644 --- a/src/hlc.c +++ b/src/hlc.c @@ -1,13 +1,604 @@ +#include +#include +#include #include +#include #include +typedef struct { + const char *filename; + int line; + int col; +} Loc; + +static void print_diagnostics(Loc loc, + const char *severity, + int severity_color, + const char *format, + va_list va) +{ + fprintf(stderr, "\033[1;%dm%s\033[1;39m: ", severity_color, severity); + vfprintf(stderr, format, va); + fprintf(stderr, + "\n \033[0;37m--> %s:%d:%d\n\033[0m", + loc.filename, + loc.line, + loc.col); +} + +[[maybe_unused]] +static void print_error(Loc loc, const char *format, ...) +{ + va_list va; + va_start(va, format); + print_diagnostics(loc, "error", 31, format, va); + va_end(va); +} + +[[maybe_unused]] +static void print_warning(Loc loc, const char *format, ...) +{ + va_list va; + va_start(va, format); + print_diagnostics(loc, "warning", 33, format, va); + va_end(va); +} + +[[maybe_unused]] +static void print_info(Loc loc, const char *format, ...) +{ + va_list va; + va_start(va, format); + print_diagnostics(loc, "info", 34, format, va); + va_end(va); +} + +#define print_error_exit(LOC, ...) \ + (print_error((LOC), __VA_ARGS__), \ + fprintf(stderr, \ + "exitted at %s:%d in %s()\n", \ + __FILE__, \ + __LINE__, \ + __func__), \ + exit(1)) + +constexpr size_t ident_max_len = 64; +constexpr size_t string_max_len = 128; +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 \ + X(Eof, ) \ + X(Ident, ) \ + X(Int, ) \ + X(Hex, ) \ + X(Bin, ) \ + X(Char, ) \ + X(Str, ) \ + X(Fn, ) \ + X(Return, ) \ + X(If, ) \ + X(Else, ) \ + X(While, ) \ + X(Break, ) \ + X(Continue, ) \ + X(Let, ) \ + X(Static, ) \ + X(Const, ) \ + X(EqEq, ) \ + X(ExclEq, ) \ + X(LtLt, ) \ + X(LtEq, ) \ + X(GtGt, ) \ + X(GtEq, ) \ + X(PlusEq, ) \ + X(MinusEq, ) \ + X(MinusGt, ) \ + X(LParen, = '(') \ + X(RParen, = ')') \ + X(LBrace, = '{') \ + X(RBrace, = '}') \ + X(LBracket, = '[') \ + X(RBracket, = ']') \ + X(Dot, = '.') \ + X(Comma, = ',') \ + X(Colon, = ':') \ + X(Semi, = ';') \ + X(Amper, = '&') \ + X(Pipe, = '|') \ + X(Lt, = '<') \ + X(Gt, = '>') \ + X(Eq, = '=') \ + X(Excl, = '!') \ + X(Plus, = '+') \ + X(Minus, = '-') \ + X(Aster, = '*') \ + X(Slash, = '/') + +typedef enum { +#define X(NAME, VAL) Tok_##NAME VAL, + TOK_LIST +#undef X +} TokTy; + +typedef struct { + Loc loc; + TokTy ty; + int val; +} Tok; + +typedef struct { + Loc loc; + FILE *file; + int ch; + bool error_occured; +} Lexer; + +static const char *keyword_strs[] = { + "fn", + "return", + "if", + "else", + "while", + "break", + "continue", + "let", + "static", + "const", +}; + +static const TokTy keyword_tys[] = { + Tok_Fn, + Tok_Return, + Tok_If, + Tok_Else, + Tok_While, + Tok_Break, + Tok_Continue, + Tok_Let, + Tok_Static, + Tok_Continue, +}; + +constexpr size_t keyword_count = sizeof(keyword_strs) / sizeof(keyword_strs[0]); +static_assert(keyword_count == sizeof(keyword_tys) / sizeof(keyword_tys[0])); + +static void lexer_step(Lexer *l) +{ + if (l->ch == '\n') { + l->loc.line += 1; + l->loc.col = 1; + } else if (l->ch != EOF) { + l->loc.col += 1; + } + l->ch = fgetc(l->file); +} + +static Tok lexer_tok(Lexer *l, Loc loc, TokTy ty, int val) +{ + (void)l; + return (Tok) { loc, ty, val }; +} + +static bool char_is_ident_start(int ch) +{ + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'; +} + +static bool char_is_ident(int ch) +{ + return char_is_ident_start(ch) || (ch >= '0' && ch <= '9'); +} + +static Tok lexer_lex_ident(Lexer *l) +{ + Loc loc = l->loc; + + char ident[ident_max_len + 1] = ""; + size_t ident_len = 0; + + ident[ident_len] = l->ch; + ident_len += 1; + lexer_step(l); + + while (char_is_ident(l->ch)) { + assert(ident_len <= ident_max_len); + + ident[ident_len] = l->ch; + ident_len += 1; + lexer_step(l); + } + + TokTy ty = Tok_Ident; + for (size_t i = 0; i < keyword_count; ++i) { + if (strcmp(ident, keyword_strs[i]) == 0) { + ty = keyword_tys[i]; + break; + } + } + + if (ty != Tok_Ident) + return lexer_tok(l, loc, ty, 0); + + size_t ident_idx = 0; + for (; ident_idx < interned_idents_size; ++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) +{ + Loc loc = l->loc; + assert(l->ch != EOF); + int ch = l->ch; + lexer_step(l); + if (ch != '\\') + return ch; + assert(l->ch != EOF); + ch = l->ch; + lexer_step(l); + switch (ch) { + case '0': + return '\0'; + case 't': + return '\t'; + case 'n': + return '\n'; + case '\"': + case '\'': + return ch; + default: + print_warning(loc, "unknown escape sequence '\\%c'", ch); + return ch; + } +} + +static Tok lexer_lex_string(Lexer *l) +{ + Loc loc = l->loc; + lexer_step(l); + + char string[string_max_len + 1] = ""; + size_t string_len = 0; + + while (l->ch != EOF && l->ch != '"') { + assert(string_len < string_max_len); + string[string_len] = lexer_lex_literal_char(l); + string_len += 1; + } + + assert(l->ch == '"'); + lexer_step(l); + + size_t string_idx = 0; + for (; string_idx < interned_strings_size; ++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) +{ + Loc loc = l->loc; + + char str[int_max_len] = ""; + size_t str_len = 0; + + if (l->ch == '0') { + lexer_step(l); + if (l->ch == 'x') { + lexer_step(l); + + while ((l->ch >= '0' && l->ch <= '9') + || (l->ch >= 'a' && l->ch <= 'f') + || (l->ch == 'A' && l->ch <= 'F')) { + + assert(str_len < int_max_len); + str[str_len] = l->ch; + str_len += 1; + lexer_step(l); + } + + int val = strtol(str, nullptr, 16); + return lexer_tok(l, loc, Tok_Hex, val); + } + + if (l->ch == 'b') { + lexer_step(l); + + while (l->ch == '0' || l->ch == '1') { + assert(str_len < int_max_len); + str[str_len] = l->ch; + str_len += 1; + lexer_step(l); + } + + int val = strtol(str, nullptr, 2); + return lexer_tok(l, loc, Tok_Hex, val); + } + return lexer_tok(l, loc, Tok_Int, 0); + } + + while (l->ch >= '0' && l->ch <= '9') { + assert(str_len < int_max_len); + str[str_len] = l->ch; + str_len += 1; + lexer_step(l); + } + + int val = strtol(str, nullptr, 10); + return lexer_tok(l, loc, Tok_Int, val); +} + +static Tok lexer_tok_stepping(Lexer *l, Loc loc, TokTy ty) +{ + lexer_step(l); + return lexer_tok(l, loc, ty, 0); +} + +Tok lexer_next(Lexer *l) +{ + Loc loc = l->loc; + if (l->ch == EOF) + return lexer_tok(l, loc, Tok_Eof, 0); + bool matched = false; + while (strchr(" \r\t\n", l->ch)) { + matched = true; + lexer_step(l); + } + if (matched) + return lexer_next(l); + if (char_is_ident_start(l->ch)) + return lexer_lex_ident(l); + if (l->ch == '"') + return lexer_lex_string(l); + if (l->ch >= '0' && l->ch <= '9') + return lexer_lex_number(l); + + if (l->ch == '\'') { + lexer_step(l); + int val = lexer_lex_literal_char(l); + assert(l->ch == '\''); + lexer_step(l); + return lexer_tok(l, loc, Tok_Char, val); + } + + if (l->ch == '/') { + lexer_step(l); + if (l->ch == '/') { + while (l->ch != EOF && l->ch != '\n') + lexer_step(l); + return lexer_next(l); + } + return lexer_tok(l, loc, '/', 0); + } + + if (strchr("(){}[].,:;&|<>=!+-*", l->ch)) { + TokTy ty = l->ch; + lexer_step(l); + if (ty == '=' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_EqEq); + if (ty == '!' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_ExclEq); + if (ty == '<' && l->ch == '<') + return lexer_tok_stepping(l, loc, Tok_LtLt); + if (ty == '<' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_LtEq); + if (ty == '>' && l->ch == '>') + return lexer_tok_stepping(l, loc, Tok_GtGt); + if (ty == '>' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_GtEq); + if (ty == '+' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_PlusEq); + if (ty == '-' && l->ch == '=') + return lexer_tok_stepping(l, loc, Tok_MinusEq); + if (ty == '-' && l->ch == '>') + return lexer_tok_stepping(l, loc, Tok_MinusGt); + return lexer_tok(l, loc, ty, 0); + } + + print_error(loc, "unexpected character '%c'", l->ch); + l->error_occured = true; + lexer_step(l); + return lexer_next(l); +} + +typedef enum { + Type_Void, + Type_U16, + Type_Ptr, +} TypeTy; + +typedef struct Type Type; + +struct Type { + union { + Type *ptr_inner; + }; + TypeTy ty; +}; + +constexpr size_t interned_types_cap = 32; +static size_t interned_types_size = 0; +static Type interned_types[interned_types_cap]; + +bool type_eq(const Type *a, const Type *b) +{ + if (a->ty != b->ty) + return false; + switch (a->ty) { + case Type_Void: + case Type_U16: + return true; + case Type_Ptr: + return type_eq(a->ptr_inner, b->ptr_inner); + } +} + +const Type *intern_type(Type type) +{ + for (size_t i = 0; i < interned_types_size; ++i) + if (type_eq(&type, &interned_types[i])) + return &interned_types[i]; + assert(interned_idents_size < interned_types_cap); + interned_types[interned_idents_size] = type; + interned_idents_size += 1; + return &interned_types[interned_idents_size]; +} + +constexpr size_t fndef_params_cap = 8; + +typedef struct { + Loc loc; + const char *ident; + const Type *type; +} FnParam; + +typedef struct { + Loc loc; + const char *ident; + FnParam params[fndef_params_cap]; + size_t params_size; + const Type *ret_type; +} FnDef; + +constexpr size_t fndefs_cap = 128; +static size_t fndefs_size = 0; +static FnDef fndefs[fndefs_cap]; + +typedef enum { + Sym_FnDef, + Sym_FnParam, +} SymTy; + +typedef struct { + const char *ident; + union { + const FnDef *fndef; + const FnParam *fnparam; + }; + SymTy ty; + int level; +} Sym; + +constexpr size_t syms_cap = 256; +static size_t syms_size = 0; +static Sym syms[syms_cap] = { }; + +typedef struct { + Lexer *lexer; + Tok tok; + bool is_scout_pass; +} Parser; + +static void parser_step(Parser *p) +{ + p->tok = lexer_next(p->lexer); +} + +static const Type *parse_type(Parser *p) +{ + Loc loc = p->tok.loc; + if (p->tok.ty == Tok_Ident) { + if (strcmp(interned_idents[p->tok.val], "u16") == 0) + return intern_type((Type) { .ty = Type_U16 }); + assert(false); + } else { + print_error_exit(loc, "expected type"); + } +} + +static FnParam parse_fn_param(Parser *p) +{ + FnParam fnparam = { .loc = p->tok.loc }; + if (p->tok.ty != Tok_Ident) + print_error_exit(p->tok.loc, "expected identifier"); + fnparam.ident = interned_idents[p->tok.val]; + if (p->tok.ty == ':') { + parser_step(p); + fnparam.type = parse_type(p); + } + return fnparam; +} + +static void parse_fn(Parser *p) +{ + FnDef fndef = { }; + + Loc loc = p->tok.loc; + fndef.loc = loc; + parser_step(p); + if (p->tok.ty != Tok_Ident) + print_error_exit(p->tok.loc, "expected identifier"); + fndef.ident = interned_idents[p->tok.val]; + parser_step(p); + if (p->tok.ty != '(') + print_error_exit(p->tok.loc, "expected '('"); + parser_step(p); + while (p->tok.ty != Tok_Eof && p->tok.ty != ')') { + assert(fndef.params_size < fndef_params_cap); + fndef.params[fndef.params_size] = parse_fn_param(p); + fndef.params_size += 1; + + if (p->tok.ty == ',') + parser_step(p); + } + if (p->tok.ty != ')') + print_error_exit(p->tok.loc, "expected ')'"); + + if (p->tok.ty == Tok_MinusGt) { + parser_step(p); + fndef.ret_type = parse_type(p); + } +} + +static void parse_top_decl(Parser *p) +{ + Loc loc = p->tok.loc; + + if (p->tok.ty == Tok_Fn) { + parse_fn(p); + } else { + print_error_exit(loc, "expected declaration"); + } +} + +void parse_file_decls(Parser *p) +{ + while (p->tok.ty != Tok_Eof) { + parse_top_decl(p); + } +} + int main(int argc, char *argv[]) { char *input_filename = nullptr; char *output_filename = nullptr; for (int i = 1; i < argc; ++i) { - if (strcmp(argv[i], "-o")) { + if (strcmp(argv[i], "-o") == 0) { i += 1; if (i >= argc) { printf("error: expected filename\n"); @@ -29,4 +620,24 @@ int main(int argc, char *argv[]) printf("input_filename = %s\n", input_filename); printf("output_filename = %s\n", output_filename); + + FILE *input_file = fopen(input_filename, "rb"); + assert(input_file); + + Lexer lexer = { + .loc = { .filename = input_filename, .line = 1, .col = 1 }, + .file = input_file, + .ch = fgetc(input_file), + .error_occured = false, + }; + + Parser parser = { + .lexer = &lexer, + .tok = lexer_next(&lexer), + .is_scout_pass = true, + }; + + parse_file_decls(&parser); + + fclose(input_file); }