aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.c')
-rw-r--r--src/main.c1225
1 files changed, 1225 insertions, 0 deletions
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 @@
1#include <stdlib.h>
2#include <assert.h>
3#include <errno.h>
4#include <time.h>
5#include <ctype.h>
6#include <fcntl.h>
7#include <unistd.h>
8#include <sys/stat.h>
9#include <sys/mman.h>
10#include "bnf-parser.h"
11#include "utils.h"
12#include "dynamic-array.h"
13#include "string-builder.h"
14#include "string-view.h"
15
16#define TERMINAL_COUNT (256 + 2) // ASCII + <EOL> + <EOF>
17
18struct string_builder sb = {0};
19
20static struct string_view
21load_file (const char *filename)
22{
23 struct string_view file_contents;
24
25 int fd = open (filename, O_RDONLY);
26 if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename);
27
28 struct stat st;
29 fstat (fd, &st);
30 file_contents.beg = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
31 close (fd);
32 file_contents.end = file_contents.beg + st.st_size;
33
34 return file_contents;
35}
36
37static void
38unload_file (struct string_view sv)
39{
40 munmap ((char *) sv.beg, STRING_VIEW_LEN (sv));
41}
42
43static void print_term (struct bnf_syntax syntax,
44 struct string_builder *sb,
45 struct bnf_lexeme term);
46
47static void
48print_nonterminal (struct bnf_syntax syntax,
49 struct string_builder *sb,
50 struct string_view sv)
51{
52 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
53 if (!STRING_VIEW_EQUALS (rule->name.sv, sv)) continue;
54
55 struct bnf_sequence sequence =
56 rule->is_replaced_by.items[rand () % rule->is_replaced_by.count];
57 DYNAMIC_ARRAY_FOREACH (term, sequence) {
58 print_term (syntax, sb, *term);
59 }
60
61 return;
62 }
63
64 printf ("%.*s\n", (int) STRING_VIEW_LEN (sv), sv.beg);
65 UNREACHABLE ();
66}
67
68static void
69print_terminal (struct string_view sv, struct string_builder *sb)
70{
71 sv.beg += 1;
72 sv.end -= 1;
73 STRING_BUILDER_APPEND_STRING_VIEW (*sb, sv);
74}
75
76static void
77print_term (struct bnf_syntax syntax, struct string_builder *sb, struct bnf_lexeme term)
78{
79 switch (term.kind) {
80 case BNF_LEXEME_KIND_TERMINAL:
81 print_terminal (term.sv, sb);
82 break;
83 case BNF_LEXEME_KIND_NONTERMINAL:
84 if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) {
85 printf ("\n");
86 } else if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) {
87 } else {
88 print_nonterminal (syntax, sb, term.sv);
89 } break;
90 default: UNREACHABLE ();
91 }
92}
93
94static void
95print_random_rule (struct bnf_syntax syntax, const char *rule)
96{
97 STRING_BUILDER_RESET (sb);
98 print_nonterminal (syntax, &sb, STRING_VIEW_FROM_CSTR (rule));
99 sb.string[0] = toupper (sb.string[0]);
100 STRING_BUILDER_APPEND_NULL (sb);
101 printf ("%s", sb.string);
102}
103
104static void
105save_dot (struct bnf_syntax syntax)
106{
107 FILE *fp = fopen ("./tmp/slovak.dot", "w");
108
109 fprintf (fp, "digraph slovak {" "\n"); {
110 fprintf (fp, "\t" "fontname=\"Aporetic Serif,serif\"" "\n");
111 fprintf (fp, "\t" "node [fontname=\"Aporetic Sans,sans-serif\"]" "\n");
112 fprintf (fp, "\t" "edge [fontname=\"Aporetic Serif Mono,mono\"]" "\n");
113 fprintf (fp, "\t" "rankdir=TD" "\n");
114 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
115 fprintf (fp, "\t" "rule_%ld [label=\"%.*s\"]" "\n",
116 rule - syntax.items,
117 (int) STRING_VIEW_LEN (rule->name.sv), rule->name.sv.beg);
118 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
119 fprintf (fp, "\t" "sequence_%ld_%ld [label=\"%ld\"]" "\n",
120 rule - syntax.items,
121 sequence - rule->is_replaced_by.items,
122 sequence - rule->is_replaced_by.items);
123 fprintf (fp, "\t" "rule_%ld -> sequence_%ld_%ld" "\n",
124 rule - syntax.items,
125 rule - syntax.items,
126 sequence - rule->is_replaced_by.items);
127 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
128 fprintf (fp, "\t" "sequence_%ld_%ld -> term_%ld_%ld_%ld" "\n",
129 rule - syntax.items,
130 sequence - rule->is_replaced_by.items,
131 rule - syntax.items,
132 sequence - rule->is_replaced_by.items,
133 term - sequence->items);
134 STRING_BUILDER_RESET (sb);
135 switch (term->kind) {
136 case BNF_LEXEME_KIND_TERMINAL:
137 STRING_BUILDER_APPEND_CSTR (sb, "\\\"");
138 STRING_BUILDER_APPEND_STRING_VIEW (
139 sb, ((struct string_view) {
140 .beg = term->sv.beg + 1,
141 .end = term->sv.end - 1,
142 }));
143 STRING_BUILDER_APPEND_CSTR (sb, "\\\"");
144 break;
145 case BNF_LEXEME_KIND_NONTERMINAL:
146 STRING_BUILDER_APPEND_STRING_VIEW (sb, term->sv);
147 break;
148 default: UNREACHABLE ();
149 }
150 STRING_BUILDER_APPEND_NULL (sb);
151 fprintf (fp, "\t" "term_%ld_%ld_%ld [label=\"%s\"]" "\n",
152 rule - syntax.items,
153 sequence - rule->is_replaced_by.items,
154 term - sequence->items,
155 sb.string);
156 }
157 }
158 }
159 } fprintf (fp, "}\n");
160
161 fclose (fp);
162}
163
164static
165void print_bnf (struct bnf_syntax syntax)
166{
167 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
168 printf ("%.*s ::=",
169 (int) STRING_VIEW_LEN (rule->name.sv), rule->name.sv.beg);
170 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
171 if (sequence != rule->is_replaced_by.items)
172 printf (" |");
173 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
174 printf (" %.*s", (int) STRING_VIEW_LEN (term->sv), term->sv.beg);
175 }
176 } printf ("\n");
177 }
178}
179
180typedef uint32_t symbol;
181
182struct symbols {
183 symbol *items;
184 uint32_t count;
185 uint32_t capacity;
186};
187
188struct production {
189 symbol from;
190 struct symbols to;
191};
192
193struct productions {
194 struct production *items;
195 uint32_t count;
196 uint32_t capacity;
197};
198
199struct selections {
200 struct selection {
201 symbol input;
202 uint32_t production;
203 } *items;
204 uint32_t count;
205 uint32_t capacity;
206};
207
208struct nonterminal {
209 const char *name;
210 struct selections selections;
211};
212
213struct nonterminals {
214 struct nonterminal *items;
215 uint32_t count;
216 uint32_t capacity;
217};
218
219// struct terminals {
220// const char **items;
221// uint32_t count;
222// uint32_t capacity;
223// };
224
225struct grammar {
226 symbol initial_nonterminal;
227 struct nonterminals nonterminals;
228 // struct terminals terminals;
229 struct productions productions;
230};
231
232static struct grammar
233build_grammar (struct bnf_syntax syntax)
234{
235 struct grammar grammar = { .initial_nonterminal = TERMINAL_COUNT };
236
237 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
238 size_t nonterminal_name_len = STRING_VIEW_LEN (rule->name.sv) - 2;
239 char *nonterminal_name = malloc (nonterminal_name_len + 1);
240 nonterminal_name[nonterminal_name_len] = '\0';
241 memcpy (nonterminal_name, rule->name.sv.beg + 1, nonterminal_name_len);
242 DYNAMIC_ARRAY_APPEND (grammar.nonterminals,
243 ((struct nonterminal) { .name = nonterminal_name }));
244 }
245
246 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
247 symbol from = TERMINAL_COUNT + (rule - syntax.items);
248 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
249 struct production production = { .from = from };
250 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
251 switch (term->kind) {
252 case BNF_LEXEME_KIND_TERMINAL:
253 for (const char *p = term->sv.beg + 1; p < term->sv.end - 1; ++p)
254 DYNAMIC_ARRAY_APPEND (production.to, (uint8_t) *p);
255 break;
256 case BNF_LEXEME_KIND_NONTERMINAL:
257 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) {
258 DYNAMIC_ARRAY_APPEND (production.to, 256);
259 } else if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) {
260 DYNAMIC_ARRAY_APPEND (production.to, 257);
261 } else {
262 size_t term_len = STRING_VIEW_LEN (term->sv) - 2;
263 DYNAMIC_ARRAY_FOREACH (nonterminal, grammar.nonterminals) {
264 size_t nonterminal_name_len = strlen (nonterminal->name);
265 if (nonterminal_name_len != term_len) continue;
266 if (memcmp (nonterminal->name, term->sv.beg + 1, term_len)) continue;
267 DYNAMIC_ARRAY_APPEND (production.to, TERMINAL_COUNT + (nonterminal - grammar.nonterminals.items));
268 break;
269 }
270 } break;
271 default: UNREACHABLE ();
272 };
273 }
274 DYNAMIC_ARRAY_APPEND (grammar.productions, production);
275 }
276 }
277
278 return grammar;
279}
280
281static void
282fprint_symbol (FILE *fp, struct grammar grammar, symbol symbol)
283{
284 if (symbol == ' ') {
285 fprintf (fp, "‿");
286 } else if (symbol < 256) {
287 // printf ("0x%02X", symbol);
288 putc (symbol, fp);
289 } else if (symbol == 256) {
290 fprintf (fp, "<EOL>");
291 } else if (symbol == 257) {
292 fprintf (fp, "<EOF>");
293 } else {
294 fprintf (fp, "<%s>", grammar.nonterminals.items[symbol - TERMINAL_COUNT].name);
295 }
296}
297
298static void
299print_symbol (struct grammar grammar, symbol symbol)
300{
301 fprint_symbol (stdout, grammar, symbol);
302}
303
304static void
305print_symbols (struct grammar grammar, struct symbols symbols)
306{
307 bool printing_nonterminal = true;
308 if (symbols.count == 0)
309 printf ("\"\"");
310 DYNAMIC_ARRAY_FOREACH (symbol, symbols) {
311 if (printing_nonterminal && *symbol < 256) {
312 putchar ('"');
313 printing_nonterminal = false;
314 } else if (!printing_nonterminal && *symbol >= 256) {
315 putchar ('"');
316 printing_nonterminal = true;
317 }
318 print_symbol (grammar, *symbol);
319 }
320 if (!printing_nonterminal)
321 putchar ('"');
322 printf ("\n");
323}
324
325static void
326print_production (struct grammar grammar, struct production production)
327{
328 print_symbol (grammar, production.from);
329 printf (" -> ");
330 print_symbols (grammar, production.to);
331}
332
333static void
334print_grammar (struct grammar grammar)
335{
336 printf ("Initial nonterminal: ");
337 print_symbol (grammar, grammar.initial_nonterminal);
338 printf ("\n");
339 DYNAMIC_ARRAY_FOREACH (production, grammar.productions) {
340 printf ("%lu. ", production - grammar.productions.items);
341 print_production (grammar, *production);
342 }
343}
344
345static int
346compare_production_pointers (const void *a, const void *b)
347{
348 const struct production *production_a = *(const struct production **) a;
349 const struct production *production_b = *(const struct production **) b;
350
351 if (production_a->from < production_b->from) return +1;
352 if (production_a->from > production_b->from) return -1;
353
354 struct symbols symbols_a = production_a->to;
355 struct symbols symbols_b = production_b->to;
356
357 for (uint32_t i = 0; i < MIN (symbols_a.count, symbols_b.count); ++i) {
358 symbol symbol_a = symbols_a.items[i];
359 symbol symbol_b = symbols_b.items[i];
360 if (symbol_a == symbol_b) continue;
361 return (int) symbol_b - symbol_a;
362 }
363
364 if (symbols_a.count < symbols_b.count) return +1;
365 if (symbols_a.count > symbols_b.count) return -1;
366
367 return 0;
368}
369
370static int
371compare_symbols (const void *a, const void *b)
372{
373 const symbol symbol_a = *(const symbol *) a;
374 const symbol symbol_b = *(const symbol *) b;
375
376 return symbol_a - symbol_b;
377}
378
379static void
380grammar_left_factor_common_prefixes (struct grammar *grammar)
381{
382 struct symbols handled = {0};
383
384 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
385 DYNAMIC_ARRAY_FOREACH (symbol, handled) {
386 if (*symbol == production->from) goto next_production;
387 }
388
389 symbol from = production->from;
390
391 size_t factored = 0;
392 factor_single:
393 struct {
394 struct production **items;
395 uint32_t count;
396 uint32_t capacity;
397 } same = {0};
398 DYNAMIC_ARRAY_FOREACH (other, grammar->productions) {
399 if (other->from != from) continue;
400 DYNAMIC_ARRAY_APPEND (same, other);
401 }
402
403 qsort (same.items, same.count, sizeof (same.items[0]), compare_production_pointers);
404 // puts ("same:");
405 // DYNAMIC_ARRAY_FOREACH (prod, same) {
406 // print_production (*grammar, **prod);
407 // }
408
409 DYNAMIC_ARRAY_FOREACH (production, same) {
410 if (production + 1 == same.items + same.count) break;
411 struct production *prod = *(production + 0);
412 struct production *next = *(production + 1);
413
414 struct symbols prefix = {0};
415 for (uint32_t i = 0; i < MIN (prod->to.count, next->to.count); ++i) {
416 if (prod->to.items[i] != next->to.items[i]) break;
417 DYNAMIC_ARRAY_APPEND (prefix, prod->to.items[i]);
418 } if (prefix.count == 0) continue;
419
420 // printf ("prefix: ");
421 // print_symbols (*grammar, prefix);
422
423 const char *nonterminal_name = grammar->nonterminals.items[prod->from - TERMINAL_COUNT].name;
424 size_t nonterminal_name_len = strlen (nonterminal_name);
425 char *nonterminal_name_new = malloc (nonterminal_name_len + 2 + factored);
426 symbol from_new = TERMINAL_COUNT + grammar->nonterminals.count;
427 memcpy (nonterminal_name_new, nonterminal_name, nonterminal_name_len);
428 for (size_t i = nonterminal_name_len; i < nonterminal_name_len + factored + 1; ++i)
429 nonterminal_name_new[i] = '\'';
430 nonterminal_name_new[nonterminal_name_len + factored + 1] = '\0';
431 DYNAMIC_ARRAY_APPEND (grammar->nonterminals,
432 ((struct nonterminal) { .name = nonterminal_name_new }));
433
434 struct production prod_new = { .from = prod->from };
435 DYNAMIC_ARRAY_APPEND_MANY (prod_new.to, prefix.items, prefix.count);
436 DYNAMIC_ARRAY_APPEND (prod_new.to, from_new);
437 DYNAMIC_ARRAY_APPEND (grammar->productions, prod_new);
438
439 struct {
440 struct production **items;
441 uint32_t count;
442 uint32_t capacity;
443 } rewrite = {0};
444 DYNAMIC_ARRAY_APPEND (rewrite, prod);
445 DYNAMIC_ARRAY_APPEND (rewrite, next);
446 for (uint32_t i = production + 2 - same.items; i < same.count; ++i) {
447 struct production *p = same.items[i];
448 if (p->to.count < prefix.count) continue;
449 if (memcmp (p->to.items, prefix.items, prefix.count*sizeof (*prefix.items))) continue;
450 DYNAMIC_ARRAY_APPEND (rewrite, p);
451 }
452
453 DYNAMIC_ARRAY_FOREACH (p, rewrite) {
454 struct production *prod = *p;
455 prod->from = from_new;
456 memmove (prod->to.items,
457 prod->to.items + prefix.count,
458 (prod->to.count - prefix.count) *
459 sizeof (prod->to.items[0]));
460 prod->to.count -= prefix.count;
461 }
462
463 factored += 1;
464 goto factor_single;
465 }
466
467 DYNAMIC_ARRAY_APPEND (handled, production->from);
468 next_production:
469 }
470}
471
472static bool
473first (struct grammar grammar, struct symbols syms, struct symbols *set)
474{
475 if (syms.count == 0) return true;
476
477 symbol first_sym = syms.items[0];
478 if (first_sym < TERMINAL_COUNT) {
479 DYNAMIC_ARRAY_FOREACH (sym, *set)
480 if (*sym == first_sym) return false;
481 DYNAMIC_ARRAY_APPEND (*set, first_sym);
482 return false;
483 }
484
485 bool has_epsilon = false;
486 DYNAMIC_ARRAY_FOREACH (production, grammar.productions) {
487 if (production->from != first_sym) continue;
488 has_epsilon = first (grammar, production->to, set);
489 }
490
491 if (has_epsilon) {
492 syms.items += 1;
493 syms.count -= 1;
494
495 return first (grammar, syms, set);
496 }
497
498 return false;
499}
500
501static void
502follow (struct grammar grammar, symbol nonterm, struct symbols *set, struct symbols *stack)
503{
504 DYNAMIC_ARRAY_FOREACH (nt, *stack)
505 if (*nt == nonterm) return;
506
507 DYNAMIC_ARRAY_APPEND (*stack, nonterm);
508 DYNAMIC_ARRAY_FOREACH (production, grammar.productions) {
509 DYNAMIC_ARRAY_FOREACH (sym, production->to) {
510 if (*sym != nonterm) continue;
511 if (sym == &DYNAMIC_ARRAY_LAST (production->to)) {
512 if (*sym == production->from) continue;
513 follow (grammar, production->from, set, stack);
514 continue;
515 }
516
517 struct symbols syms = {
518 .items = sym + 1,
519 .count = production->to.count - (sym - production->to.items),
520 };
521 if (first (grammar, syms, set))
522 follow (grammar, production->from, set, stack);
523 }
524 }
525 stack->count -= 1;
526}
527
528static void
529build_lookup_table (struct grammar *grammar)
530{
531 struct symbols selection = {0};
532 struct symbols stack = {0};
533 DYNAMIC_ARRAY_FOREACH (nonterminal, grammar->nonterminals) {
534 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
535 if (production->from != TERMINAL_COUNT + nonterminal - grammar->nonterminals.items) continue;
536 // print_production (*grammar, *production);
537 selection.count = 0;
538 stack.count = 0;
539 if (first (*grammar, production->to, &selection))
540 follow (*grammar, production->from, &selection, &stack);
541
542 for (uint32_t i = 0; i < selection.count - 1; ++i) {
543 for (uint32_t j = i + 1; j < selection.count; ++j) {
544 if (selection.items[j] != selection.items[i]) continue;
545 selection.items[j] = selection.items[--selection.count];
546 }
547 }
548
549 // DYNAMIC_ARRAY_FOREACH (sym, selection) {
550 // if (*sym < 256)
551 // putchar (*sym);
552 // else if (*sym == 256)
553 // printf ("<EOL>");
554 // else if (*sym == 257)
555 // printf ("<EOF>");
556 // } printf ("\n");
557
558 DYNAMIC_ARRAY_FOREACH (sym, selection) {
559 DYNAMIC_ARRAY_APPEND (
560 nonterminal->selections,
561 ((struct selection) {
562 .input = *sym,
563 .production = production - grammar->productions.items,
564 }));
565 }
566 }
567 }
568 DYNAMIC_ARRAY_FREE (selection);
569 DYNAMIC_ARRAY_FREE (stack);
570
571 // DYNAMIC_ARRAY_FOREACH (nonterminal, grammar->nonterminals) {
572 // printf ("<%s> |", nonterminal->name);
573 // DYNAMIC_ARRAY_FOREACH (selection, nonterminal->selections) {
574 // if (selection->input == 256)
575 // printf (" <EOL> -> %u |", selection->production);
576 // else if (selection->input == 257)
577 // printf (" <EOF> -> %u |", selection->production);
578 // else
579 // printf (" %c -> %u |", selection->input, selection->production);
580 // } printf ("\n");
581 // }
582}
583
584struct tree {
585 struct children {
586 struct tree *items;
587 uint32_t count;
588 uint32_t capacity;
589 } children;
590 struct tree *parent;
591 const char *begin;
592 symbol symbol;
593};
594
595static struct tree *
596tree_root (struct tree *tree)
597{
598 ASSERT (tree);
599 while (tree->parent)
600 tree = tree->parent;
601 return tree;
602}
603
604static size_t
605tree_count_terminals_within (struct tree *node)
606{
607 ASSERT (node);
608
609 if (!node->begin) return 0;
610
611 if (node->children.count == 0)
612 return node->symbol < TERMINAL_COUNT; // TODO: handle special symbols
613
614 size_t sum = 0;
615 DYNAMIC_ARRAY_FOREACH (child, node->children)
616 sum += tree_count_terminals_within (child);
617 return sum;
618}
619
620static size_t
621tree_count_terminals_from_to (struct tree *from, struct tree *to)
622{
623 ASSERT (from);
624 ASSERT (to);
625
626 if (from >= to)
627 return 0;
628
629 if (from->children.count == 0)
630 return from->symbol < TERMINAL_COUNT; // TODO: handle special symbols
631
632 size_t sum = 0;
633 DYNAMIC_ARRAY_FOREACH (child, from->children)
634 sum += tree_count_terminals_within (from);
635 return sum;
636}
637
638static size_t
639tree_count_terminals_up_to (struct tree *to)
640{
641 ASSERT (to);
642 return tree_count_terminals_from_to (tree_root (to), to);
643}
644
645static void
646print_tree_highlight (struct grammar grammar,
647 struct tree *tree,
648 struct tree *highlight,
649 int depth)
650{
651 ASSERT (tree);
652
653 for (int i = 0; i < depth; ++i)
654 printf (" ");
655 printf (tree == highlight ? "+ " : " ");
656 if (tree->symbol < 256) putchar ('"');
657 print_symbol (grammar, tree->symbol);
658 if (tree->symbol < 256) putchar ('"');
659 if (tree->begin)
660 printf (" -> \"%.*s\"",
661 (int) tree_count_terminals_within (tree), tree->begin);
662 printf ("\n");
663 DYNAMIC_ARRAY_FOREACH (child, tree->children)
664 print_tree_highlight (grammar, child, highlight, depth + 1);
665 if (depth == 0)
666 printf ("\n");
667}
668
669static void
670print_tree (struct grammar grammar, struct tree *tree)
671{
672 ASSERT (tree);
673 print_tree_highlight (grammar, tree_root (tree), tree, 0);
674}
675
676static struct tree *
677tree_prev_leaf (struct tree *tree)
678{
679 ASSERT (tree);
680
681 if (tree->children.count > 0) {
682 while (tree->parent && tree == tree->parent->children.items)
683 tree = tree->parent;
684 if (!tree->parent) return NULL;
685 tree -= 1;
686 while (tree->children.count > 0)
687 tree = &DYNAMIC_ARRAY_LAST (tree->children);
688 return tree;
689 }
690
691 if (!tree->parent) return NULL;
692 if (tree > tree->parent->children.items) {
693 tree -= 1;
694 while (tree->children.count > 0)
695 tree = &DYNAMIC_ARRAY_LAST (tree->children);
696 return tree;
697 }
698
699 return NULL;
700}
701
702static struct tree *
703tree_next_leaf (struct tree *tree)
704{
705 ASSERT (tree);
706
707 if (tree->children.count > 0) {
708 do tree = tree->children.items;
709 while (tree->children.count > 0);
710 return tree;
711 }
712
713 if (!tree->parent) return NULL;
714
715 if (tree < &DYNAMIC_ARRAY_LAST (tree->parent->children)) {
716 tree += 1;
717 while (tree->children.count > 0)
718 tree = tree->children.items;
719 return tree;
720 }
721
722 do tree = tree->parent;
723 while (tree->parent && tree == &DYNAMIC_ARRAY_LAST (tree->parent->children));
724 if (!tree->parent) return NULL;
725 return tree + 1;
726}
727
728static void
729tree_remove_child (struct tree *child)
730{
731 while (child->parent && child->children.count == 0) {
732 struct tree *parent = child->parent;
733 if (child != &DYNAMIC_ARRAY_LAST (parent->children))
734 memmove (child, child + 1,
735 (&DYNAMIC_ARRAY_LAST (parent->children) - child)*sizeof (*child));
736 parent->children.count -= 1;
737 child = parent;
738 }
739}
740
741static bool
742parse_impl (struct grammar grammar, struct tree *leaf)
743{
744 do {
745 if (leaf->parent) {
746 leaf->begin = leaf->parent->begin;
747 DYNAMIC_ARRAY_FOREACH (child, leaf->parent->children) {
748 if (child == leaf) break;
749 leaf->begin += tree_count_terminals_within (child);
750 }
751 }
752
753 if (leaf->symbol < TERMINAL_COUNT) {
754 if (!(*leaf->begin == '\n' && leaf->symbol == 256 ||
755 *leaf->begin == '\0' && leaf->symbol == 257) &&
756 (uint8_t) *leaf->begin != leaf->symbol) {
757 // printf ("didn't match %c (expected %c)\n", *leaf->begin, leaf->symbol);
758 return false;
759 };
760
761 // printf ("matched terminal ");
762 // print_symbol (grammar, leaf->symbol);
763 // printf ("\n");
764 } else { // nonterminal
765 struct selections selections =
766 grammar.nonterminals.items[leaf->symbol - TERMINAL_COUNT].selections;
767 DYNAMIC_ARRAY_FOREACH (selection, selections) {
768 if (!(*leaf->begin == '\n' && selection->input == 256 ||
769 *leaf->begin == '\0' && selection->input == 257 ||
770 selection->input == (uint8_t) *leaf->begin))
771 continue;
772
773 struct production production =
774 grammar.productions.items[selection->production];
775 if (production.to.count == 0) {
776 if (!leaf->parent) REACHED ("peculiar situation");
777 // print_tree (grammar, leaf);
778 if (parse_impl (grammar, tree_next_leaf (leaf)))
779 return true;
780 } else {
781 DYNAMIC_ARRAY_FOREACH (sym, production.to) {
782 DYNAMIC_ARRAY_APPEND (leaf->children, ((struct tree) {
783 .symbol = *sym,
784 .parent = leaf,
785 }));
786 }
787 // print_tree (grammar, leaf);
788 if (parse_impl (grammar, tree_next_leaf (leaf)))
789 return true;
790 DYNAMIC_ARRAY_RESET (leaf->children);
791 }
792 }
793 // puts ("backtracking");
794 return false;
795 }
796 } while (leaf = tree_next_leaf (leaf));
797 return true; // only return true if fully parsed!
798}
799
800static struct tree
801parse (struct grammar grammar, const char *str)
802{
803 struct tree tree = {
804 .symbol = grammar.initial_nonterminal,
805 .begin = str,
806 };
807 parse_impl (grammar, &tree);
808 return tree;
809}
810
811static void
812grammar_reduce (struct grammar *grammar)
813{
814 struct symbols reachable = {0};
815 DYNAMIC_ARRAY_APPEND (reachable, grammar->initial_nonterminal);
816 for (uint32_t i = 0; i < reachable.count; ++i) {
817 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
818 if (production->from != reachable.items[i]) continue;
819 DYNAMIC_ARRAY_FOREACH (symbol, production->to) {
820 if (*symbol < TERMINAL_COUNT) continue;
821 DYNAMIC_ARRAY_FOREACH (nonterminal, reachable)
822 if (*nonterminal == *symbol) goto reachable_next_symbol;
823 DYNAMIC_ARRAY_APPEND (reachable, *symbol);
824 reachable_next_symbol:
825 }
826 }
827 }
828
829 struct {
830 struct production **items;
831 uint32_t count;
832 uint32_t capacity;
833 } productive = {0};
834 uint32_t added;
835 do {
836 added = productive.count;
837
838 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
839 DYNAMIC_ARRAY_FOREACH (productive_production, productive) {
840 if (*productive_production == production)
841 goto productive_next_production;
842 }
843
844 DYNAMIC_ARRAY_FOREACH (symbol, production->to) {
845 if (*symbol < TERMINAL_COUNT) continue;
846 DYNAMIC_ARRAY_FOREACH (productive_production, productive) {
847 if ((*productive_production)->from == *symbol)
848 goto productive_next_symbol;
849 }
850 goto productive_next_production;
851 productive_next_symbol:
852 }
853
854 DYNAMIC_ARRAY_APPEND (productive, production);
855 productive_next_production:
856 }
857
858 added = productive.count - added;
859 } while (added);
860
861 // print_symbols (*grammar, reachable);
862 // DYNAMIC_ARRAY_FOREACH (production, productive)
863 // print_production (*grammar, **production);
864
865 struct productions productions = {0};
866 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
867 DYNAMIC_ARRAY_FOREACH (reachable_nonterminal, reachable)
868 if (*reachable_nonterminal == production->from) goto reachable;
869 DYNAMIC_ARRAY_FREE (production->to);
870 continue;
871 reachable:
872 DYNAMIC_ARRAY_FOREACH (productive_production, productive)
873 if (*productive_production == production) goto productive;
874 DYNAMIC_ARRAY_FREE (production->to);
875 continue;
876 productive:
877 DYNAMIC_ARRAY_APPEND (productions, *production);
878 }
879 DYNAMIC_ARRAY_FREE (grammar->productions);
880 grammar->productions = productions;
881}
882
883static void
884grammar_add_combinations (struct grammar *grammar, struct symbols input,
885 struct production output1, symbol sym, uint32_t remove)
886{
887 if (remove == 0) {
888 DYNAMIC_ARRAY_APPEND_MANY (output1.to, input.items, input.count);
889 DYNAMIC_ARRAY_APPEND (grammar->productions, output1);
890 return;
891 }
892
893 while (input.count != 0 && input.items[0] != sym) {
894 DYNAMIC_ARRAY_APPEND (output1.to, input.items[0]);
895 input.items += 1;
896 input.count -= 1;
897 }
898
899 if (input.count == 0) {
900 DYNAMIC_ARRAY_FREE (output1.to);
901 return;
902 }
903
904 struct production output2 = { .from = output1.from };
905 DYNAMIC_ARRAY_APPEND_MANY (output2.to, output1.to.items, output1.to.count);
906 DYNAMIC_ARRAY_APPEND (output1.to, input.items[0]);
907 input.items += 1;
908 input.count -= 1;
909 grammar_add_combinations (grammar, input, output1, sym, remove - 0);
910 grammar_add_combinations (grammar, input, output2, sym, remove - 1);
911}
912
913static void
914grammar_make_epsilon_free (struct grammar *grammar)
915{
916 bool has_initial_epsilon = false;
917 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
918 if (production->to.count != 0) continue;
919 if (production->from == grammar->initial_nonterminal)
920 has_initial_epsilon = true;
921
922 symbol from = production->from;
923 if (production < &DYNAMIC_ARRAY_LAST (grammar->productions)) {
924 memmove (production, production + 1,
925 (&DYNAMIC_ARRAY_LAST (grammar->productions) - production) *
926 sizeof (*production));
927 }
928 production -= 1;
929 grammar->productions.count -= 1;
930
931 DYNAMIC_ARRAY_FOREACH (other_production, grammar->productions) {
932 uint32_t count = 0;
933 DYNAMIC_ARRAY_FOREACH (symbol, other_production->to)
934 if (*symbol == from) count += 1;
935 if (count == 0) continue;
936
937 for (uint32_t i = 1; i <= count; ++i) {
938 grammar_add_combinations (grammar, other_production->to,
939 (struct production) { .from = other_production->from },
940 from, i);
941 }
942 }
943 }
944
945 if (has_initial_epsilon) {
946 symbol new_initial_nonterminal = TERMINAL_COUNT + grammar->nonterminals.count;
947
948 const char *initial_nonterminal_name =
949 grammar->nonterminals.items[grammar->initial_nonterminal - TERMINAL_COUNT].name;
950 size_t initial_nonterminal_name_len = strlen (initial_nonterminal_name);
951 char *new_nonterminal_name = malloc (initial_nonterminal_name_len + 2);
952 memcpy (new_nonterminal_name, initial_nonterminal_name, initial_nonterminal_name_len);
953 new_nonterminal_name[initial_nonterminal_name_len + 0] = '*';
954 new_nonterminal_name[initial_nonterminal_name_len + 1] = '\0';
955 DYNAMIC_ARRAY_APPEND (grammar->nonterminals, ((struct nonterminal) { .name = new_nonterminal_name }));
956
957 struct production new_production = { .from = new_initial_nonterminal };
958 DYNAMIC_ARRAY_APPEND (grammar->productions, new_production);
959 DYNAMIC_ARRAY_APPEND (new_production.to, grammar->initial_nonterminal);
960 DYNAMIC_ARRAY_APPEND (grammar->productions, new_production);
961
962 grammar->initial_nonterminal = new_initial_nonterminal;
963 }
964}
965
966static void
967grammar_remove_unit_productions (struct grammar *grammar)
968{
969 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
970 if (production->to.count != 1 ||
971 production->to.items[0] < TERMINAL_COUNT) continue;
972
973 symbol from = production->from;
974 symbol to = production->to.items[0];
975 if (production < &DYNAMIC_ARRAY_LAST (grammar->productions)) {
976 memmove (production, production + 1,
977 (&DYNAMIC_ARRAY_LAST (grammar->productions) - production) *
978 sizeof (*production));
979 } grammar->productions.count -= 1;
980
981 DYNAMIC_ARRAY_FOREACH (other_production, grammar->productions) {
982 if (other_production->from == from) continue;
983 if (other_production->from != to) continue;
984 if (!(other_production->to.count != 1 ||
985 other_production->to.items[0] < TERMINAL_COUNT)) continue;
986 struct production new_production = { .from = from };
987 DYNAMIC_ARRAY_APPEND_DYNAMIC_ARRAY (new_production.to, other_production->to);
988 uint32_t i = other_production - grammar->productions.items;
989 DYNAMIC_ARRAY_APPEND (grammar->productions, new_production);
990 other_production = &grammar->productions.items[i];
991 }
992 }
993}
994
995static bool
996starts_with (const char *str, const char *start)
997{
998 size_t str_len = strlen (str);
999 size_t start_len = strlen (start);
1000
1001 if (str_len < start_len) return false;
1002 return !memcmp (start, str, start_len);
1003}
1004
1005static bool
1006symbol_is_property (struct grammar grammar, symbol sym)
1007{
1008 const char *name = grammar.nonterminals.items[sym - TERMINAL_COUNT].name;
1009 return (starts_with (name, "noun-") ||
1010 starts_with (name, "pronoun-") ||
1011 starts_with (name, "fragment-s") ||
1012 starts_with (name, "fragment-p") ||
1013 starts_with (name, "verb-sg-p1-") ||
1014 starts_with (name, "verb-sg-p1-") ||
1015 starts_with (name, "verb-sg-p2-") ||
1016 starts_with (name, "verb-pl-p3-") ||
1017 starts_with (name, "verb-pl-p2-") ||
1018 starts_with (name, "verb-pl-p3-") ||
1019 starts_with (name, "verb-perfective"));
1020}
1021
1022static void
1023print_tree_dot (struct grammar grammar, struct tree tree)
1024{
1025 FILE *fp = fopen ("./tmp/tree.dot", "w");
1026 fprintf (fp, "digraph {" "\n");
1027 fprintf (fp, "\t" "node [shape=box, fontname=\"Aporetic Serif Mono,mono\"]" "\n");
1028
1029 struct stack {
1030 struct tree **items;
1031 uint32_t count;
1032 uint32_t capacity;
1033 };
1034 struct stack stack_front = {0};
1035 struct stack stack_back = {0};
1036 DYNAMIC_ARRAY_APPEND (stack_front, &tree);
1037 while (stack_front.count) {
1038 DYNAMIC_ARRAY_FOREACH (node, stack_front) {
1039 if ((*node)->symbol < TERMINAL_COUNT) continue;
1040 if ((*node)->children.count == 0) continue;
1041
1042 const char *shape = "box";
1043 if ((*node)->symbol == grammar.initial_nonterminal)
1044 shape = "diamond";
1045 else if (symbol_is_property (grammar, (*node)->symbol))
1046 shape = "octagon";
1047 fprintf (fp, "\t" "n%lu [shape=%s, label=\"%s\"]" "\n", (size_t) *node, shape,
1048 grammar.nonterminals.items[(*node)->symbol - TERMINAL_COUNT].name);
1049 if ((*node)->parent)
1050 fprintf (fp, "\t" "n%lu -> n%lu" "\n", (size_t) (*node)->parent, (size_t) *node);
1051
1052 DYNAMIC_ARRAY_FOREACH (child, (*node)->children) {
1053 DYNAMIC_ARRAY_APPEND (stack_back, child);
1054 }
1055 }
1056
1057 struct stack tmp = stack_front;
1058 stack_front = stack_back;
1059 stack_back = tmp;
1060 DYNAMIC_ARRAY_RESET (stack_back);
1061 }
1062
1063 fprintf (fp, "\t" "subgraph {" "\n");
1064 fprintf (fp, "\t\t" "node [shape=ellipse, fontname=\"Aporetic Serif,serif\"]" "\n");
1065 fprintf (fp, "\t\t" "rank=same" "\n");
1066 struct tree *last = NULL;
1067 for (struct tree *leaf = tree_next_leaf (&tree); leaf; leaf = tree_next_leaf (leaf)) {
1068 if (!(leaf->symbol < TERMINAL_COUNT)) continue;
1069 struct tree *parent = leaf->parent;
1070 fprintf (fp, "\t\t" "l%lu [label=\"", (size_t) leaf);
1071 struct tree *start = leaf;
1072 while (leaf->symbol < TERMINAL_COUNT) {
1073 symbol sym = leaf->symbol;
1074 if (!last && start == leaf)
1075 sym = toupper (sym);
1076 fprint_symbol (fp, grammar, sym);
1077 if (leaf == &DYNAMIC_ARRAY_LAST (parent->children))
1078 break;
1079 leaf += 1;
1080 }
1081 fprintf (fp, "\"]" "\n");
1082 if (last)
1083 fprintf (fp, "\t\t" "l%lu -> l%lu [style=invis]\n", (size_t) last, (size_t) start);
1084 last = start;
1085 }
1086 fprintf (fp, "\t" "}" "\n");
1087
1088 fprintf (fp, "\n");
1089 for (struct tree *leaf = tree_next_leaf (&tree); leaf; leaf = tree_next_leaf (leaf)) {
1090 if (!(leaf->symbol < TERMINAL_COUNT)) continue;
1091 struct tree *parent = leaf->parent;
1092 fprintf (fp, "\t" "n%lu -> l%lu\n", (size_t) parent, (size_t) leaf);
1093 while (leaf->symbol < TERMINAL_COUNT) {
1094 if (leaf == &DYNAMIC_ARRAY_LAST (parent->children))
1095 break;
1096 leaf += 1;
1097 }
1098 }
1099
1100 fprintf (fp, "}" "\n");
1101 fclose (fp);
1102}
1103
1104static bool
1105check_upcase (const char *str)
1106{
1107 if (isupper (str[0])) return true;
1108 if (!memcmp (str, "Ď", 2)) return true;
1109 if (!memcmp (str, "Ť", 2)) return true;
1110 if (!memcmp (str, "Ň", 2)) return true;
1111 if (!memcmp (str, "Ľ", 2)) return true;
1112 if (!memcmp (str, "Č", 2)) return true;
1113 if (!memcmp (str, "Š", 2)) return true;
1114 if (!memcmp (str, "Ž", 2)) return true;
1115 if (!memcmp (str, "Á", 2)) return true;
1116 if (!memcmp (str, "Ó", 2)) return true;
1117 if (!memcmp (str, "Ú", 2)) return true;
1118 if (!memcmp (str, "É", 2)) return true;
1119 if (!memcmp (str, "Í", 2)) return true;
1120 if (!memcmp (str, "Ý", 2)) return true;
1121 if (!memcmp (str, "Ŕ", 2)) return true;
1122 if (!memcmp (str, "Ĺ", 2)) return true;
1123 if (!memcmp (str, "Ô", 2)) return true;
1124 if (!memcmp (str, "Ä", 2)) return true;
1125 return false;
1126}
1127
1128static void
1129downcase (char *str)
1130{
1131 if (isascii (str[0])) {str[0] = tolower (str[0]); return;}
1132 if (!memcmp (str, "Ď", 2)) { memcpy (str, "ď", 2); return; }
1133 if (!memcmp (str, "Ť", 2)) { memcpy (str, "ť", 2); return; }
1134 if (!memcmp (str, "Ň", 2)) { memcpy (str, "ň", 2); return; }
1135 if (!memcmp (str, "Ľ", 2)) { memcpy (str, "ľ", 2); return; }
1136 if (!memcmp (str, "Č", 2)) { memcpy (str, "č", 2); return; }
1137 if (!memcmp (str, "Š", 2)) { memcpy (str, "š", 2); return; }
1138 if (!memcmp (str, "Ž", 2)) { memcpy (str, "ž", 2); return; }
1139 if (!memcmp (str, "Á", 2)) { memcpy (str, "á", 2); return; }
1140 if (!memcmp (str, "Ó", 2)) { memcpy (str, "ó", 2); return; }
1141 if (!memcmp (str, "Ú", 2)) { memcpy (str, "ú", 2); return; }
1142 if (!memcmp (str, "É", 2)) { memcpy (str, "é", 2); return; }
1143 if (!memcmp (str, "Í", 2)) { memcpy (str, "í", 2); return; }
1144 if (!memcmp (str, "Ý", 2)) { memcpy (str, "ý", 2); return; }
1145 if (!memcmp (str, "Ŕ", 2)) { memcpy (str, "ŕ", 2); return; }
1146 if (!memcmp (str, "Ĺ", 2)) { memcpy (str, "ĺ", 2); return; }
1147 if (!memcmp (str, "Ô", 2)) { memcpy (str, "ô", 2); return; }
1148 if (!memcmp (str, "Ä", 2)) { memcpy (str, "ä", 2); return; }
1149}
1150
1151int
1152main (int argc, char *argv[])
1153{
1154 const char *progname = *argv++;
1155 if (argc < 2) DIE ("Usage: %s file", progname);
1156
1157 const char *filename = *argv++;
1158 struct string_view file_contents = load_file (filename);
1159
1160 struct bnf_lexer lexer = bnf_lexer_from_string_view (file_contents, filename);
1161 struct bnf_syntax syntax = bnf_parse_syntax (&lexer);
1162 assert (bnf_check_syntax (&lexer, syntax)); // check if grammar has rules for all nonterminals
1163
1164 // save_dot (syntax);
1165 // print_bnf (syntax);
1166
1167 int seed = time (NULL);
1168 // seed = 0;
1169 srand (seed);
1170
1171 printf ("Correct examples:\n");
1172 print_random_rule (syntax, "<sentence>");
1173 for (int i = 0; i < 16; ++i) {
1174 printf ("\n");
1175 print_random_rule (syntax, "<sentence>");
1176 } printf ("\n");
1177
1178 struct grammar grammar = build_grammar (syntax);
1179 // puts ("build:"); print_grammar (grammar);
1180 // grammar_make_epsilon_free (&grammar);
1181 // puts ("make_epsilon_free:"); print_grammar (grammar);
1182 // grammar_remove_unit_productions (&grammar);
1183 // puts ("remove_unit_productions:"); print_grammar (grammar);
1184 // grammar_reduce (&grammar); // remove rules with (unreachable and unproductive) nonterminals
1185 // puts ("reduce:"); print_grammar (grammar);
1186 grammar_left_factor_common_prefixes (&grammar);
1187 // puts ("left_factor_common_prefixes:"); print_grammar (grammar);
1188 // TODO **expose indirect left recurisons
1189 // TODO *eliminate left recurions
1190 // TODO **ensure disjoint first and follow sets
1191 build_lookup_table (&grammar);
1192
1193 char *line = NULL;
1194 size_t line_size = 0;
1195 for (;;) {
1196 printf ("Enter string to parse: ");
1197 getline (&line, &line_size, stdin);
1198 size_t line_len = strlen (line);
1199 if (line_len == 1) break;
1200 line[line_len - 1] = '\0';
1201
1202 printf ("matching: `%s'...\n", line);
1203 if (!check_upcase (line)) {
1204 puts ("didn't match!");
1205 continue;
1206 }
1207
1208 downcase (line);
1209 struct tree tree = parse (grammar, line);
1210 if (tree.children.count == 0)
1211 puts ("didn't match!");
1212 else {
1213 puts ("matched");
1214 print_tree_dot (grammar, tree);
1215 printf ("./tmp/tree.dot:1:0: info: generated parsing tree\n");
1216 }
1217 } puts ("Exiting...");
1218
1219 free (line);
1220 DYNAMIC_ARRAY_FREE (syntax);
1221 STRING_BUILDER_FREE (sb);
1222 unload_file (file_contents);
1223
1224 return EXIT_SUCCESS;
1225}