From 8bbefe95d25fa2981add4df35bdd9903c91a8e62 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sun, 8 Nov 2026 08:13:29 +0300 Subject: publish --- src/dynamic-array.h | 59 ++++++++++++++ src/export.c | 19 +++++ src/lex.c | 220 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lexeme.c | 13 +++ src/lexeme.h | 74 +++++++++++++++++ src/lexer.c | 172 ++++++++++++++++++++++++++++++++++++++++ src/lexer.h | 26 ++++++ src/string-builder.c | 41 ++++++++++ src/string-builder.h | 42 ++++++++++ src/string-view.h | 16 ++++ src/utils.h | 26 ++++++ 11 files changed, 708 insertions(+) create mode 100644 src/dynamic-array.h create mode 100644 src/export.c create mode 100644 src/lex.c create mode 100644 src/lexeme.c create mode 100644 src/lexeme.h create mode 100644 src/lexer.c create mode 100644 src/lexer.h create mode 100644 src/string-builder.c create mode 100644 src/string-builder.h create mode 100644 src/string-view.h create mode 100644 src/utils.h (limited to 'src') diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..6a02769 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,59 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DA, COUNT) \ + ({ \ + if ((DA).count + (COUNT) > (DA).capacity) { \ + if ((DA).capacity == 0) \ + (DA).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DA).count + (COUNT) > (DA).capacity) \ + (DA).capacity *= 2; \ + (DA).items = REALLOC((DA).items, \ + (DA).capacity * \ + sizeof (*(DA).items)); \ + ASSERT((DA).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DA) \ + ({ \ + (DA).capacity = (DA).count; \ + (DA).items = REALLOC((DA).items, \ + (DA).capacity * \ + sizeof (*(DA).items)); \ + ASSERT((DA).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DA, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), 1); \ + (DA).items[(DA).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), (NEW_ITEMS_COUNT)); \ + memcpy ((DA).items + (DA).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \ + (DA).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DA) \ + (DA).items[(DA).count - 1] + +#define DYNAMIC_ARRAY_RESET(DA) ({ (DA).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DA) FREE((DA).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DA) for ( \ + typeof ((DA).items) ITEM = (DA).items; \ + ITEM < (DA).items + (DA).count; ++ITEM) + +#endif // INCLUDED_DYNAMIC_ARRAY_H diff --git a/src/export.c b/src/export.c new file mode 100644 index 0000000..3477ef6 --- /dev/null +++ b/src/export.c @@ -0,0 +1,19 @@ +#include +#include "utils.h" +#include "lexeme.h" +#include "lexer.c" + +int +main (int argc, char *argv[]) +{ + UNUSED (argc); + UNUSED (argv); + + for (enum lexeme_kind kind = 1; kind < LEXEME_KIND_COUNT; ++kind) { + printf ("- %s --- =%s=\n", + lexeme_kind_names[kind - 1], + lexeme_regex_strings[kind - 1]); + } + + return EXIT_SUCCESS; +} diff --git a/src/lex.c b/src/lex.c new file mode 100644 index 0000000..3b10266 --- /dev/null +++ b/src/lex.c @@ -0,0 +1,220 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utils.h" +#include "string-builder.h" +#include "lexer.h" + +const char *file; + +static void +print_lexing_error (const struct lexer *lexer, + const struct lexeme *lexeme, + const char *fmt, ...) +{ + const char *beginning_of_line = lexer->sv.beg; + size_t line = 1; + + for (const char *p = lexer->sv.beg; p < lexeme->sv.beg; ++p) { + if (*p == '\n') { + beginning_of_line = p + 1; + line += 1; + } + } + + fprintf (stderr, "%s:%d:%d: error: ", file, (int) line, + (int) (lexeme->sv.beg - beginning_of_line)); + va_list ap; + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + putc ('\n', stderr); + + const char *p = beginning_of_line; + fprintf (stderr, "%5lu | ", line); + while (*p != '\n') + putc (*p++, stderr); + putc ('\n', stderr); + + p = beginning_of_line; + fprintf (stderr, " | "); + while (p++ < lexeme->sv.beg) + putc (' ', stderr); + putc ('^', stderr); + while (p++ < lexeme->sv.end) + putc ('~', stderr); + putc ('\n', stderr); +} + +static int +display_to_byte_len (const char *str, int len) +{ + while (*str) { + if (*str++ & 0xD0) { + len += 1; + str += 1; + } + } + + return len; +} + +int +main (int argc, char *argv[]) +{ + const char *progname = *argv++; + if (argc < 2) DIE ("Usage: %s file", progname); + + file = *argv++; + int fd = open (file, O_RDONLY); + if (fd == -1) DIE ("error: %s: %s", strerror (errno), file); + + struct stat st; + fstat (fd, &st); + char *string = mmap (NULL, st.st_size + 1, PROT_READ, MAP_PRIVATE, fd, 0); + close (fd); + + puts ("Исходный текст:"); + fwrite (string, 1, st.st_size, stdout); + + FILE *dump = fopen ("./build/dump.txt", "w"); + + struct { + struct lexeme *items; + uint32_t count; + uint32_t capacity; + } invalid_lexemes = {0}; + + struct string_builder sb = {0}; + struct lexer lexer = lexer_create (string, st.st_size); + putchar ('\n'); + printf ("| *Лексема* | *Тип лексемы* | *Значение* |\n"); + printf ("|------------------+-----------------------------+------------|\n"); + for (struct lexeme lexeme = lexer_next_lexeme (&lexer); + lexeme.kind != LEXEME_KIND_END_OF_FILE; + lexeme = lexer_next_lexeme (&lexer)) { + switch (lexeme.kind) { + case LEXEME_KIND_INVALID: + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + case LEXEME_KIND_COMMENT_UNTERMINATED: + DYNAMIC_ARRAY_APPEND (invalid_lexemes, lexeme); + continue; + default: break; + } + + if (lexeme.kind == LEXEME_KIND_COMMENT) + continue; + + fwrite (lexeme.sv.beg, STRING_VIEW_LEN (lexeme.sv), 1, dump); + putc (' ', dump); + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: + string_builder_printf (&sb, "K[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_SYMBOL_COMPARISON: + string_builder_printf (&sb, "C[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_CONSTANT_INTEGER: + string_builder_printf (&sb, "%d", lexeme.value.integer); + break; + case LEXEME_KIND_CONSTANT_REAL: + string_builder_printf (&sb, "%g", lexeme.value.real); + break; + case LEXEME_KIND_CONSTANT_STRING: + string_builder_printf (&sb, "S[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_IDENTIFIER: + string_builder_printf (&sb, "I[%d]", lexeme.value.table_index); + break; + default: + STRING_BUILDER_APPEND_CSTR (sb, ""); + } + string_builder_append_ntimes (&sb, ' ', 10 - sb.count); + STRING_BUILDER_APPEND_NULL (sb); + printf ("| %-16.*s | %-*s | %s |\n", + (int) STRING_VIEW_LEN (lexeme.sv), lexeme.sv.beg, + display_to_byte_len (lexeme_kind_names[lexeme.kind - 1], 27), + lexeme_kind_names[lexeme.kind - 1], + sb.items); + STRING_BUILDER_RESET (sb); + } + + fclose (dump); + + putchar ('\n'); + printf ("| *№* | *K* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < KEYWORD_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, keyword_names[i]); + + putchar ('\n'); + printf ("| *№* | *C* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < COMPARISON_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, comparison_names[i]); + + putchar ('\n'); + printf ("| *№* | *S* |\n"); + printf ("|-----+----------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.constant_string_table) { + printf ("| %3ld | %-14.*s |\n", e - lexer.constant_string_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + putchar ('\n'); + printf ("| *№* | *I* |\n"); + printf ("|-----+------------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.identifier_table) { + printf ("| %3ld | %-16.*s |\n", e - lexer.identifier_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + DYNAMIC_ARRAY_FOREACH (invalid_lexeme, invalid_lexemes) { + switch (invalid_lexeme->kind) { + case LEXEME_KIND_INVALID: + print_lexing_error (&lexer, invalid_lexeme, "invalid lexeme `%.*s'", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + print_lexing_error (&lexer, invalid_lexeme, + "string constant longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (invalid_lexeme->sv)); + break; + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + print_lexing_error (&lexer, invalid_lexeme, + "identifier longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (invalid_lexeme->sv)); + break; + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + print_lexing_error (&lexer, invalid_lexeme, "invalid number constant `%.*s'", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + case LEXEME_KIND_COMMENT_UNTERMINATED: + invalid_lexeme->sv.end = invalid_lexeme->sv.beg + 2; + print_lexing_error (&lexer, invalid_lexeme, "unterminated comment", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + default: break; + } + } + + munmap (string, st.st_size); + + return EXIT_SUCCESS; +} diff --git a/src/lexeme.c b/src/lexeme.c new file mode 100644 index 0000000..41ae8c8 --- /dev/null +++ b/src/lexeme.c @@ -0,0 +1,13 @@ +#include "lexeme.h" + +#define X(SYM, STR, ...) [LEXEME_KIND_##SYM - 1] = (STR), +const char *lexeme_kind_names[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X + +#define X(SYM, STR, ...) [KEYWORD_##SYM] = (STR), +const char *keyword_names[KEYWORD_COUNT] = { KEYWORDS () }; +#undef X + +#define X(SYM, STR, ...) [COMPARISON_##SYM] = (STR), +const char *comparison_names[COMPARISON_COUNT] = { COMPARISONS () }; +#undef X diff --git a/src/lexeme.h b/src/lexeme.h new file mode 100644 index 0000000..ebb8958 --- /dev/null +++ b/src/lexeme.h @@ -0,0 +1,74 @@ +#ifndef INCLUDED_LEXEME_H +#define INCLUDED_LEXEME_H + +#include +#include +#include "utils.h" +#include "string-view.h" + +// Входной язык содержит операторы цикла for (...; ...; ...) do, +// разделенные символом | (вертикальная полоса). Операторы цикла +// содержат идентификаторы, знаки сравнения <, >, =, строковые +// константы (последовательность символов в двойных кавычках), знак +// присваивания (:=). +#define LEXEME_KINDS() \ + X (KEYWORD, "Ключевое слово", "for|do" ) \ + X (IDENTIFIER_TOO_LONG, "Слишком длинный идентификатор", "[A-Z_a-z][0-9A-Z_a-z]{16,}" ) \ + X (IDENTIFIER, "Идентификатор", "[A-Z_a-z][0-9A-Z_a-z]*" ) \ + X (SYMBOL_SEPARATOR, "Символ вертикальной полосы", "\\|" ) \ + X (SYMBOL_ASSIGNMENT, "Знак присваивания", ":=" ) \ + X (SYMBOL_COMPARISON, "Знак операции сравнения", "<|=|>" ) \ + X (SYMBOL_PARENTHESIS_LEFT, "Знак левой скобки", "\\(" ) \ + X (SYMBOL_PARENTHESIS_RIGHT, "Знак правой скобки", "\\)" ) \ + X (SYMBOL_SEMICOLON, "Знак точки с запятой", ";" ) \ + X (CONSTANT_NUMBER_INVALID, "Недопустимая числовая константа", "-?[0-9]*\\.?[0-9]+[A-Z_a-z][0-9A-Z_a-z]+") \ + X (CONSTANT_INTEGER, "Целочиселная константа", "-?[0-9]+" ) \ + X (CONSTANT_REAL, "Вещественная константа", "-?[0-9]*\\.[0-9]+" ) \ + X (CONSTANT_STRING_TOO_LONG, "Слишком длинная строковая константа", "\"[^\"]{15,}\"" ) \ + X (CONSTANT_STRING, "Строковая константа", "\"[^\"]{0,14}\"" ) \ + X (COMMENT, "Комментарий", "//[^\n]*|/\\*+([^*]|\\*[^/])*\\*+/" ) \ + X (COMMENT_UNTERMINATED, "Незавершенный Комментарий", "/\\*([^*]|]\\*[^/])*" ) + +#define X(SYM, ...) LEXEME_KIND_##SYM, +enum lexeme_kind { + LEXEME_KIND_INVALID, + LEXEME_KINDS () + LEXEME_KIND_COUNT, + LEXEME_KIND_END_OF_FILE, +}; +#undef X + +#define KEYWORDS() \ + X (FOR, "for") \ + X (DO, "do") + +#define COMPARISONS() \ + X (EQUALS, "=") \ + X (LESS_THAN, "<") \ + X (GREATER_THAN, ">") + +#define X(SYM, ...) KEYWORD_##SYM, +enum keyword { KEYWORDS () KEYWORD_COUNT }; +#undef X + +#define X(SYM, ...) COMPARISON_##SYM, +enum comparison { COMPARISONS () COMPARISON_COUNT }; +#undef X + +struct lexeme { + struct string_view sv; + enum lexeme_kind kind; + union { + enum keyword keyword; + enum comparison comparison; + int integer; + float real; + uint32_t table_index; + } value; +}; + +extern const char *lexeme_kind_names[LEXEME_KIND_COUNT - 1]; +extern const char *keyword_names[KEYWORD_COUNT]; +extern const char *comparison_names[COMPARISON_COUNT]; + +#endif diff --git a/src/lexer.c b/src/lexer.c new file mode 100644 index 0000000..a219c91 --- /dev/null +++ b/src/lexer.c @@ -0,0 +1,172 @@ +#include "lexer.h" +#include +#include +#include +#include +#include +#include "dynamic-array.h" + +#define X(SYM, STR, REG) [LEXEME_KIND_##SYM - 1] = "^(" REG ")", +static const char *lexeme_regex_strings[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X + +static regex_t lexeme_regexes[LEXEME_KIND_COUNT - 1]; + +static void +print_regex_error (const regex_t *comp, const char *regex, int errcode) +{ + size_t length = regerror (errcode, comp, NULL, 0); + char *buffer = malloc (length); + regerror (errcode, comp, buffer, length); + fprintf (stderr, "error: regcomp (\"%s\"): %s\n", + regex, buffer); + free (buffer); +} + +static void __attribute__((constructor)) +compile_regexes (void) +{ + for (enum lexeme_kind kind = 1; kind < LEXEME_KIND_COUNT; ++kind) { + int errcode = regcomp (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + REG_EXTENDED); + if (errcode) { + print_regex_error (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + errcode); + exit (1); + } + } +} + +struct lexer +lexer_create (const char *string, size_t len) +{ + return (struct lexer) { + .sv = { + .beg = string, + .end = string + len, + }, + .cursor = string, + .beginning_of_line = string, + .line = 0, + }; +} + +static void +lexer_skip_whitespace (struct lexer *lexer) +{ + while (lexer->cursor < lexer->sv.end && isspace (*lexer->cursor)) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} + +static void +lexer_progress_cursor_by (struct lexer *lexer, int count) +{ + const char *end = lexer->cursor + count; + ASSERT (end <= lexer->sv.end); + + while (lexer->cursor < end) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} + +struct lexeme +lexer_next_lexeme (struct lexer *lexer) +{ + lexer_skip_whitespace (lexer); + struct lexeme lexeme = { .sv.beg = lexer->cursor }; + + if (lexer->cursor >= lexer->sv.end) { + lexeme.kind = LEXEME_KIND_END_OF_FILE; + lexeme.sv.end = lexer->cursor; + return lexeme; + } + + regmatch_t regmatch; + enum lexeme_kind longest_matching_lexeme_kind = LEXEME_KIND_INVALID; + int longest_matching_lexeme_kind_length = 0; + for (enum lexeme_kind lexeme_kind = 1; lexeme_kind < LEXEME_KIND_COUNT; ++lexeme_kind) { + if (regexec (&lexeme_regexes[lexeme_kind - 1], lexer->cursor, 1, ®match, 0)) continue; + if (regmatch.rm_eo <= longest_matching_lexeme_kind_length) continue; + longest_matching_lexeme_kind_length = regmatch.rm_eo; + longest_matching_lexeme_kind = lexeme_kind; + } + + if (longest_matching_lexeme_kind) { + lexeme.kind = longest_matching_lexeme_kind; + lexer_progress_cursor_by (lexer, longest_matching_lexeme_kind_length); + lexeme.sv.end = lexer->cursor; + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: { + for (enum keyword keyword = 0; keyword < KEYWORD_COUNT; ++keyword) { + struct string_view keyword_sv = { + .beg = keyword_names[keyword], + .end = keyword_names[keyword] + strlen (keyword_names[keyword]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, keyword_sv)) continue; + + lexeme.value.table_index = keyword; + } + } break; + case LEXEME_KIND_SYMBOL_COMPARISON: { + for (enum comparison comparison = 0; comparison < COMPARISON_COUNT; ++comparison) { + struct string_view comparison_sv = { + .beg = comparison_names[comparison], + .end = comparison_names[comparison] + strlen (comparison_names[comparison]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, comparison_sv)) continue; + + lexeme.value.table_index = comparison; + } + } break; + case LEXEME_KIND_CONSTANT_INTEGER: { + TODO ("fix overflow"); + lexeme.value.integer = strtol (lexeme.sv.beg, NULL, 10); + } break; + case LEXEME_KIND_CONSTANT_REAL: + TODO ("fix overflow"); + lexeme.value.real = strtof (lexeme.sv.beg, NULL); + break; + case LEXEME_KIND_CONSTANT_STRING: { + struct string_view sv = { + .beg = lexeme.sv.beg + 1, + .end = lexeme.sv.end - 1, + }; + DYNAMIC_ARRAY_FOREACH (e, lexer->constant_string_table) { + if (STRING_VIEW_EQUALS (sv, *e)) { + lexeme.value.table_index = e - lexer->constant_string_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->constant_string_table.count; + DYNAMIC_ARRAY_APPEND (lexer->constant_string_table, sv); + } break; + case LEXEME_KIND_IDENTIFIER: { + DYNAMIC_ARRAY_FOREACH (e, lexer->identifier_table) { + if (STRING_VIEW_EQUALS (lexeme.sv, *e)) { + lexeme.value.table_index = e - lexer->identifier_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->identifier_table.count; + DYNAMIC_ARRAY_APPEND (lexer->identifier_table, lexeme.sv); + } break; + default: + break; + } + + return lexeme; + } + + lexeme.sv.end = ++lexer->cursor; + return lexeme; +} diff --git a/src/lexer.h b/src/lexer.h new file mode 100644 index 0000000..563dc60 --- /dev/null +++ b/src/lexer.h @@ -0,0 +1,26 @@ +#ifndef INCLUDED_LEXER_H +#define INCLUDED_LEXER_H + +#include +#include "utils.h" +#include "lexeme.h" + +struct string_view_table { + struct string_view *items; + uint32_t count; + uint32_t capacity; +}; + +struct lexer { + struct string_view sv; + const char *cursor; + const char *beginning_of_line; + size_t line; + struct string_view_table constant_string_table; + struct string_view_table identifier_table; +}; + +extern struct lexer lexer_create (const char *string, size_t len); +extern struct lexeme lexer_next_lexeme (struct lexer *); + +#endif diff --git a/src/string-builder.c b/src/string-builder.c new file mode 100644 index 0000000..5880da8 --- /dev/null +++ b/src/string-builder.c @@ -0,0 +1,41 @@ +#include "string-builder.h" +#include +#include + +void +string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n) +{ + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n); + memset (sb->items + sb->count, c, n); + sb->count += n; +} + +void +string_builder_append_cstrs (STRING_BUILDER sb, ...) +{ + va_list args; + + va_start (args, sb); + const char *arg = va_arg (args, const char *); + while (arg) { + STRING_BUILDER_APPEND_CSTR(*sb, arg); + arg = va_arg (args, const char *); + } va_end (args); +} + +void +string_builder_printf (STRING_BUILDER sb, const char *format, ...) +{ + va_list args; + + va_start (args, format); + int size = vsnprintf (NULL, 0, format, args); + va_end (args); + ASSERT (size >= 0); + + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1); + va_start (args, format); + vsnprintf (&sb->items[sb->count], size + 1, format, args); + va_end (args); + sb->count += size; +} diff --git a/src/string-builder.h b/src/string-builder.h new file mode 100644 index 0000000..6834eed --- /dev/null +++ b/src/string-builder.h @@ -0,0 +1,42 @@ +#ifndef INCLUDED_STRING_BUILDER_H +#define INCLUDED_STRING_BUILDER_H + +#include +#include +#include "utils.h" +#include "dynamic-array.h" + +struct string_builder { + char *items; + size_t count; + size_t capacity; +}; +#define STRING_BUILDER struct string_builder * + +#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \ + DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE) + +#define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \ + ({ \ + const char *s = (CSTR); \ + size_t n = strlen (s); \ + DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \ + }) + +#define STRING_BUILDER_APPEND_CSTRS(SB, ...) \ + string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL) + +#define STRING_BUILDER_APPEND_NULL(SB) \ + DYNAMIC_ARRAY_APPEND (SB, '\0') + +#define STRING_BUILDER_RESET(SB) \ + DYNAMIC_ARRAY_RESET (SB) + +#define STRING_BUILDER_FREE(SB) \ + DYNAMIC_ARRAY_FREE(SB) + +extern void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n); +extern void string_builder_append_cstrs (STRING_BUILDER, ...); +extern void string_builder_printf (STRING_BUILDER, const char *format, ...); + +#endif diff --git a/src/string-view.h b/src/string-view.h new file mode 100644 index 0000000..c745d12 --- /dev/null +++ b/src/string-view.h @@ -0,0 +1,16 @@ +#ifndef INCLUDED_STRING_VIEW_H +#define INCLUDED_STRING_VIEW_H + +#include + +struct string_view { + const char *beg; + const char *end; +}; + +#define STRING_VIEW_LEN(SV) ((SV).end - (SV).beg) +#define STRING_VIEW_EQUALS(A, B) \ + (STRING_VIEW_LEN (A) == STRING_VIEW_LEN (B) && \ + !memcmp ((A).beg, (B).beg, STRING_VIEW_LEN (A))) + +#endif // INCLUDED_STRING_VIEW_H diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..68bb2b5 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,26 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include + +#define UNUSED(X) ((void) (X)) +#define UNREACHABLE() ASSERT (!"reached the unreachable...") +// #define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__) +#define TODO(...) + +#define ASSERT assert +#define REALLOC realloc +#define FREE free + +#define DIE(FMT, ...) \ + ({ \ + fprintf (stderr, FMT "\n" __VA_OPT__(,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + }) + +#define ARRAY_LEN(array) (sizeof (array)/sizeof (*array)) +#define ARRAY_GET(array, index) \ + (ASSERT(index >= 0), ASSERT(index < ARRAY_LEN(array)), array[index]) + +#endif -- cgit v1.3.1