From 6ecea40c849effd171c1d27c961f5c1ee100481f Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sun, 8 Nov 2026 09:02:38 +0300 Subject: publish --- src/bnf-lexeme.c | 10 + src/bnf-lexeme.h | 35 ++ src/bnf-lexer.c | 101 ++++ src/bnf-lexer.h | 18 + src/bnf-parser.c | 191 ++++++++ src/bnf-parser.h | 51 ++ src/bnf-preprocessor.c | 76 +++ src/bnf-preprocessor.h | 8 + src/dynamic-array.h | 75 +++ src/generate-grammar.c | 391 +++++++++++++++ src/main.c | 1225 ++++++++++++++++++++++++++++++++++++++++++++++ src/slovak-adjective.bnf | 97 ++++ src/slovak-adverb.bnf | 3 + src/slovak-noun.bnf | 321 ++++++++++++ src/slovak-object.bnf | 56 +++ src/slovak-sentence.bnf | 43 ++ src/slovak-verb.bnf | 113 +++++ src/string-builder.c | 41 ++ src/string-builder.h | 48 ++ src/string-view.h | 17 + src/utils.h | 37 ++ 21 files changed, 2957 insertions(+) create mode 100644 src/bnf-lexeme.c create mode 100644 src/bnf-lexeme.h create mode 100644 src/bnf-lexer.c create mode 100644 src/bnf-lexer.h create mode 100644 src/bnf-parser.c create mode 100644 src/bnf-parser.h create mode 100644 src/bnf-preprocessor.c create mode 100644 src/bnf-preprocessor.h create mode 100644 src/dynamic-array.h create mode 100644 src/generate-grammar.c create mode 100644 src/main.c create mode 100644 src/slovak-adjective.bnf create mode 100644 src/slovak-adverb.bnf create mode 100644 src/slovak-noun.bnf create mode 100644 src/slovak-object.bnf create mode 100644 src/slovak-sentence.bnf create mode 100644 src/slovak-verb.bnf 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/bnf-lexeme.c b/src/bnf-lexeme.c new file mode 100644 index 0000000..22ab39d --- /dev/null +++ b/src/bnf-lexeme.c @@ -0,0 +1,10 @@ +#include "bnf-lexeme.h" + +#define X(SYM, ...) [BNF_LEXEME_KIND_##SYM] = #SYM, +const char *bnf_lexeme_kind_names[BNF_LEXEME_KIND_COUNT] = { + BNF_LEXEME_KINDS () + [BNF_LEXEME_KIND_END_OF_LINE] = "END_OF_LINE", + [BNF_LEXEME_KIND_END_OF_FILE] = "END_OF_FILE", + [BNF_LEXEME_KIND_INVALID ] = "INVALID", +}; +#undef X diff --git a/src/bnf-lexeme.h b/src/bnf-lexeme.h new file mode 100644 index 0000000..20c532c --- /dev/null +++ b/src/bnf-lexeme.h @@ -0,0 +1,35 @@ +#ifndef INCLUDED_BNF_LEXEME_H +#define INCLUDED_BNF_LEXEME_H + +#include +#include +#include "utils.h" +#include "string-view.h" + +#define BNF_LEXEME_KINDS() \ + X (TERMINAL, "\"[^\"]*\"|'[^']*'") \ + X (NONTERMINAL, "<[^>]*>" ) \ + X (SYMBOL_ALTERNATIVE, "\\|" ) \ + X (SYMBOL_IS_REPLACED_BY, "::=" ) \ + X (COMMENT, "#[^\n]*" ) + +#define X(SYM, ...) BNF_LEXEME_KIND_##SYM, +enum bnf_lexeme_kind { + BNF_LEXEME_KINDS () + BNF_LEXEME_KIND_END_OF_LINE, + BNF_LEXEME_KIND_END_OF_FILE, + BNF_LEXEME_KIND_INVALID, + BNF_LEXEME_KIND_COUNT, +}; +#undef X + +#define BNF_LEXEME_REGEX_COUNT (BNF_LEXEME_KIND_COUNT - 3) + +struct bnf_lexeme { + struct string_view sv; + enum bnf_lexeme_kind kind; +}; + +extern const char *bnf_lexeme_kind_names[BNF_LEXEME_KIND_COUNT]; + +#endif // INCLUDED_BNF_LEXEME_H diff --git a/src/bnf-lexer.c b/src/bnf-lexer.c new file mode 100644 index 0000000..f859af9 --- /dev/null +++ b/src/bnf-lexer.c @@ -0,0 +1,101 @@ +#include "bnf-lexer.h" +#include +#include +#include +#include +#include +#include "dynamic-array.h" + +#define X(SYM, REG, ...) [BNF_LEXEME_KIND_##SYM] = "^(" REG ")", +static const char *lexeme_regex_strings[BNF_LEXEME_REGEX_COUNT] = { BNF_LEXEME_KINDS () }; +#undef X + +static regex_t lexeme_regexes[BNF_LEXEME_REGEX_COUNT]; + +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 bnf_lexeme_kind kind = 0; kind < BNF_LEXEME_REGEX_COUNT; ++kind) { + regex_t *compiled = &lexeme_regexes[kind]; + const char *pattern = lexeme_regex_strings[kind]; + int errcode = regcomp (compiled, pattern, REG_EXTENDED); + if (errcode) { + print_regex_error (compiled, pattern, errcode); + exit (1); + } + } +} + +struct bnf_lexer +bnf_lexer_from_string_view (struct string_view sv, const char *filename) +{ + return (struct bnf_lexer) { + .sv = sv, + .cursor = sv.beg, + .filename = filename, + }; +} + +static void +lexer_skip_whitespace (struct bnf_lexer *lexer) +{ + while (lexer->cursor < lexer->sv.end && (*lexer->cursor == ' ' || + *lexer->cursor == '\t')) + lexer->cursor += 1; +} + +struct bnf_lexeme +bnf_lexer_next_lexeme (struct bnf_lexer *lexer) +{ + lexer_skip_whitespace (lexer); + struct bnf_lexeme lexeme = { + .sv.beg = lexer->cursor, + .kind = BNF_LEXEME_KIND_INVALID, + }; + + if (lexer->cursor >= lexer->sv.end) { + lexeme.kind = BNF_LEXEME_KIND_END_OF_FILE; + lexeme.sv.end = lexer->sv.end; + return lexeme; + } + + if (*lexer->cursor == '\n') { + lexeme.kind = BNF_LEXEME_KIND_END_OF_LINE; + lexeme.sv.end = ++lexer->cursor; + return lexeme; + } + + regmatch_t regmatch; + enum bnf_lexeme_kind longest_matching_lexeme_kind = BNF_LEXEME_KIND_INVALID; + int longest_matching_lexeme_kind_length = 0; + for (enum bnf_lexeme_kind kind = 0; kind < BNF_LEXEME_REGEX_COUNT; ++kind) { + if (regexec (&lexeme_regexes[kind], 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 = kind; + } + + if (longest_matching_lexeme_kind != BNF_LEXEME_KIND_INVALID) { + lexeme.kind = longest_matching_lexeme_kind; + lexeme.sv.end = lexer->cursor += longest_matching_lexeme_kind_length; + + switch (lexeme.kind) { + case BNF_LEXEME_KIND_COMMENT: return bnf_lexer_next_lexeme (lexer); + default: return lexeme; + } + } + + lexeme.sv.end = ++lexer->cursor; + return lexeme; +} diff --git a/src/bnf-lexer.h b/src/bnf-lexer.h new file mode 100644 index 0000000..5863219 --- /dev/null +++ b/src/bnf-lexer.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_BNF_LEXER_H +#define INCLUDED_BNF_LEXER_H + +#include +#include "utils.h" +#include "bnf-lexeme.h" + +struct bnf_lexer { + struct string_view sv; + const char *cursor; + const char *filename; +}; + +extern struct bnf_lexer bnf_lexer_from_string_view (struct string_view, const char *filename); +extern struct bnf_lexer bnf_lexer_from_filename (const char *); +extern struct bnf_lexeme bnf_lexer_next_lexeme (struct bnf_lexer *); + +#endif // INCLUDED_BNF_LEXER_H diff --git a/src/bnf-parser.c b/src/bnf-parser.c new file mode 100644 index 0000000..7aa26f0 --- /dev/null +++ b/src/bnf-parser.c @@ -0,0 +1,191 @@ +#include +#include "bnf-parser.h" +#include "dynamic-array.h" + +void +print_error (struct bnf_lexer *lexer, const char *point, + const char *template, ...) +{ + int row = 1; + int col = 0; + + for (const char *head = lexer->sv.beg; head < point; ++head) { + col += 1; + if (*head == '\n') { + row += 1; + col = 0; + } + }; + + fprintf (stderr, "%s:%d:%d: error: ", lexer->filename, row, col); + + va_list ap; + va_start (ap, template); + vfprintf (stderr, template, ap); + va_end (ap); + + putc ('\n', stderr); +} + +bool +is_bnf_lexeme_valid (struct bnf_lexeme lexeme) +{ + return lexeme.kind != BNF_LEXEME_KIND_INVALID; +} + +bool +bnf_parse_lexeme (struct bnf_lexer *lexer, enum bnf_lexeme_kind kind) +{ + const char *checkpoint = lexer->cursor; + struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer); + + if (lexeme.kind != kind) goto revert; + + return true; + +revert: + lexer->cursor = checkpoint; + return false; +} + +struct bnf_lexeme +bnf_parse_nonterminal (struct bnf_lexer *lexer) +{ + const char *checkpoint = lexer->cursor; + struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer); + if (lexeme.kind == BNF_LEXEME_KIND_NONTERMINAL) + return lexeme; + +revert: + lexer->cursor = checkpoint; + return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID }; +} + +struct bnf_lexeme +bnf_parse_terminal (struct bnf_lexer *lexer) +{ + const char *checkpoint = lexer->cursor; + + struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer); + if (lexeme.kind == BNF_LEXEME_KIND_TERMINAL) + return lexeme; + +revert: + lexer->cursor = checkpoint; + return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID }; +} + +bool +is_bnf_sequence_valid (struct bnf_sequence sequence) +{ + return sequence.term_count != 0; +} + +struct bnf_sequence +bnf_parse_sequence (struct bnf_lexer *lexer) +{ + struct bnf_sequence sequence = {0}; + const char *checkpoint = lexer->cursor; + + for (;;) { + struct bnf_lexeme lexeme = bnf_parse_nonterminal (lexer); + if (!is_bnf_lexeme_valid (lexeme)) + lexeme = bnf_parse_terminal (lexer); + if (!is_bnf_lexeme_valid (lexeme)) + break; + + DYNAMIC_ARRAY_APPEND (sequence, lexeme); + } if (!is_bnf_sequence_valid (sequence)) goto revert; + + if (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_ALTERNATIVE) || + bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE)) + return sequence; + +revert: + DYNAMIC_ARRAY_FREE (sequence); + lexer->cursor = checkpoint; + return (struct bnf_sequence) {0}; +} + +bool +is_bnf_rule_valid (struct bnf_rule rule) +{ + return rule.is_replaced_by.sequence_count != 0; +} + +struct bnf_rule +bnf_parse_rule (struct bnf_lexer *lexer) +{ + struct bnf_rule rule = {0}; + const char *checkpoint = lexer->cursor; + + rule.name = bnf_parse_nonterminal (lexer); + if (!is_bnf_lexeme_valid (rule.name)) + goto revert; + + if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_IS_REPLACED_BY)) + goto revert; + + for (;;) { + struct bnf_sequence sequence = bnf_parse_sequence (lexer); + if (!is_bnf_sequence_valid (sequence)) break; + DYNAMIC_ARRAY_APPEND (rule.is_replaced_by, sequence); + } if (is_bnf_rule_valid (rule)) return rule; + +revert: + DYNAMIC_ARRAY_FREE (rule.is_replaced_by); + lexer->cursor = checkpoint; + return (struct bnf_rule) {0}; +} + +struct bnf_syntax +bnf_parse_syntax (struct bnf_lexer *lexer) +{ + struct bnf_syntax syntax = {0}; + + for (;;) { + while (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE)); + struct bnf_rule rule = bnf_parse_rule (lexer); + if (!is_bnf_rule_valid (rule)) { + if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_FILE)) { + print_error (lexer, lexer->cursor, "unable to parse rule"); + } + break; + } + + DYNAMIC_ARRAY_APPEND (syntax, rule); + } + + return syntax; +} + +bool +bnf_check_syntax (struct bnf_lexer *lexer, struct bnf_syntax syntax) +{ + bool no_errors = true; + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) { + DYNAMIC_ARRAY_FOREACH (term, *sequence) { + if (term->kind != BNF_LEXEME_KIND_NONTERMINAL) continue; + if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR (""))) continue; + if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR (""))) continue; + + bool rule_found = false; + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + if (!STRING_VIEW_EQUALS (rule->name.sv, term->sv)) continue; + rule_found = true; + break; + } + + if (!rule_found) { + no_errors = false; + print_error (lexer, term->sv.beg, + "rule not found: %.*s", + (int) STRING_VIEW_LEN (term->sv), term->sv.beg); + } + } + } + } + + return no_errors; +} diff --git a/src/bnf-parser.h b/src/bnf-parser.h new file mode 100644 index 0000000..db9804d --- /dev/null +++ b/src/bnf-parser.h @@ -0,0 +1,51 @@ +#ifndef INCLUDED_BNF_PARSER_H +#define INCLUDED_BNF_PARSER_H + +#include +#include +#include "bnf-lexer.h" + +struct bnf_sequence { + union { struct bnf_lexeme *items, *terms; }; + union { uint32_t count, term_count; }; + uint32_t capacity; +}; + +struct bnf_rule { + struct bnf_lexeme name; + struct { + union { struct bnf_sequence *items, *sequences; }; + union { uint32_t count, sequence_count; }; + uint32_t capacity; + } is_replaced_by; +}; + +struct bnf_syntax { + union { struct bnf_rule *items, *rules; }; + union { uint32_t count, rule_count; }; + uint32_t capacity; +}; + +// struct term_table { +// union { struct bnf_lexeme *items, *terms; }; +// union { uint32_t count, term_count; }; +// uint32_t capacity; +// }; + +struct bnf_parser { + struct bnf_lexer lexer; +}; + +bool is_bnf_lexeme_valid (struct bnf_lexeme); +bool is_bnf_sequence_valid (struct bnf_sequence); +bool is_bnf_rule_valid (struct bnf_rule); + +bool bnf_check_syntax (struct bnf_lexer *, struct bnf_syntax); +bool bnf_parse_lexeme (struct bnf_lexer *, enum bnf_lexeme_kind); +struct bnf_lexeme bnf_parse_nonterminal (struct bnf_lexer *); +struct bnf_lexeme bnf_parse_terminal (struct bnf_lexer *); +struct bnf_sequence bnf_parse_sequence (struct bnf_lexer *); +struct bnf_rule bnf_parse_rule (struct bnf_lexer *); +struct bnf_syntax bnf_parse_syntax (struct bnf_lexer *); + +#endif // INCLUDED_BNF_PARSER_H diff --git a/src/bnf-preprocessor.c b/src/bnf-preprocessor.c new file mode 100644 index 0000000..67fafc7 --- /dev/null +++ b/src/bnf-preprocessor.c @@ -0,0 +1,76 @@ +#include "bnf-preprocessor.h" +#include "string-builder.h" +#include +#include +#include +#include +#include + +struct preprocessor { + struct { + struct open_file { + struct string_view sv; + const char *filename; + const char *cursor; + } *items; + uint32_t count; + uint32_t capacity; + } open_files; + struct string_builder sb; +}; + +static const char import_cstr[] = "import"; +static struct string_view import_sv = { + .beg = import_cstr, + .end = import_cstr + sizeof (import_cstr) - 1, +}; + + +static void +preprocess_file (struct string_builder *sb, const char *filename) +{ + struct string_view file_contents; + const char *cursor; + + int fd = open (filename, O_RDONLY); + if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename); + + struct stat st; + fstat (fd, &st); + cursor = file_contents.beg = + mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + close (fd); + file_contents.end = file_contents.beg + st.st_size; + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, STRING_VIEW_LEN (file_contents)); + + do { + if (*cursor == '!') { + cursor += 1; + while (*cursor == ' ') cursor += 1; + if () + while (*cursor != '\n') cursor += 1; + cursor += 1; + preprocess_file (sb, import_filename); + continue; + } + + DYNAMIC_ARRAY_APPEND_FAST (*sb, *cursor++); + } while (1); + + munmap ((char *) file_contents.beg, STRING_VIEW_LEN (file_contents)); +} + +struct string_view +bnf_preprocess_file (const char *filename) +{ + struct string_builder sb = {0}; + + preprocess_file (&sb, filename); + + struct string_view output = { + .beg = sb.string, + .end = sb.string + sb.count, + }; + + return output; +} diff --git a/src/bnf-preprocessor.h b/src/bnf-preprocessor.h new file mode 100644 index 0000000..6181137 --- /dev/null +++ b/src/bnf-preprocessor.h @@ -0,0 +1,8 @@ +#ifndef INCLUDED_BNF_PREPROCESSOR_H +#define INCLUDED_BNF_PREPROCESSOR_H + +#include "string-view.h" + +struct string_view bnf_preprocess_file (const char *filename); + +#endif // INCLUDED_BNF_PREPROCESSOR_H diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..1329995 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,75 @@ +#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_FAST(DA, ITEM) \ + (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_APPEND_DYNAMIC_ARRAY(TO, FROM) \ + DYNAMIC_ARRAY_APPEND_MANY ((TO), \ + (FROM).items, \ + (FROM).count) + +#define DYNAMIC_ARRAY_LAST(DA) \ + (DA).items[(DA).count - 1] + +#define DYNAMIC_ARRAY_POP(DA) \ + (DA).items[--(DA).count] + +#define DYNAMIC_ARRAY_RESET(DA) ({ (DA).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DA) FREE((DA).items) + +// NOTE(cmmm): resizing will invalidate! +#define DYNAMIC_ARRAY_FOREACH(ITEM, DA) for ( \ + typeof ((DA).items) ITEM = (DA).items; \ + ITEM < (DA).items + (DA).count; ++ITEM) + +#define DYNAMIC_ARRAY_FOREACH_REVERSED(ITEM, DA) for ( \ + typeof ((DA).items) ITEM = &DYNAMIC_ARRAY_LAST (DA); \ + ITEM >= (DA).items; --ITEM) + +#endif // INCLUDED_DYNAMIC_ARRAY_H diff --git a/src/generate-grammar.c b/src/generate-grammar.c new file mode 100644 index 0000000..d4d0132 --- /dev/null +++ b/src/generate-grammar.c @@ -0,0 +1,391 @@ +#include +#include + +int +main (int argc, char *argv[]) +{ + FILE *fp = stdout; + + verb { + imperfective { + indicative { + present { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + past { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + future { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + conditional { + present { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + past { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + }; + imperative { + sg { + p2; + }; + pl { + p1; + p2; + }; + }; + participle { + sg { + masculine; + feminine; + neuter; + }; + pl { + masculine { + animate; + inanimate; + }; + feminine; + neuter; + }; + }; + }; + perfective { + indicative { + present { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + past { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + }; + conditional { + present { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + past { + masculine { + sg { + p1; + p2; + p3; + }; + pl { + p1 { + animate; + inanimate; + }; + p2 { + animate; + inanimate; + }; + p3 { + animate; + inanimate; + }; + }; + }; + feminine { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + neuter { + sg { + p1; + p2; + p3; + }; + pl { + p1; + p2; + p3; + }; + }; + }; + }; + imperative { + sg { + p2; + }; + pl { + p1; + p2; + }; + }; + participle { + sg { + masculine; + feminine; + neuter; + }; + pl { + masculine { + animate; + inanimate; + }; + feminine; + neuter; + }; + }; + }; + }; + + return EXIT_SUCCESS; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..b17fbbc --- /dev/null +++ b/src/main.c @@ -0,0 +1,1225 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bnf-parser.h" +#include "utils.h" +#include "dynamic-array.h" +#include "string-builder.h" +#include "string-view.h" + +#define TERMINAL_COUNT (256 + 2) // ASCII + + + +struct string_builder sb = {0}; + +static struct string_view +load_file (const char *filename) +{ + struct string_view file_contents; + + int fd = open (filename, O_RDONLY); + if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename); + + struct stat st; + fstat (fd, &st); + file_contents.beg = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + close (fd); + file_contents.end = file_contents.beg + st.st_size; + + return file_contents; +} + +static void +unload_file (struct string_view sv) +{ + munmap ((char *) sv.beg, STRING_VIEW_LEN (sv)); +} + +static void print_term (struct bnf_syntax syntax, + struct string_builder *sb, + struct bnf_lexeme term); + +static void +print_nonterminal (struct bnf_syntax syntax, + struct string_builder *sb, + struct string_view sv) +{ + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + if (!STRING_VIEW_EQUALS (rule->name.sv, sv)) continue; + + struct bnf_sequence sequence = + rule->is_replaced_by.items[rand () % rule->is_replaced_by.count]; + DYNAMIC_ARRAY_FOREACH (term, sequence) { + print_term (syntax, sb, *term); + } + + return; + } + + printf ("%.*s\n", (int) STRING_VIEW_LEN (sv), sv.beg); + UNREACHABLE (); +} + +static void +print_terminal (struct string_view sv, struct string_builder *sb) +{ + sv.beg += 1; + sv.end -= 1; + STRING_BUILDER_APPEND_STRING_VIEW (*sb, sv); +} + +static void +print_term (struct bnf_syntax syntax, struct string_builder *sb, struct bnf_lexeme term) +{ + switch (term.kind) { + case BNF_LEXEME_KIND_TERMINAL: + print_terminal (term.sv, sb); + break; + case BNF_LEXEME_KIND_NONTERMINAL: + if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR (""))) { + printf ("\n"); + } else if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR (""))) { + } else { + print_nonterminal (syntax, sb, term.sv); + } break; + default: UNREACHABLE (); + } +} + +static void +print_random_rule (struct bnf_syntax syntax, const char *rule) +{ + STRING_BUILDER_RESET (sb); + print_nonterminal (syntax, &sb, STRING_VIEW_FROM_CSTR (rule)); + sb.string[0] = toupper (sb.string[0]); + STRING_BUILDER_APPEND_NULL (sb); + printf ("%s", sb.string); +} + +static void +save_dot (struct bnf_syntax syntax) +{ + FILE *fp = fopen ("./tmp/slovak.dot", "w"); + + fprintf (fp, "digraph slovak {" "\n"); { + fprintf (fp, "\t" "fontname=\"Aporetic Serif,serif\"" "\n"); + fprintf (fp, "\t" "node [fontname=\"Aporetic Sans,sans-serif\"]" "\n"); + fprintf (fp, "\t" "edge [fontname=\"Aporetic Serif Mono,mono\"]" "\n"); + fprintf (fp, "\t" "rankdir=TD" "\n"); + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + fprintf (fp, "\t" "rule_%ld [label=\"%.*s\"]" "\n", + rule - syntax.items, + (int) STRING_VIEW_LEN (rule->name.sv), rule->name.sv.beg); + DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) { + fprintf (fp, "\t" "sequence_%ld_%ld [label=\"%ld\"]" "\n", + rule - syntax.items, + sequence - rule->is_replaced_by.items, + sequence - rule->is_replaced_by.items); + fprintf (fp, "\t" "rule_%ld -> sequence_%ld_%ld" "\n", + rule - syntax.items, + rule - syntax.items, + sequence - rule->is_replaced_by.items); + DYNAMIC_ARRAY_FOREACH (term, *sequence) { + fprintf (fp, "\t" "sequence_%ld_%ld -> term_%ld_%ld_%ld" "\n", + rule - syntax.items, + sequence - rule->is_replaced_by.items, + rule - syntax.items, + sequence - rule->is_replaced_by.items, + term - sequence->items); + STRING_BUILDER_RESET (sb); + switch (term->kind) { + case BNF_LEXEME_KIND_TERMINAL: + STRING_BUILDER_APPEND_CSTR (sb, "\\\""); + STRING_BUILDER_APPEND_STRING_VIEW ( + sb, ((struct string_view) { + .beg = term->sv.beg + 1, + .end = term->sv.end - 1, + })); + STRING_BUILDER_APPEND_CSTR (sb, "\\\""); + break; + case BNF_LEXEME_KIND_NONTERMINAL: + STRING_BUILDER_APPEND_STRING_VIEW (sb, term->sv); + break; + default: UNREACHABLE (); + } + STRING_BUILDER_APPEND_NULL (sb); + fprintf (fp, "\t" "term_%ld_%ld_%ld [label=\"%s\"]" "\n", + rule - syntax.items, + sequence - rule->is_replaced_by.items, + term - sequence->items, + sb.string); + } + } + } + } fprintf (fp, "}\n"); + + fclose (fp); +} + +static +void print_bnf (struct bnf_syntax syntax) +{ + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + printf ("%.*s ::=", + (int) STRING_VIEW_LEN (rule->name.sv), rule->name.sv.beg); + DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) { + if (sequence != rule->is_replaced_by.items) + printf (" |"); + DYNAMIC_ARRAY_FOREACH (term, *sequence) { + printf (" %.*s", (int) STRING_VIEW_LEN (term->sv), term->sv.beg); + } + } printf ("\n"); + } +} + +typedef uint32_t symbol; + +struct symbols { + symbol *items; + uint32_t count; + uint32_t capacity; +}; + +struct production { + symbol from; + struct symbols to; +}; + +struct productions { + struct production *items; + uint32_t count; + uint32_t capacity; +}; + +struct selections { + struct selection { + symbol input; + uint32_t production; + } *items; + uint32_t count; + uint32_t capacity; +}; + +struct nonterminal { + const char *name; + struct selections selections; +}; + +struct nonterminals { + struct nonterminal *items; + uint32_t count; + uint32_t capacity; +}; + +// struct terminals { +// const char **items; +// uint32_t count; +// uint32_t capacity; +// }; + +struct grammar { + symbol initial_nonterminal; + struct nonterminals nonterminals; + // struct terminals terminals; + struct productions productions; +}; + +static struct grammar +build_grammar (struct bnf_syntax syntax) +{ + struct grammar grammar = { .initial_nonterminal = TERMINAL_COUNT }; + + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + size_t nonterminal_name_len = STRING_VIEW_LEN (rule->name.sv) - 2; + char *nonterminal_name = malloc (nonterminal_name_len + 1); + nonterminal_name[nonterminal_name_len] = '\0'; + memcpy (nonterminal_name, rule->name.sv.beg + 1, nonterminal_name_len); + DYNAMIC_ARRAY_APPEND (grammar.nonterminals, + ((struct nonterminal) { .name = nonterminal_name })); + } + + DYNAMIC_ARRAY_FOREACH (rule, syntax) { + symbol from = TERMINAL_COUNT + (rule - syntax.items); + DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) { + struct production production = { .from = from }; + DYNAMIC_ARRAY_FOREACH (term, *sequence) { + switch (term->kind) { + case BNF_LEXEME_KIND_TERMINAL: + for (const char *p = term->sv.beg + 1; p < term->sv.end - 1; ++p) + DYNAMIC_ARRAY_APPEND (production.to, (uint8_t) *p); + break; + case BNF_LEXEME_KIND_NONTERMINAL: + if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR (""))) { + DYNAMIC_ARRAY_APPEND (production.to, 256); + } else if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR (""))) { + DYNAMIC_ARRAY_APPEND (production.to, 257); + } else { + size_t term_len = STRING_VIEW_LEN (term->sv) - 2; + DYNAMIC_ARRAY_FOREACH (nonterminal, grammar.nonterminals) { + size_t nonterminal_name_len = strlen (nonterminal->name); + if (nonterminal_name_len != term_len) continue; + if (memcmp (nonterminal->name, term->sv.beg + 1, term_len)) continue; + DYNAMIC_ARRAY_APPEND (production.to, TERMINAL_COUNT + (nonterminal - grammar.nonterminals.items)); + break; + } + } break; + default: UNREACHABLE (); + }; + } + DYNAMIC_ARRAY_APPEND (grammar.productions, production); + } + } + + return grammar; +} + +static void +fprint_symbol (FILE *fp, struct grammar grammar, symbol symbol) +{ + if (symbol == ' ') { + fprintf (fp, "‿"); + } else if (symbol < 256) { + // printf ("0x%02X", symbol); + putc (symbol, fp); + } else if (symbol == 256) { + fprintf (fp, ""); + } else if (symbol == 257) { + fprintf (fp, ""); + } else { + fprintf (fp, "<%s>", grammar.nonterminals.items[symbol - TERMINAL_COUNT].name); + } +} + +static void +print_symbol (struct grammar grammar, symbol symbol) +{ + fprint_symbol (stdout, grammar, symbol); +} + +static void +print_symbols (struct grammar grammar, struct symbols symbols) +{ + bool printing_nonterminal = true; + if (symbols.count == 0) + printf ("\"\""); + DYNAMIC_ARRAY_FOREACH (symbol, symbols) { + if (printing_nonterminal && *symbol < 256) { + putchar ('"'); + printing_nonterminal = false; + } else if (!printing_nonterminal && *symbol >= 256) { + putchar ('"'); + printing_nonterminal = true; + } + print_symbol (grammar, *symbol); + } + if (!printing_nonterminal) + putchar ('"'); + printf ("\n"); +} + +static void +print_production (struct grammar grammar, struct production production) +{ + print_symbol (grammar, production.from); + printf (" -> "); + print_symbols (grammar, production.to); +} + +static void +print_grammar (struct grammar grammar) +{ + printf ("Initial nonterminal: "); + print_symbol (grammar, grammar.initial_nonterminal); + printf ("\n"); + DYNAMIC_ARRAY_FOREACH (production, grammar.productions) { + printf ("%lu. ", production - grammar.productions.items); + print_production (grammar, *production); + } +} + +static int +compare_production_pointers (const void *a, const void *b) +{ + const struct production *production_a = *(const struct production **) a; + const struct production *production_b = *(const struct production **) b; + + if (production_a->from < production_b->from) return +1; + if (production_a->from > production_b->from) return -1; + + struct symbols symbols_a = production_a->to; + struct symbols symbols_b = production_b->to; + + for (uint32_t i = 0; i < MIN (symbols_a.count, symbols_b.count); ++i) { + symbol symbol_a = symbols_a.items[i]; + symbol symbol_b = symbols_b.items[i]; + if (symbol_a == symbol_b) continue; + return (int) symbol_b - symbol_a; + } + + if (symbols_a.count < symbols_b.count) return +1; + if (symbols_a.count > symbols_b.count) return -1; + + return 0; +} + +static int +compare_symbols (const void *a, const void *b) +{ + const symbol symbol_a = *(const symbol *) a; + const symbol symbol_b = *(const symbol *) b; + + return symbol_a - symbol_b; +} + +static void +grammar_left_factor_common_prefixes (struct grammar *grammar) +{ + struct symbols handled = {0}; + + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + DYNAMIC_ARRAY_FOREACH (symbol, handled) { + if (*symbol == production->from) goto next_production; + } + + symbol from = production->from; + + size_t factored = 0; + factor_single: + struct { + struct production **items; + uint32_t count; + uint32_t capacity; + } same = {0}; + DYNAMIC_ARRAY_FOREACH (other, grammar->productions) { + if (other->from != from) continue; + DYNAMIC_ARRAY_APPEND (same, other); + } + + qsort (same.items, same.count, sizeof (same.items[0]), compare_production_pointers); + // puts ("same:"); + // DYNAMIC_ARRAY_FOREACH (prod, same) { + // print_production (*grammar, **prod); + // } + + DYNAMIC_ARRAY_FOREACH (production, same) { + if (production + 1 == same.items + same.count) break; + struct production *prod = *(production + 0); + struct production *next = *(production + 1); + + struct symbols prefix = {0}; + for (uint32_t i = 0; i < MIN (prod->to.count, next->to.count); ++i) { + if (prod->to.items[i] != next->to.items[i]) break; + DYNAMIC_ARRAY_APPEND (prefix, prod->to.items[i]); + } if (prefix.count == 0) continue; + + // printf ("prefix: "); + // print_symbols (*grammar, prefix); + + const char *nonterminal_name = grammar->nonterminals.items[prod->from - TERMINAL_COUNT].name; + size_t nonterminal_name_len = strlen (nonterminal_name); + char *nonterminal_name_new = malloc (nonterminal_name_len + 2 + factored); + symbol from_new = TERMINAL_COUNT + grammar->nonterminals.count; + memcpy (nonterminal_name_new, nonterminal_name, nonterminal_name_len); + for (size_t i = nonterminal_name_len; i < nonterminal_name_len + factored + 1; ++i) + nonterminal_name_new[i] = '\''; + nonterminal_name_new[nonterminal_name_len + factored + 1] = '\0'; + DYNAMIC_ARRAY_APPEND (grammar->nonterminals, + ((struct nonterminal) { .name = nonterminal_name_new })); + + struct production prod_new = { .from = prod->from }; + DYNAMIC_ARRAY_APPEND_MANY (prod_new.to, prefix.items, prefix.count); + DYNAMIC_ARRAY_APPEND (prod_new.to, from_new); + DYNAMIC_ARRAY_APPEND (grammar->productions, prod_new); + + struct { + struct production **items; + uint32_t count; + uint32_t capacity; + } rewrite = {0}; + DYNAMIC_ARRAY_APPEND (rewrite, prod); + DYNAMIC_ARRAY_APPEND (rewrite, next); + for (uint32_t i = production + 2 - same.items; i < same.count; ++i) { + struct production *p = same.items[i]; + if (p->to.count < prefix.count) continue; + if (memcmp (p->to.items, prefix.items, prefix.count*sizeof (*prefix.items))) continue; + DYNAMIC_ARRAY_APPEND (rewrite, p); + } + + DYNAMIC_ARRAY_FOREACH (p, rewrite) { + struct production *prod = *p; + prod->from = from_new; + memmove (prod->to.items, + prod->to.items + prefix.count, + (prod->to.count - prefix.count) * + sizeof (prod->to.items[0])); + prod->to.count -= prefix.count; + } + + factored += 1; + goto factor_single; + } + + DYNAMIC_ARRAY_APPEND (handled, production->from); + next_production: + } +} + +static bool +first (struct grammar grammar, struct symbols syms, struct symbols *set) +{ + if (syms.count == 0) return true; + + symbol first_sym = syms.items[0]; + if (first_sym < TERMINAL_COUNT) { + DYNAMIC_ARRAY_FOREACH (sym, *set) + if (*sym == first_sym) return false; + DYNAMIC_ARRAY_APPEND (*set, first_sym); + return false; + } + + bool has_epsilon = false; + DYNAMIC_ARRAY_FOREACH (production, grammar.productions) { + if (production->from != first_sym) continue; + has_epsilon = first (grammar, production->to, set); + } + + if (has_epsilon) { + syms.items += 1; + syms.count -= 1; + + return first (grammar, syms, set); + } + + return false; +} + +static void +follow (struct grammar grammar, symbol nonterm, struct symbols *set, struct symbols *stack) +{ + DYNAMIC_ARRAY_FOREACH (nt, *stack) + if (*nt == nonterm) return; + + DYNAMIC_ARRAY_APPEND (*stack, nonterm); + DYNAMIC_ARRAY_FOREACH (production, grammar.productions) { + DYNAMIC_ARRAY_FOREACH (sym, production->to) { + if (*sym != nonterm) continue; + if (sym == &DYNAMIC_ARRAY_LAST (production->to)) { + if (*sym == production->from) continue; + follow (grammar, production->from, set, stack); + continue; + } + + struct symbols syms = { + .items = sym + 1, + .count = production->to.count - (sym - production->to.items), + }; + if (first (grammar, syms, set)) + follow (grammar, production->from, set, stack); + } + } + stack->count -= 1; +} + +static void +build_lookup_table (struct grammar *grammar) +{ + struct symbols selection = {0}; + struct symbols stack = {0}; + DYNAMIC_ARRAY_FOREACH (nonterminal, grammar->nonterminals) { + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + if (production->from != TERMINAL_COUNT + nonterminal - grammar->nonterminals.items) continue; + // print_production (*grammar, *production); + selection.count = 0; + stack.count = 0; + if (first (*grammar, production->to, &selection)) + follow (*grammar, production->from, &selection, &stack); + + for (uint32_t i = 0; i < selection.count - 1; ++i) { + for (uint32_t j = i + 1; j < selection.count; ++j) { + if (selection.items[j] != selection.items[i]) continue; + selection.items[j] = selection.items[--selection.count]; + } + } + + // DYNAMIC_ARRAY_FOREACH (sym, selection) { + // if (*sym < 256) + // putchar (*sym); + // else if (*sym == 256) + // printf (""); + // else if (*sym == 257) + // printf (""); + // } printf ("\n"); + + DYNAMIC_ARRAY_FOREACH (sym, selection) { + DYNAMIC_ARRAY_APPEND ( + nonterminal->selections, + ((struct selection) { + .input = *sym, + .production = production - grammar->productions.items, + })); + } + } + } + DYNAMIC_ARRAY_FREE (selection); + DYNAMIC_ARRAY_FREE (stack); + + // DYNAMIC_ARRAY_FOREACH (nonterminal, grammar->nonterminals) { + // printf ("<%s> |", nonterminal->name); + // DYNAMIC_ARRAY_FOREACH (selection, nonterminal->selections) { + // if (selection->input == 256) + // printf (" -> %u |", selection->production); + // else if (selection->input == 257) + // printf (" -> %u |", selection->production); + // else + // printf (" %c -> %u |", selection->input, selection->production); + // } printf ("\n"); + // } +} + +struct tree { + struct children { + struct tree *items; + uint32_t count; + uint32_t capacity; + } children; + struct tree *parent; + const char *begin; + symbol symbol; +}; + +static struct tree * +tree_root (struct tree *tree) +{ + ASSERT (tree); + while (tree->parent) + tree = tree->parent; + return tree; +} + +static size_t +tree_count_terminals_within (struct tree *node) +{ + ASSERT (node); + + if (!node->begin) return 0; + + if (node->children.count == 0) + return node->symbol < TERMINAL_COUNT; // TODO: handle special symbols + + size_t sum = 0; + DYNAMIC_ARRAY_FOREACH (child, node->children) + sum += tree_count_terminals_within (child); + return sum; +} + +static size_t +tree_count_terminals_from_to (struct tree *from, struct tree *to) +{ + ASSERT (from); + ASSERT (to); + + if (from >= to) + return 0; + + if (from->children.count == 0) + return from->symbol < TERMINAL_COUNT; // TODO: handle special symbols + + size_t sum = 0; + DYNAMIC_ARRAY_FOREACH (child, from->children) + sum += tree_count_terminals_within (from); + return sum; +} + +static size_t +tree_count_terminals_up_to (struct tree *to) +{ + ASSERT (to); + return tree_count_terminals_from_to (tree_root (to), to); +} + +static void +print_tree_highlight (struct grammar grammar, + struct tree *tree, + struct tree *highlight, + int depth) +{ + ASSERT (tree); + + for (int i = 0; i < depth; ++i) + printf (" "); + printf (tree == highlight ? "+ " : " "); + if (tree->symbol < 256) putchar ('"'); + print_symbol (grammar, tree->symbol); + if (tree->symbol < 256) putchar ('"'); + if (tree->begin) + printf (" -> \"%.*s\"", + (int) tree_count_terminals_within (tree), tree->begin); + printf ("\n"); + DYNAMIC_ARRAY_FOREACH (child, tree->children) + print_tree_highlight (grammar, child, highlight, depth + 1); + if (depth == 0) + printf ("\n"); +} + +static void +print_tree (struct grammar grammar, struct tree *tree) +{ + ASSERT (tree); + print_tree_highlight (grammar, tree_root (tree), tree, 0); +} + +static struct tree * +tree_prev_leaf (struct tree *tree) +{ + ASSERT (tree); + + if (tree->children.count > 0) { + while (tree->parent && tree == tree->parent->children.items) + tree = tree->parent; + if (!tree->parent) return NULL; + tree -= 1; + while (tree->children.count > 0) + tree = &DYNAMIC_ARRAY_LAST (tree->children); + return tree; + } + + if (!tree->parent) return NULL; + if (tree > tree->parent->children.items) { + tree -= 1; + while (tree->children.count > 0) + tree = &DYNAMIC_ARRAY_LAST (tree->children); + return tree; + } + + return NULL; +} + +static struct tree * +tree_next_leaf (struct tree *tree) +{ + ASSERT (tree); + + if (tree->children.count > 0) { + do tree = tree->children.items; + while (tree->children.count > 0); + return tree; + } + + if (!tree->parent) return NULL; + + if (tree < &DYNAMIC_ARRAY_LAST (tree->parent->children)) { + tree += 1; + while (tree->children.count > 0) + tree = tree->children.items; + return tree; + } + + do tree = tree->parent; + while (tree->parent && tree == &DYNAMIC_ARRAY_LAST (tree->parent->children)); + if (!tree->parent) return NULL; + return tree + 1; +} + +static void +tree_remove_child (struct tree *child) +{ + while (child->parent && child->children.count == 0) { + struct tree *parent = child->parent; + if (child != &DYNAMIC_ARRAY_LAST (parent->children)) + memmove (child, child + 1, + (&DYNAMIC_ARRAY_LAST (parent->children) - child)*sizeof (*child)); + parent->children.count -= 1; + child = parent; + } +} + +static bool +parse_impl (struct grammar grammar, struct tree *leaf) +{ + do { + if (leaf->parent) { + leaf->begin = leaf->parent->begin; + DYNAMIC_ARRAY_FOREACH (child, leaf->parent->children) { + if (child == leaf) break; + leaf->begin += tree_count_terminals_within (child); + } + } + + if (leaf->symbol < TERMINAL_COUNT) { + if (!(*leaf->begin == '\n' && leaf->symbol == 256 || + *leaf->begin == '\0' && leaf->symbol == 257) && + (uint8_t) *leaf->begin != leaf->symbol) { + // printf ("didn't match %c (expected %c)\n", *leaf->begin, leaf->symbol); + return false; + }; + + // printf ("matched terminal "); + // print_symbol (grammar, leaf->symbol); + // printf ("\n"); + } else { // nonterminal + struct selections selections = + grammar.nonterminals.items[leaf->symbol - TERMINAL_COUNT].selections; + DYNAMIC_ARRAY_FOREACH (selection, selections) { + if (!(*leaf->begin == '\n' && selection->input == 256 || + *leaf->begin == '\0' && selection->input == 257 || + selection->input == (uint8_t) *leaf->begin)) + continue; + + struct production production = + grammar.productions.items[selection->production]; + if (production.to.count == 0) { + if (!leaf->parent) REACHED ("peculiar situation"); + // print_tree (grammar, leaf); + if (parse_impl (grammar, tree_next_leaf (leaf))) + return true; + } else { + DYNAMIC_ARRAY_FOREACH (sym, production.to) { + DYNAMIC_ARRAY_APPEND (leaf->children, ((struct tree) { + .symbol = *sym, + .parent = leaf, + })); + } + // print_tree (grammar, leaf); + if (parse_impl (grammar, tree_next_leaf (leaf))) + return true; + DYNAMIC_ARRAY_RESET (leaf->children); + } + } + // puts ("backtracking"); + return false; + } + } while (leaf = tree_next_leaf (leaf)); + return true; // only return true if fully parsed! +} + +static struct tree +parse (struct grammar grammar, const char *str) +{ + struct tree tree = { + .symbol = grammar.initial_nonterminal, + .begin = str, + }; + parse_impl (grammar, &tree); + return tree; +} + +static void +grammar_reduce (struct grammar *grammar) +{ + struct symbols reachable = {0}; + DYNAMIC_ARRAY_APPEND (reachable, grammar->initial_nonterminal); + for (uint32_t i = 0; i < reachable.count; ++i) { + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + if (production->from != reachable.items[i]) continue; + DYNAMIC_ARRAY_FOREACH (symbol, production->to) { + if (*symbol < TERMINAL_COUNT) continue; + DYNAMIC_ARRAY_FOREACH (nonterminal, reachable) + if (*nonterminal == *symbol) goto reachable_next_symbol; + DYNAMIC_ARRAY_APPEND (reachable, *symbol); + reachable_next_symbol: + } + } + } + + struct { + struct production **items; + uint32_t count; + uint32_t capacity; + } productive = {0}; + uint32_t added; + do { + added = productive.count; + + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + DYNAMIC_ARRAY_FOREACH (productive_production, productive) { + if (*productive_production == production) + goto productive_next_production; + } + + DYNAMIC_ARRAY_FOREACH (symbol, production->to) { + if (*symbol < TERMINAL_COUNT) continue; + DYNAMIC_ARRAY_FOREACH (productive_production, productive) { + if ((*productive_production)->from == *symbol) + goto productive_next_symbol; + } + goto productive_next_production; + productive_next_symbol: + } + + DYNAMIC_ARRAY_APPEND (productive, production); + productive_next_production: + } + + added = productive.count - added; + } while (added); + + // print_symbols (*grammar, reachable); + // DYNAMIC_ARRAY_FOREACH (production, productive) + // print_production (*grammar, **production); + + struct productions productions = {0}; + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + DYNAMIC_ARRAY_FOREACH (reachable_nonterminal, reachable) + if (*reachable_nonterminal == production->from) goto reachable; + DYNAMIC_ARRAY_FREE (production->to); + continue; + reachable: + DYNAMIC_ARRAY_FOREACH (productive_production, productive) + if (*productive_production == production) goto productive; + DYNAMIC_ARRAY_FREE (production->to); + continue; + productive: + DYNAMIC_ARRAY_APPEND (productions, *production); + } + DYNAMIC_ARRAY_FREE (grammar->productions); + grammar->productions = productions; +} + +static void +grammar_add_combinations (struct grammar *grammar, struct symbols input, + struct production output1, symbol sym, uint32_t remove) +{ + if (remove == 0) { + DYNAMIC_ARRAY_APPEND_MANY (output1.to, input.items, input.count); + DYNAMIC_ARRAY_APPEND (grammar->productions, output1); + return; + } + + while (input.count != 0 && input.items[0] != sym) { + DYNAMIC_ARRAY_APPEND (output1.to, input.items[0]); + input.items += 1; + input.count -= 1; + } + + if (input.count == 0) { + DYNAMIC_ARRAY_FREE (output1.to); + return; + } + + struct production output2 = { .from = output1.from }; + DYNAMIC_ARRAY_APPEND_MANY (output2.to, output1.to.items, output1.to.count); + DYNAMIC_ARRAY_APPEND (output1.to, input.items[0]); + input.items += 1; + input.count -= 1; + grammar_add_combinations (grammar, input, output1, sym, remove - 0); + grammar_add_combinations (grammar, input, output2, sym, remove - 1); +} + +static void +grammar_make_epsilon_free (struct grammar *grammar) +{ + bool has_initial_epsilon = false; + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + if (production->to.count != 0) continue; + if (production->from == grammar->initial_nonterminal) + has_initial_epsilon = true; + + symbol from = production->from; + if (production < &DYNAMIC_ARRAY_LAST (grammar->productions)) { + memmove (production, production + 1, + (&DYNAMIC_ARRAY_LAST (grammar->productions) - production) * + sizeof (*production)); + } + production -= 1; + grammar->productions.count -= 1; + + DYNAMIC_ARRAY_FOREACH (other_production, grammar->productions) { + uint32_t count = 0; + DYNAMIC_ARRAY_FOREACH (symbol, other_production->to) + if (*symbol == from) count += 1; + if (count == 0) continue; + + for (uint32_t i = 1; i <= count; ++i) { + grammar_add_combinations (grammar, other_production->to, + (struct production) { .from = other_production->from }, + from, i); + } + } + } + + if (has_initial_epsilon) { + symbol new_initial_nonterminal = TERMINAL_COUNT + grammar->nonterminals.count; + + const char *initial_nonterminal_name = + grammar->nonterminals.items[grammar->initial_nonterminal - TERMINAL_COUNT].name; + size_t initial_nonterminal_name_len = strlen (initial_nonterminal_name); + char *new_nonterminal_name = malloc (initial_nonterminal_name_len + 2); + memcpy (new_nonterminal_name, initial_nonterminal_name, initial_nonterminal_name_len); + new_nonterminal_name[initial_nonterminal_name_len + 0] = '*'; + new_nonterminal_name[initial_nonterminal_name_len + 1] = '\0'; + DYNAMIC_ARRAY_APPEND (grammar->nonterminals, ((struct nonterminal) { .name = new_nonterminal_name })); + + struct production new_production = { .from = new_initial_nonterminal }; + DYNAMIC_ARRAY_APPEND (grammar->productions, new_production); + DYNAMIC_ARRAY_APPEND (new_production.to, grammar->initial_nonterminal); + DYNAMIC_ARRAY_APPEND (grammar->productions, new_production); + + grammar->initial_nonterminal = new_initial_nonterminal; + } +} + +static void +grammar_remove_unit_productions (struct grammar *grammar) +{ + DYNAMIC_ARRAY_FOREACH (production, grammar->productions) { + if (production->to.count != 1 || + production->to.items[0] < TERMINAL_COUNT) continue; + + symbol from = production->from; + symbol to = production->to.items[0]; + if (production < &DYNAMIC_ARRAY_LAST (grammar->productions)) { + memmove (production, production + 1, + (&DYNAMIC_ARRAY_LAST (grammar->productions) - production) * + sizeof (*production)); + } grammar->productions.count -= 1; + + DYNAMIC_ARRAY_FOREACH (other_production, grammar->productions) { + if (other_production->from == from) continue; + if (other_production->from != to) continue; + if (!(other_production->to.count != 1 || + other_production->to.items[0] < TERMINAL_COUNT)) continue; + struct production new_production = { .from = from }; + DYNAMIC_ARRAY_APPEND_DYNAMIC_ARRAY (new_production.to, other_production->to); + uint32_t i = other_production - grammar->productions.items; + DYNAMIC_ARRAY_APPEND (grammar->productions, new_production); + other_production = &grammar->productions.items[i]; + } + } +} + +static bool +starts_with (const char *str, const char *start) +{ + size_t str_len = strlen (str); + size_t start_len = strlen (start); + + if (str_len < start_len) return false; + return !memcmp (start, str, start_len); +} + +static bool +symbol_is_property (struct grammar grammar, symbol sym) +{ + const char *name = grammar.nonterminals.items[sym - TERMINAL_COUNT].name; + return (starts_with (name, "noun-") || + starts_with (name, "pronoun-") || + starts_with (name, "fragment-s") || + starts_with (name, "fragment-p") || + starts_with (name, "verb-sg-p1-") || + starts_with (name, "verb-sg-p1-") || + starts_with (name, "verb-sg-p2-") || + starts_with (name, "verb-pl-p3-") || + starts_with (name, "verb-pl-p2-") || + starts_with (name, "verb-pl-p3-") || + starts_with (name, "verb-perfective")); +} + +static void +print_tree_dot (struct grammar grammar, struct tree tree) +{ + FILE *fp = fopen ("./tmp/tree.dot", "w"); + fprintf (fp, "digraph {" "\n"); + fprintf (fp, "\t" "node [shape=box, fontname=\"Aporetic Serif Mono,mono\"]" "\n"); + + struct stack { + struct tree **items; + uint32_t count; + uint32_t capacity; + }; + struct stack stack_front = {0}; + struct stack stack_back = {0}; + DYNAMIC_ARRAY_APPEND (stack_front, &tree); + while (stack_front.count) { + DYNAMIC_ARRAY_FOREACH (node, stack_front) { + if ((*node)->symbol < TERMINAL_COUNT) continue; + if ((*node)->children.count == 0) continue; + + const char *shape = "box"; + if ((*node)->symbol == grammar.initial_nonterminal) + shape = "diamond"; + else if (symbol_is_property (grammar, (*node)->symbol)) + shape = "octagon"; + fprintf (fp, "\t" "n%lu [shape=%s, label=\"%s\"]" "\n", (size_t) *node, shape, + grammar.nonterminals.items[(*node)->symbol - TERMINAL_COUNT].name); + if ((*node)->parent) + fprintf (fp, "\t" "n%lu -> n%lu" "\n", (size_t) (*node)->parent, (size_t) *node); + + DYNAMIC_ARRAY_FOREACH (child, (*node)->children) { + DYNAMIC_ARRAY_APPEND (stack_back, child); + } + } + + struct stack tmp = stack_front; + stack_front = stack_back; + stack_back = tmp; + DYNAMIC_ARRAY_RESET (stack_back); + } + + fprintf (fp, "\t" "subgraph {" "\n"); + fprintf (fp, "\t\t" "node [shape=ellipse, fontname=\"Aporetic Serif,serif\"]" "\n"); + fprintf (fp, "\t\t" "rank=same" "\n"); + struct tree *last = NULL; + for (struct tree *leaf = tree_next_leaf (&tree); leaf; leaf = tree_next_leaf (leaf)) { + if (!(leaf->symbol < TERMINAL_COUNT)) continue; + struct tree *parent = leaf->parent; + fprintf (fp, "\t\t" "l%lu [label=\"", (size_t) leaf); + struct tree *start = leaf; + while (leaf->symbol < TERMINAL_COUNT) { + symbol sym = leaf->symbol; + if (!last && start == leaf) + sym = toupper (sym); + fprint_symbol (fp, grammar, sym); + if (leaf == &DYNAMIC_ARRAY_LAST (parent->children)) + break; + leaf += 1; + } + fprintf (fp, "\"]" "\n"); + if (last) + fprintf (fp, "\t\t" "l%lu -> l%lu [style=invis]\n", (size_t) last, (size_t) start); + last = start; + } + fprintf (fp, "\t" "}" "\n"); + + fprintf (fp, "\n"); + for (struct tree *leaf = tree_next_leaf (&tree); leaf; leaf = tree_next_leaf (leaf)) { + if (!(leaf->symbol < TERMINAL_COUNT)) continue; + struct tree *parent = leaf->parent; + fprintf (fp, "\t" "n%lu -> l%lu\n", (size_t) parent, (size_t) leaf); + while (leaf->symbol < TERMINAL_COUNT) { + if (leaf == &DYNAMIC_ARRAY_LAST (parent->children)) + break; + leaf += 1; + } + } + + fprintf (fp, "}" "\n"); + fclose (fp); +} + +static bool +check_upcase (const char *str) +{ + if (isupper (str[0])) return true; + if (!memcmp (str, "Ď", 2)) return true; + if (!memcmp (str, "Ť", 2)) return true; + if (!memcmp (str, "Ň", 2)) return true; + if (!memcmp (str, "Ľ", 2)) return true; + if (!memcmp (str, "Č", 2)) return true; + if (!memcmp (str, "Š", 2)) return true; + if (!memcmp (str, "Ž", 2)) return true; + if (!memcmp (str, "Á", 2)) return true; + if (!memcmp (str, "Ó", 2)) return true; + if (!memcmp (str, "Ú", 2)) return true; + if (!memcmp (str, "É", 2)) return true; + if (!memcmp (str, "Í", 2)) return true; + if (!memcmp (str, "Ý", 2)) return true; + if (!memcmp (str, "Ŕ", 2)) return true; + if (!memcmp (str, "Ĺ", 2)) return true; + if (!memcmp (str, "Ô", 2)) return true; + if (!memcmp (str, "Ä", 2)) return true; + return false; +} + +static void +downcase (char *str) +{ + if (isascii (str[0])) {str[0] = tolower (str[0]); return;} + if (!memcmp (str, "Ď", 2)) { memcpy (str, "ď", 2); return; } + if (!memcmp (str, "Ť", 2)) { memcpy (str, "ť", 2); return; } + if (!memcmp (str, "Ň", 2)) { memcpy (str, "ň", 2); return; } + if (!memcmp (str, "Ľ", 2)) { memcpy (str, "ľ", 2); return; } + if (!memcmp (str, "Č", 2)) { memcpy (str, "č", 2); return; } + if (!memcmp (str, "Š", 2)) { memcpy (str, "š", 2); return; } + if (!memcmp (str, "Ž", 2)) { memcpy (str, "ž", 2); return; } + if (!memcmp (str, "Á", 2)) { memcpy (str, "á", 2); return; } + if (!memcmp (str, "Ó", 2)) { memcpy (str, "ó", 2); return; } + if (!memcmp (str, "Ú", 2)) { memcpy (str, "ú", 2); return; } + if (!memcmp (str, "É", 2)) { memcpy (str, "é", 2); return; } + if (!memcmp (str, "Í", 2)) { memcpy (str, "í", 2); return; } + if (!memcmp (str, "Ý", 2)) { memcpy (str, "ý", 2); return; } + if (!memcmp (str, "Ŕ", 2)) { memcpy (str, "ŕ", 2); return; } + if (!memcmp (str, "Ĺ", 2)) { memcpy (str, "ĺ", 2); return; } + if (!memcmp (str, "Ô", 2)) { memcpy (str, "ô", 2); return; } + if (!memcmp (str, "Ä", 2)) { memcpy (str, "ä", 2); return; } +} + +int +main (int argc, char *argv[]) +{ + const char *progname = *argv++; + if (argc < 2) DIE ("Usage: %s file", progname); + + const char *filename = *argv++; + struct string_view file_contents = load_file (filename); + + struct bnf_lexer lexer = bnf_lexer_from_string_view (file_contents, filename); + struct bnf_syntax syntax = bnf_parse_syntax (&lexer); + assert (bnf_check_syntax (&lexer, syntax)); // check if grammar has rules for all nonterminals + + // save_dot (syntax); + // print_bnf (syntax); + + int seed = time (NULL); + // seed = 0; + srand (seed); + + printf ("Correct examples:\n"); + print_random_rule (syntax, ""); + for (int i = 0; i < 16; ++i) { + printf ("\n"); + print_random_rule (syntax, ""); + } printf ("\n"); + + struct grammar grammar = build_grammar (syntax); + // puts ("build:"); print_grammar (grammar); + // grammar_make_epsilon_free (&grammar); + // puts ("make_epsilon_free:"); print_grammar (grammar); + // grammar_remove_unit_productions (&grammar); + // puts ("remove_unit_productions:"); print_grammar (grammar); + // grammar_reduce (&grammar); // remove rules with (unreachable and unproductive) nonterminals + // puts ("reduce:"); print_grammar (grammar); + grammar_left_factor_common_prefixes (&grammar); + // puts ("left_factor_common_prefixes:"); print_grammar (grammar); + // TODO **expose indirect left recurisons + // TODO *eliminate left recurions + // TODO **ensure disjoint first and follow sets + build_lookup_table (&grammar); + + char *line = NULL; + size_t line_size = 0; + for (;;) { + printf ("Enter string to parse: "); + getline (&line, &line_size, stdin); + size_t line_len = strlen (line); + if (line_len == 1) break; + line[line_len - 1] = '\0'; + + printf ("matching: `%s'...\n", line); + if (!check_upcase (line)) { + puts ("didn't match!"); + continue; + } + + downcase (line); + struct tree tree = parse (grammar, line); + if (tree.children.count == 0) + puts ("didn't match!"); + else { + puts ("matched"); + print_tree_dot (grammar, tree); + printf ("./tmp/tree.dot:1:0: info: generated parsing tree\n"); + } + } puts ("Exiting..."); + + free (line); + DYNAMIC_ARRAY_FREE (syntax); + STRING_BUILDER_FREE (sb); + unload_file (file_contents); + + return EXIT_SUCCESS; +} diff --git a/src/slovak-adjective.bnf b/src/slovak-adjective.bnf new file mode 100644 index 0000000..4174d16 --- /dev/null +++ b/src/slovak-adjective.bnf @@ -0,0 +1,97 @@ +# -*- BNF -*- +# resources: +# - https://www.naturalminevita.sk/portal/slovencina/pridavne-mena-vzory-a-sklonovanie-pridavnych-mien/ + + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + ::= " a " | ", " + + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + ::= + + ::= "ý" + ::= "ého" + ::= "émy" + ::= "ého" + ::= "om" + ::= "ým" + ::= "á" + ::= "ej" + ::= "ej" + ::= "ú" + ::= "ej" + ::= "ou" + ::= "é" + ::= "ého" + ::= "émy" + ::= "é" + ::= "om" + ::= "ým" + ::= "í" + ::= "ých" + ::= "ým" + ::= "ých" + ::= "ých" + ::= "ými" + ::= "é" + ::= "ých" + ::= "ým" + ::= "é" + ::= "ých" + ::= "ými" + ::= "pekn" diff --git a/src/slovak-adverb.bnf b/src/slovak-adverb.bnf new file mode 100644 index 0000000..fab601f --- /dev/null +++ b/src/slovak-adverb.bnf @@ -0,0 +1,3 @@ +# -*- BNF -*- +# resources: +# - https://yourslovakteacher.com/grammar_theory/formation-of-slovak-adverbs-rules-and-examples/ diff --git a/src/slovak-noun.bnf b/src/slovak-noun.bnf new file mode 100644 index 0000000..8e81a08 --- /dev/null +++ b/src/slovak-noun.bnf @@ -0,0 +1,321 @@ +# slovak-noun.bnf -*- BNF -*- +# resources: +# - https://www.naturalminevita.sk/portal/slovencina/podstatne-mena/ + + ::= | | + ::= | | + ::= | | + + ::= | | + ::= | | + + ::= | + ::= | | | | | + ::= | | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + ::= | | | | + + ::= | + ::= | | | | | + ::= | | | | | + ::= | | "o" + ::= "a" + ::= "ovi" + ::= "a" + ::= "ovi" + ::= "om" + ::= "i" | "ia" | "ovia" + ::= "ov" + ::= "om" + ::= "ov" + ::= "och" + ::= "mi" + ::= | | + ::= "chlap" | "rytier" | # "chlapec" | "otec" | "pes" + ::= "brat" # | "učiteľ" + ::= "uj" | "ded" | "Pal" | "strýk" # | "syn" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "a" | "o" | "ista" + ::= "u" + ::= "ovi" + ::= "u" + ::= "ovi" + ::= "om" + ::= "ovia" | "ovia" | "i" + ::= "ov" + ::= "om" + ::= "ov" + ::= "och" + ::= "ami" + ::= | | + ::= "hrdin" | "sluh" | "sudc" + ::= "Krask" + ::= "husl" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "a" + ::= "u" + ::= "" + ::= "e" + ::= "om" + ::= "y" + ::= "ov" + ::= "om" + ::= "y" + ::= "och" + ::= "i" + ::= "dub" | "dom" | "strom" | "vodopád" | "obraz" | "autobus" | "trolejbus" | "pot" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "a" + ::= "u" + ::= "" + ::= "i" + ::= "om" + ::= "e" + ::= "ov" + ::= "om" + ::= "e" + ::= "och" + ::= "mi" + ::= "stroj" | "počítač" | "dážď" | "máj" | "kameň" | "kôš" | "nôž" | "terč" | "olej" | "čaj" # | "oheň" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "ho" + ::= "mu" + ::= "ho" + ::= "m" + ::= "m" + ::= "ovia" + ::= "ov" + ::= "om" + ::= "ob" + ::= "och" + ::= "ami" + ::= "kuli" | "pony" | "grizly" | "Goethe" | "Pálfy" | "Škultéty" | "Goethe" | "Krčméry" + + ::= | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + + ::= | + ::= | | | | | + ::= | | | | | + ::= "a" + ::= "y" + ::= "e" + ::= "y" + ::= "e" + ::= "ou" + ::= "y" + ::= "í" # meh + ::= "ám" + ::= "y" + ::= "ách" + ::= "ami" + ::= "žen" | "dcér" | "mam" |"vnučk" | "rodin" | "knih" | "cest" | "vod" | "ruk" | "noh" | "hlav" | "stred" | "sobot" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "a" + ::= "e" + ::= "i" + ::= "u" + ::= "i" + ::= "ou" + ::= "e" + ::= "íc" # ulíc + ::= "iam" + ::= "e" + ::= "iach" + ::= "ami" + ::= "ulic" | "lodenic" | "vež" | "košeľ" | "prác" | "stanic" | "schôdz" | "tabuľ" | "ruž" | "cibuľ" | "vaň" | "fľaš" | "nedeľ" | "chvíľ" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "e" + ::= "i" + ::= "" + ::= "i" + ::= "ou" + ::= "e" + ::= "í" + ::= "iam" + ::= "e" + ::= "iach" + ::= "ami" + ::= "dlaň" | "púšť" | "čakáreň" | "pec" | "pieseň" | "loď" | "báseň" | "reportáž" | "posteľ" | "predpoveď" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "i" + ::= "i" + ::= "" + ::= "i" + ::= "ou" + ::= "i" + ::= "í" + ::= "iam" + ::= "i" + ::= "iach" + ::= "ami" + ::= "kosť" | "radosť" | "vec" | "noc" | "step" | "pomoc" | "zmes" | "krv" | "tvrdosť" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "á" + ::= "ej" + ::= "ej" + ::= "ú" + ::= "ej" + ::= "ou" + ::= "é" + ::= "ín" # meh + ::= "ám" + ::= "é" + ::= "ách" + ::= "ami" + ::= "gazdin" | "princezn" | "kráľovn" | "cisárovn" | "šľachtičn" | "kňažn" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "a" + ::= "y" + ::= "i" + ::= "u" + ::= "i" + ::= "ou" + ::= "y" + ::= "í" + ::= "ám" + ::= "y" + ::= "ách" + ::= "ami" + ::= "ide" | "orchide" | "Nikaragu" | "Ike" | "Andre" | "alo" + + ::= | + ::= | | | | | + ::= | | | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + ::= | | | + + ::= | + ::= | | | | | + ::= | | | | | + ::= "o" + ::= "a" + ::= "u" + ::= "o" + ::= "e" # -u + ::= "om" + ::= "á" + ::= "í" # miest + ::= "ám" + ::= "á" + ::= "ách" + ::= "ami" + ::= "mest" | "mravenisk" | "aut" | "let" | "aut" | "koles" | "jablk" | "Slovensk" | "kaka" | "drev" | "diel" | "vedr" | "ok" | "uch" | "bruch" | "mydl" | "rádi" # | "gymnázium", "štúdium" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "e" + ::= "a" + ::= "u" + ::= "e" + ::= "i" # -u + ::= "om" + ::= "ia" + ::= "" # sŕdc + ::= "iam" + ::= "ia" + ::= "iach" + ::= "ami" + ::= "srdc" | "pol" | "mor" | "vrec" | "vajc" | "mor" | "nástupišt" | "pol" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "ie" + ::= "ia" + ::= "iu" + ::= "ie" + ::= "í" + ::= "ím" + ::= "ia" + ::= "í" + ::= "iam" + ::= "ia" + ::= "iach" + ::= "iami" + ::= "vysvedčen" | "pozad" | "úskal" | "obdob" | "líst" | "stretnut" | "zahranič" | "námest" | "umenie" + + ::= | + ::= | | | | | + ::= | | | | | + ::= "" + ::= "ťa" + ::= "ťu" + ::= "" + ::= "ti" + ::= "ťom" + ::= "tá" + ::= "t" + ::= "tám" + ::= "tá" + ::= "tách" + ::= "tami" + ::= "dievča" | "vnúča" | "zviera" | "páža" | "knieža" | "mláďa" | "kura" | "chlápä" | "žriebä" # | "dieťa" + +# slovak-noun.bnf ends here diff --git a/src/slovak-object.bnf b/src/slovak-object.bnf new file mode 100644 index 0000000..fb8062c --- /dev/null +++ b/src/slovak-object.bnf @@ -0,0 +1,56 @@ +# -*- BNF -*- + + ::= | " " + + ::= | | + ::= | + ::= | + ::= | + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + + ::= | | | | | + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " + ::= | " " | " " diff --git a/src/slovak-sentence.bnf b/src/slovak-sentence.bnf new file mode 100644 index 0000000..b2a9205 --- /dev/null +++ b/src/slovak-sentence.bnf @@ -0,0 +1,43 @@ +# slovak-sentence.bnf -*- BNF -*- +# references: +# - https://www.zones.sk/studentske-prace/gramatika/11209-morfologia-slovenskeho-jazyka/ +# - https://yourslovakteacher.com/grammar_theory/introduction-to-slovak-syntax-and-sentence-structure/ + + ::= + ::= | ", " | ", " " " + ::= " " | | + ::= | | + ::= | | + ::= " " " " + ::= " " " " + ::= " " " " + ::= " " " " + ::= " " " " + ::= " " " " + + ::= "ale" | "keď" + ::= "." | "?" | "!" | "..." + + ::= + + ::= | + ::= | | + ::= | | + ::= + ::= + ::= | + ::= + ::= + ::= | + + ::= | + ::= | | + ::= | | + ::= "ja" + ::= "ty" + ::= "on" | "ona" | "ono" + ::= "my" + ::= "vy" + ::= "oni" | "ony" + +# slovak-sentence.bnf ends here diff --git a/src/slovak-verb.bnf b/src/slovak-verb.bnf new file mode 100644 index 0000000..c29f991 --- /dev/null +++ b/src/slovak-verb.bnf @@ -0,0 +1,113 @@ +# slovak-verb.bnf -*- BNF -*- +# resources: +# - https://www.verbix.com/languages/slovak +# - https://slovake.eu/grammar/classes/verbs +# - https://www.eduself.sk/slovensky-jazyk/gramatika/slovesa +# - https://yourslovakteacher.com/patterns-in-slovak-verb-conjugation/ +# - https://yourslovakteacher.com/grammar_theory/overview-of-slovak-verb-tenses/ +# - https://www.zones.sk/studentske-prace/gramatika/11209-morfologia-slovenskeho-jazyka/ + + ::= | + ::= | | + ::= | | + ::= | + ::= | + ::= | + ::= | + ::= | + ::= | + + ::= # | + ::= # | + ::= | + ::= | | + ::= | | + ::= "budem " + ::= "budeš " + ::= "bude " + ::= "budeme " + ::= "budete " + ::= "budú " + + ::= # | + ::= # | + ::= | + ::= | | + ::= | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + ::= | | | | | + + ::= "ám" + ::= "áš" + ::= "á" + ::= "áme" + ::= "áte" + ::= "ajú" + + ::= "am" + ::= "aš" + ::= "a" + ::= "ame" + ::= "ate" + ::= "ajú" + + ::= "ím" + ::= "íš" + ::= "í" + ::= "íme" + ::= "íte" + ::= "ia" + + ::= "im" + ::= "iš" + ::= "i" + ::= "ime" + ::= "ite" + ::= "ia" + + ::= "ujem" + ::= "uješ" + ::= "uje" + ::= "ujeme" + ::= "ujete" + ::= "ujú" + + ::= "iem" + ::= "ieš" + ::= "ie" + ::= "ieme" + ::= "iete" + ::= "ejú" + + ::= | | | + ::= "ať" + ::= "iť" + ::= "ovať" + ::= "ieť" + + ::= | | | # ať | iť | ovať | ieť + ::= | + ::= | + ::= "m" | "hľad" | "pozn" | "hr" + ::= "čít" | "pláv" | "umýv" | "liet" + ::= "rob" | "uč" | "var" | "lieč" + ::= "kúp" | "ľúb" | "pál" + ::= "kup" | "okup" | "poráb" | "vyráb" | "preráb" | "štud" | "prac" | "tanc" | "telefon" | "fotograf" | "mail" | "maľ" + ::= "rozum" | "ved" + + ::= "u" | "na" | "vy" | "pre" | "po" | "pod" | "za" | "pri" | "o" | "ob" + +# NOTE(cmmm): modal verbs don't have prefixes +# TODO(cmmm): separate modal verbs... +# TODO(cmmm): ensure (using past tense conjugations for future tense) +# budem rozumieť | budem sa rozumieť | porozumel by som | porozumel by som sa +# budeš rozumieť | budeš sa rozumieť | porozumel by si | porozumel by si sa | porozumela by si | porozumela by si sa | porozumelo by si | porozumela by si sa +# bude rozumieť | bude sa rozumieť | porozumel by | porozumela by | porozumelo by +# budeme rozumieť | budeme sa rozumieť | budeme si rozumieť | porozumeli by sme | porozumeli by sme sa | porozumeli by sme si +# budete rozumieť | budete sa rozumieť | budete si rozumieť | porozumeli by ste | porozumeli by ste sa | porozumeli by ste si +# budú rozumieť | budú sa rozumieť | budú si rozumieť | porozumeli by sa | porozumeli by si +# slovak-verb.bnf ends here 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..0ba8a4e --- /dev/null +++ b/src/string-builder.h @@ -0,0 +1,48 @@ +#ifndef INCLUDED_STRING_BUILDER_H +#define INCLUDED_STRING_BUILDER_H + +#include +#include +#include "utils.h" +#include "dynamic-array.h" + +struct string_builder { + union { char *items, *string; }; + size_t count; + size_t capacity; +}; +#define STRING_BUILDER struct string_builder * + +#define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \ + DYNAMIC_ARRAY_APPEND (SB, CHAR) + +#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_STRING_VIEW(SB, SV) \ + DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).beg, STRING_VIEW_LEN (SV)); + +#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..0b6034a --- /dev/null +++ b/src/string-view.h @@ -0,0 +1,17 @@ +#ifndef INCLUDED_STRING_VIEW_H +#define INCLUDED_STRING_VIEW_H + +#include + +struct string_view { + const char *beg; + const char *end; +}; + +#define STRING_VIEW_FROM_CSTR(CSTR) ((struct string_view) { .beg = (CSTR), .end = (CSTR) + strlen (CSTR) }) +#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..16679e4 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,37 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#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 REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__) + +#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]) + +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) + +struct string_views { + struct string_view *items; + uint32_t count; + uint32_t capacity; +}; + +#endif -- cgit v1.3.1