#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; }