aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-08 06:02:38 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-08 06:26:07 +0000
commit6ecea40c849effd171c1d27c961f5c1ee100481f (patch)
tree99a92dafddf7d2ef0e318d927ae70c3b642e4171
downloadlab-03-master.tar.gz
publishHEADmaster
-rw-r--r--.gitignore6
-rw-r--r--README.org134
-rw-r--r--UNLICENSE24
-rwxr-xr-xbin/build.sh23
-rw-r--r--doc/biblio.bib13
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty23
-rw-r--r--doc/gost/gost-7-32-counters.sty44
-rw-r--r--doc/gost/gost-7-32-headings.sty114
-rw-r--r--doc/gost/gost-7-32-lists.sty17
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/ox-init.el31
-rw-r--r--doc/report.org1060
-rw-r--r--doc/setup.org34
-rw-r--r--doc/spbstu-report.cls78
-rw-r--r--lib/bnf-mode.el40
-rw-r--r--src/bnf-lexeme.c10
-rw-r--r--src/bnf-lexeme.h35
-rw-r--r--src/bnf-lexer.c101
-rw-r--r--src/bnf-lexer.h18
-rw-r--r--src/bnf-parser.c191
-rw-r--r--src/bnf-parser.h51
-rw-r--r--src/bnf-preprocessor.c76
-rw-r--r--src/bnf-preprocessor.h8
-rw-r--r--src/dynamic-array.h75
-rw-r--r--src/generate-grammar.c391
-rw-r--r--src/main.c1225
-rw-r--r--src/slovak-adjective.bnf97
-rw-r--r--src/slovak-adverb.bnf3
-rw-r--r--src/slovak-noun.bnf321
-rw-r--r--src/slovak-object.bnf56
-rw-r--r--src/slovak-sentence.bnf43
-rw-r--r--src/slovak-verb.bnf113
-rw-r--r--src/string-builder.c41
-rw-r--r--src/string-builder.h48
-rw-r--r--src/string-view.h17
-rw-r--r--src/utils.h37
39 files changed, 4780 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..02e5e3e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
1*.html
2*.pdf
3*.tex
4*.dot
5*.png
6/build
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..d99ae1e
--- /dev/null
+++ b/README.org
@@ -0,0 +1,134 @@
1#+title: Context-free grammar for a subset of a natural language
2#+subtitle: Slovak language -- future tense
3#+date: 2025H1
4
5* Task
6:PROPERTIES:
7:CUSTOM_ID: task
8:END:
9Construct a context‑free grammar for a subset of natural language
10sentences, defined by a certain time. Based on the created grammar,
11implement the generation of random sentences belonging to the grammar
12and an algorithm for recognizing entered sentences.
13
14* Problem statement
15:PROPERTIES:
16:CUSTOM_ID: problem-statement
17:END:
18The future tense in the Slovak language is called /budúci čas/ or
19/futúrum/. The word order in the Slovak language is more or less free;
20changing it does not alter the meaning of the sentence, but changing
21the word order can be used to emphasize certain words. The usual word
22order is: subject + predicate + other members of the sentence + final
23punctuation mark (end mark).
24
25In the Slovak language, it is possible to build complex sentences (or
26compound sentences) --- these are sentences consisting of several
27simple sentences and expressing one complete thought. They can be
28both simple and complex.:
29- A simple complex sentence:
30- Contains two predicative units (two grammatical bases).
31 - Example: Jano sadol do auta a odišiel.
32 - Translation: Jano got into the car and drove away.
33- Compound complex sentence:
34 - Contains more than two predicative units (three or more
35 grammatical bases).
36 - Example: Mama vedela, že príde, lebo mu verila.
37 - Translation: Mom knew that he would come because she believed in him.
38
39There are many different types of compound sentences, but they always
40use conjunctions or connective expressions to join the parts of the
41sentence.
42
43To examine the applicability of context-free grammars in working with
44morphologically correct sentences, we will implement the agreement of
45person and number between the subject and the verb of the sentence
46fragment.
47
48To display the result of the syntax analyzer’s operation, we'll
49automatically generate a parse tree.
50
51* Documentation
52:PROPERTIES:
53:CUSTOM_ID: documentation
54:END:
55The exported report can be found at [[https://git.michalec.dev/files/uni/term-06/math-logic/lab-03/report.pdf][this link]].
56
57* Showcase
58:PROPERTIES:
59:CUSTOM_ID: showcase
60:END:
61I wrote a custom BNF parser for this, [[https://git.michalec.dev/uni/term-06/math-logic/lab-03/tree/src/slovak-sentence.bnf][here]] is an example of what it
62can parse.
63
64Listing [[generated]] shows the generated sentences. You can see that
65they consist of a different number of fragments, have different
66endings, and in some fragments the subject is omitted.
67
68#+name: generated
69#+caption: Generated sentences
70#+begin_src text
71Ty preľúbiš Kraskov, ona bude vedieť počítači, podliečíte dážď, cibuľa vyhľadá kuratá, ale oni ovaria morami, ty očítaš knihe, ono bude vedieť umenieie.
72Ja načítam Kraskovi, ty budeš mať ruka, keď budeš vedieť stretnutia, ty prelietaš huslu, ale ono bude vedieť princeznej, keď vy učítate mláďatá, ale ty budeš plávať bruchom?
73My budeme rozumieť dlaňe, bude robiť oleja.
74Púšť bude páliť chlápät, keď ono podrozumie úskalia, keď my budeme mať orchideu, vy budete maľovať lístím, ale oni budú vedieť chlápäťu, keď ukupuje vysvedčeniach, ja utelefonujem pozadím.
75Ty budeš telefonovať Nikaragua, keď ono bude vedieť Kraskovi, my budeme rozumieť noci, ale budem maľovať dážďmi?
76Vy zaľúbite stromoch, budeš páliť bratoch...
77Ty budeš tancovať uja.
78Ty ukúpiš huslovi, lístia budú fotografovať Kraskovi, vy opálite umenieia, polia budú učiť mláďa, keď obľúbim knihe, keď my budeme tancovať chvíľe, vy privaríte trolejbusy, ony budú liečiť kosťou, vy budete liečiť vodopádi, bude učiť chvíľou!
79Vy budete kupovať pieseňi, ale dážďe budú prerábovať nástupištia, my budeme robiť huslom?
80Budú robiť rodiny, keď ja pohľadám bratoch.
81Budem umývať sluhami, keď ty obliečíš kráľovnej.
82My vypracujeme reportáž, keď ony budú ľúbiť úskaliam, vy budete rozumieť šľachtičnej, zarobia auto?
83Nástupište opozná brata, keď ja ukúpim dlaňi, ale ja budem ľúbiť vodopád, ona prevedie kuliami, ona preliečí pážaťa...
84Vody obhľadajú kôša, ale vy budete rozumieť zmesiach, ale vyčítam báseňiach, vy budete rozumieť košeľíc...
85Vy obrozumiete huslov...
86My oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
87Ty budeš mailovať stredám?
88#+end_src
89
90In listing [[no-match-first]], an example is provided that does not comply
91with the grammar rules because the sentence starts with a lowercase
92letter instead of a capital one.
93
94#+name: no-match-first
95#+caption: A sentence that does not follow the rules of grammar -- does not start with a capital letter
96#+begin_src text
97Enter string to parse: my oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
98didn't match!
99#+end_src
100
101Lisiting [[no-match-number]] shows an example that does not conform to the
102grammar due to a mismatch in number between the subject and the verb.
103/"My oučím"/ can be matched in number in the following ways: /"My
104oučíme"/, /"Ja oučím"/.
105
106#+name: no-match-number
107#+caption: A sentence that does not conform to grammar -- an inconsistent number.
108#+begin_src text
109Enter string to parse: My oučím stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
110didn't match!
111#+end_src
112
113Listing [[match]] shows an example of a sentence that complies with the
114grammar. And figure [[tree]] presents the automatically generated parse tree
115for it.
116
117#+name: match
118#+caption: A sentence that complies with the grammar
119#+begin_src text
120Enter string to parse: My oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
121matched
122./tmp/tree.dot:1:0: info: generated parsing tree
123#+end_src
124
125#+name: tree
126#+caption: Parsing tree of the complient sentence
127#+attr_html: :width 100%
128[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-03/tree.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-03/tree.png]]
129
130* Unlicense
131:PROPERTIES:
132:CUSTOM_ID: unlicense
133:END:
134#+include: UNLICENSE verse
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/bin/build.sh b/bin/build.sh
new file mode 100755
index 0000000..740a756
--- /dev/null
+++ b/bin/build.sh
@@ -0,0 +1,23 @@
1#!/bin/sh
2
3set -xe
4
5mkdir -p ./build
6
7cat \
8 ./src/slovak-sentence.bnf \
9 ./src/slovak-verb.bnf \
10 ./src/slovak-noun.bnf \
11 > ./build/slovak.bnf
12 # ./src/slovak-adjective.bnf \
13 # ./src/slovak-object.bnf \
14 # ./src/slovak-adverb.bnf \
15
16gcc -std=gnu99 -O3 -ggdb3 \
17 -Wall -Wextra -Wno-unused-label -Wno-unused-function -Wno-parentheses \
18 -o ./build/analyze \
19 ./src/string-builder.c \
20 ./src/bnf-lexeme.c \
21 ./src/bnf-lexer.c \
22 ./src/bnf-parser.c \
23 ./src/main.c \
diff --git a/doc/biblio.bib b/doc/biblio.bib
new file mode 100644
index 0000000..3f5d63c
--- /dev/null
+++ b/doc/biblio.bib
@@ -0,0 +1,13 @@
1@book{WOLFRAM2002,
2author = {Стивен Вольфрам},
3title = {Наука нового типа},
4publisher = {Wolfram Media},
5year = {2002},
6pages = {1197}
7}
8@online{VOSTROV2024,
9author = {Востров А. В},
10title = {Математическая логика},
11url = {https://tema.spbstu.ru/compiler/},
12urldate = {2025-04-04}
13}
diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty
new file mode 100644
index 0000000..dca60fa
--- /dev/null
+++ b/doc/gost/gost-7-32-bibliography.sty
@@ -0,0 +1,57 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\makeatother
diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty
new file mode 100644
index 0000000..43447d5
--- /dev/null
+++ b/doc/gost/gost-7-32-captions.sty
@@ -0,0 +1,23 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, justification=centering, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=above}
20
21\addto\captionsrussian{\renewcommand{\figurename}{Рис.}}
22% \addto\captionsrussian{\renewcommand{\mintedname}{Рис.}}
23\addto\captionsrussian{\captionsetup[listing]{name=Рис.}}
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty
new file mode 100644
index 0000000..01d944b
--- /dev/null
+++ b/doc/gost/gost-7-32-counters.sty
@@ -0,0 +1,44 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\makeatother
38
39% Increment figure counter when using lstlisting
40\let\oldlstlisting\lstlisting
41\renewcommand{\lstlisting}[1][]{%
42 \refstepcounter{figure}
43 \oldlstlisting[#1]
44}
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty
new file mode 100644
index 0000000..cb2a7f0
--- /dev/null
+++ b/doc/gost/gost-7-32-headings.sty
@@ -0,0 +1,114 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9\setcounter{secnumdepth}{5}
10
11%
12% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
13%
14\titleformat{\section}[block]{\centering\Large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
15\titlespacing*{\section}{0cm}{0cm}{0.5cm}
16\newcommand{\sectionbreak}{\clearpage}
17
18\titleformat{\subsection}[block]{\Large\bfseries}{\thesubsection}{0.5em}{}
19\titlespacing{\subsection}{0cm}{0.5cm}{0.25cm}
20
21\titleformat{\subsubsection}[block]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}
22\titlespacing{\subsubsection}{0cm}{0.5em}{0.25cm}
23
24\titleformat{\paragraph}[block]{\normalsize\bfseries}{\theparagraph}{0.5em}{}
25\titlespacing*{\paragraph}{0cm}{0.5em}{0.25cm}
26
27\titleformat{\subparagraph}[block]{\normalsize\bfseries}{\thesubparagraph}{0.5em}{}
28\titlespacing{\subparagraph}{0cm}{0.5em}{0.25cm}
29
30\makeatletter
31\let\oldsection\section
32\newcommand{\@sectionnostar}[1]{\oldsection*{#1}\addcontentsline{toc}{section}{#1}}
33\newcommand{\@sectionstar}[1]{\oldsection{#1}}
34\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}}
35\makeatother
36
37%
38% Make special headings, that have their own formatting rules:
39% - centered
40% - all-caps
41% - bold
42%
43% Only three of them must appear in TOC: introduction, conclusion and references
44%
45\newcommand{\introduction}{
46 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
47 \begin{center}
48 \bfseries\large
49 ВВЕДЕНИЕ
50 \end{center}
51}
52
53\newcommand{\conclusion}{
54 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
55 \begin{center}
56 \bfseries\large
57 ЗАКЛЮЧЕНИЕ
58 \end{center}
59}
60
61\newcommand{\references}{
62 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
63 \begin{center}
64 \bfseries\large
65 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
66 \end{center}
67}
68
69\newcommand{\essay}{
70 \begin{center}
71 \bfseries\large
72 РЕФЕРАТ
73 \end{center}
74}
75
76\newcommand{\definitions}{
77 \begin{center}
78 \bfseries\large
79 ОПРЕДЕЛЕНИЯ
80 \end{center}
81}
82
83\newcommand{\abbreviations}{
84 \begin{center}
85 \bfseries\large
86 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
87 \end{center}
88}
89
90\newcommand{\defsabbrs}{
91 \begin{center}
92 \bfseries\large
93 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
94 \end{center}
95}
96
97%
98% Appendices headings. Appendices have autoincrementing number,
99% that is represented with russian letter.
100% This heading must appear in TOC
101%
102\newcounter{appendixcnt}
103\setcounter{appendixcnt}{1}
104
105\renewcommand{\appendix}[1]{
106 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
107 \begin{center}
108 \bfseries\large
109 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
110
111 #1
112 \end{center}
113 \stepcounter{appendixcnt}
114}
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty
new file mode 100644
index 0000000..6f41980
--- /dev/null
+++ b/doc/gost/gost-7-32-lists.sty
@@ -0,0 +1,17 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11\setlist[itemize, 3]{label=\bullet}
12
13\setlist[enumerate, 2]{label=\alphRus*)}
14
15\setlist[1]{wide=\parindent}
16\setlist[2]{wide=2\parindent, leftmargin=\parindent}
17\setlist[3]{wide=2\parindent}
diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty
new file mode 100644
index 0000000..750ab75
--- /dev/null
+++ b/doc/gost/gost-7-32-tables.sty
@@ -0,0 +1,29 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\newcommand{\designation}[2]{#1 &---& #2. \\}
diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty
new file mode 100644
index 0000000..328079d
--- /dev/null
+++ b/doc/gost/gost-7-32-toc.sty
@@ -0,0 +1,34 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black,
14 hidelinks
15]{hyperref}
16
17%
18% Set custom font styles
19%
20\renewcommand{\cftsecfont}{\normalfont}
21\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
22\renewcommand{\cftsecpagefont}{\normalsize}
23\renewcommand{\cftaftertoctitle}{\hfill\hfill}
24\renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31\setlength{\cftbeforesecskip}{0cm}
32\setlength{\cftbeforesubsecskip}{0cm}
33\setlength{\cftbeforesubsubsecskip}{0cm}
34\setlength{\cftbeforeparaskip}{0cm}
diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls
new file mode 100644
index 0000000..c13b00e
--- /dev/null
+++ b/doc/gost/gost-7-32.cls
@@ -0,0 +1,62 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\RequirePackage{gost-7-32-tables}
diff --git a/doc/ox-init.el b/doc/ox-init.el
new file mode 100644
index 0000000..94aec5f
--- /dev/null
+++ b/doc/ox-init.el
@@ -0,0 +1,31 @@
1;;; ox-init.el --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(setq org-latex-src-block-backend 'minted)
13
14(require 'oc-bibtex)
15(setq org-latex-bib-compiler "biber")
16
17(setq org-latex-remove-logfiles nil)
18
19(setq org-latex-caption-above '(table))
20
21(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
22 "%bib %b"
23 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
24(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
25 ("\\section{%s}" . "\\section*{%s}")
26 ("\\subsection{%s}" . "\\subsection*{%s}")
27 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
28 ("\\paragraph{%s}" . "\\paragraph*{%s}")
29 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
30
31;;; ox-init.el ends here
diff --git a/doc/report.org b/doc/report.org
new file mode 100644
index 0000000..64d09fb
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,1060 @@
1#+title: Построение контексно-свободной грамматики подмножества естественного языка
2#+subtitle: Словацкий язык: будущее время
3#+author: Михалец Мартин
4#+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №3}
5#+latex_header: \subject{по дисциплине «Математическая логика и теория автоматов»}
6#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
7#+latex_header: \institute{Институт компьютерных наук и кибербезопасности}
8#+latex_header: \school{Высшая школа технологии искусственного интеллекта}
9#+latex_header: \direction{02.03.01 Математика и компьютерные науки}
10#+latex_header: \reviewertitle{}\reviewer{Востров Алекскей Владимирович}
11#+latex_header: \city{Санкт-Петербург}
12#+date: 2025
13
14#+setupfile: setup.org
15#+latex: \sloppy
16#+latex: \setlength{\grammarparsep}{3pt}
17
18* ВВЕДЕНИЕ
19:PROPERTIES:
20:UNNUMBERED: t
21:END:
22Цель данной работы --- составить контексто свободную грамматику для
23подмножества предложений эстественного языка, определённого времени.
24На основе созданной грамматики требуется реализовать генерацию
25случайного предложения, пренадлежашего грамматике, и алгоритм
26распознавания введенного предложения.
27
28Будущее время в словацком языке называется /budúci čas/ или /futúrum/.
29Порядок слов в словацком языке более или менее свободный, его
30изменением значение предложения не меняется, но изменением порядка
31слов можно акцентировать отдельные слова. Обычный порядок слов:
32подлежащее + сказуемое + остальные члены предложения + завершающий
33знак препинания (концевой знак).
34
35В словацком языке можно строить сложные предложения (или составные
36предложения) --- это предложения, состоящее из нескольких простых
37предложений и выражающее одну завершённую мысль. Они могут быть как
38простыми так и сложными:
39- Простое сложное предложение:
40 - Содержит две предикативные единицы (два грамматических основы).
41 - Пример: Jano sadol do auta a odišiel.
42 - Перевод: Яно сел в машину и уехал.
43- Составное сложное предложение
44 - Содержит более двух предикативных единиц (три и более
45 грамматических основ).
46 - Пример: Mama vedela, že príde, lebo mu verila.
47 - Перевод: Мама знала, что он придёт, потому что верила ему.
48
49Существует много разных типов составных предложений, но в них всегда
50используются союзы или соединительные выражения, для соединения частей
51предложения.
52
53* Постановка задачи
54В качестве эстественного языка был выбран словацкий язык, будущего
55времени, с ограничением на простые предложения состоящие из нескольких
56фрагментов, с поддержкой замолчанного субьекта.
57
58Для рассмотрения применимость КС-грамматик в работе с морфологически
59корректными предложениями, реализуем соглашение лица и числа субьекта
60и глагола фрагмента предложения.
61
62Для отображения результата работы синтаксичесого анализатора надо
63автоматически генерировать дерево разбора.
64
65* Математическое описание
66/Контекстно-свободная грамматика/ --- частный случай формальной
67грамматики (тип 2 по иерархии Хомского), у которой левые части всех
68продукций являются одиночными нетерминалами. Смысл термина
69«контекстно-свободная» заключается в том, что есть возможность
70применить продукцию к нетерминалу, причём независимо от контекста
71этого нетерминала (в отличие от общего случая неограниченной
72грамматики Хомского).
73
74Язык, который может быть задан КС-грамматикой, называется
75контекстно-свободным языком или КС-языком.
76
77Одной из форм записи КС-грамматики является БНФ.
78
79** КС-грамматика подмножества предложений словацкого языка
80Предложения на словацком языке состоят из одного или больше
81фрагментов, из-за чего не получится построить автоматную грамматику,
82так как для этого нам потребуется продукция вида \(A \rightarrow
83BaA\), что нарушило линейную структуру А-грамматики. Но в тоже время
84КС-грамматика для нас достаточна, так как в левой части продукции в
85данном случае получается всегда указать один нетерминал.
86
87И так, все продукции имеют вид : \(A \rightarrow \gamma\)
88
89На рис. [[sentence]] представлены правила, описывающие предложения. Для
90того, чтобы в дальнейшем распознавать всю строчку как предложение,
91будем начинать из нетерминала \synt{initial}.
92
93#+name: sentence
94#+caption: Предложение
95#+attr_latex: :options [H]
96#+begin_figure
97\setlength{\grammarindent}{7em}
98\begin{grammar}
99 <initial> $::=$ <sentence> <EOF>
100
101 <sentence> $::=$ <fragment> <sentence-end>
102 \alt <fragment> `, ' <sentence>
103 \alt <fragment> `, ' <fragment-joiner> ` ' <sentence>
104
105 <sentence-end> $::=$ `.' | `?' | `!' | `...'
106\end{grammar}
107#+end_figure
108
109Фрагмент простого предложения состоит из субъекта, который может быть
110опущен, глагола и объекта. В качестве объекта будем рассматривать
111только существительные. На этом этапе согласовывается число и лицо
112субъекта и глагола. На рис. [[fragment]] представлены правила фрагментов
113предложения.
114
115#+name: fragment
116#+caption: Фрагмент предложения
117#+attr_latex: :options [H]
118#+begin_figure
119\begin{grammar}
120 <fragment> $::=$ <verb> ` ' <object> | <fragment-sg> | <fragment-pl>
121
122 <fragment-sg> $::=$ <fragment-sg-p1> | <fragment-sg-p2> | <fragment-sg-p3>
123
124 <fragment-pl> $::=$ <fragment-pl-p1> | <fragment-pl-p2> | <fragment-pl-p3>
125
126 <fragment-sg-p1> $::=$ <subject-sg-p1> ` ' <verb-sg-p1> ` ' <object>
127
128 <fragment-sg-p2> $::=$ <subject-sg-p2> ` ' <verb-sg-p2> ` ' <object>
129
130 <fragment-sg-p3> $::=$ <subject-sg-p3> ` ' <verb-sg-p3> ` ' <object>
131
132 <fragment-pl-p1> $::=$ <subject-pl-p1> ` ' <verb-pl-p1> ` ' <object>
133
134 <fragment-pl-p2> $::=$ <subject-pl-p2> ` ' <verb-pl-p2> ` ' <object>
135
136 <fragment-pl-p3> $::=$ <subject-pl-p3> ` ' <verb-pl-p3> ` ' <object>
137
138 <fragment-joiner> $::=$ `ale' | `keď'
139
140 <object> $::=$ <noun>
141\end{grammar}
142#+end_figure
143
144Субъектом может быть как местоимение, так и существительное, но за
145счёт согласования числа и лица, правил у нас будет куда больше, такое
146поведение будет продолжаться чуть ли не до корней слов, что делает
147КС-грамматики неочень удобными для морфологического согласования. На
148рис. [[subject]] представлены правила фрагментов предложения.
149
150#+name: subject
151#+caption: Субъект
152#+attr_latex: :options [H]
153#+begin_figure
154\begin{grammar}
155 <subject> $::=$ <subject-sg> | <subject-pl>
156
157 <subject-sg> $::=$ <subject-sg-p1> | <subject-sg-p2> | <subject-sg-p3>
158
159 <subject-pl> $::=$ <subject-pl-p1> | <subject-pl-p2> | <subject-pl-p3>
160
161 <subject-sg-p1> $::=$ <pronoun-sg-p1>
162
163 <subject-sg-p2> $::=$ <pronoun-sg-p2>
164
165 <subject-sg-p3> $::=$ <pronoun-sg-p3> | <noun-sg-nominative>
166
167 <subject-pl-p1> $::=$ <pronoun-pl-p1>
168
169 <subject-pl-p2> $::=$ <pronoun-pl-p2>
170
171 <subject-pl-p3> $::=$ <pronoun-pl-p3> | <noun-pl-nominative>
172\end{grammar}
173#+end_figure
174
175Местоимения описать довольно легко, тем более когда нам для них не
176нужна детализация по роду. Их правила представлены на рис. [[pronoun]].
177
178#+name: pronoun
179#+caption: Местоимение
180#+attr_latex: :options [H]
181#+begin_figure
182\begin{grammar}
183 <pronoun> $::=$ <pronoun-sg> | <pronoun-pl>
184
185 <pronoun-sg> $::=$ <pronoun-sg-p1> | <pronoun-sg-p2> | <pronoun-sg-p3>
186
187 <pronoun-pl> $::=$ <pronoun-pl-p1> | <pronoun-pl-p2> | <pronoun-pl-p3>
188
189 <pronoun-sg-p1> $::=$ `ja'
190
191 <pronoun-sg-p2> $::=$ `ty'
192
193 <pronoun-sg-p3> $::=$ `on' | `ona' | `ono'
194
195 <pronoun-pl-p1> $::=$ `my'
196
197 <pronoun-pl-p2> $::=$ `vy'
198
199 <pronoun-pl-p3> $::=$ `oni' | `ony'
200\end{grammar}
201#+end_figure
202
203Глаголы несовершенного вида будущего времени строятся как и в русском:
204быть будущего времени + инфинитив. Здесь начинается наблюдать
205разделение глаголов на группы, по тому, какие у них окончания в
206инфинитиве. Их правила представлены на рис. [[verb-imperfective]].
207
208#+name: verb-imperfective
209#+caption: Глагол -- несовершенный вид, будущее время
210#+attr_latex: :options [H]
211#+begin_figure
212\setlength{\grammarindent}{9em}
213\begin{grammar}
214 <verb-imperfective-indicative-future-sg-p1> $::=$ `budem ' <verb-infinitive>
215
216 <verb-imperfective-indicative-future-sg-p2> $::=$ `budeš ' <verb-infinitive>
217
218 <verb-imperfective-indicative-future-sg-p3> $::=$ `bude ' <verb-infinitive>
219
220 <verb-imperfective-indicative-future-pl-p1> $::=$ `budeme ' <verb-infinitive>
221
222 <verb-imperfective-indicative-future-pl-p2> $::=$ `budete ' <verb-infinitive>
223
224 <verb-imperfective-indicative-future-pl-p3> $::=$ `budú ' <verb-infinitive>
225
226 <verb-infinitive> $::=$ <verb-intinifive-g1>
227 \alt <verb-intinifive-g2>
228 \alt <verb-intinifive-g3>
229 \alt <verb-intinifive-g4>
230
231 <verb-intinifive-g1> $::=$ <verb-stem-g1> `ať'
232
233 <verb-intinifive-g2> $::=$ <verb-stem-g2> `iť'
234
235 <verb-intinifive-g3> $::=$ <verb-stem-g3> `ovať'
236
237 <verb-intinifive-g4> $::=$ <verb-stem-g4> `ieť'
238\end{grammar}
239#+end_figure
240
241Дальше, для глаголов совершенного вида приходится менять окончание не
242только по группе, но и возможной подгруппе, числу и лицу. На
243рис. [[verb-perfective-example]] представлены правила именно для группы 1,
244подгруппы «a», а также возможные приставки.
245
246#+name: verb-perfective-example
247#+caption: Глагол: совершённый вид, будущее время, группа 1, подгруппа «a»
248#+attr_latex: :options [H]
249#+begin_figure
250\begin{grammar}
251 <verb-perfective-indicative-future-sg-p1-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `ám'
252
253 <verb-perfective-indicative-future-sg-p2-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `áš'
254
255 <verb-perfective-indicative-future-sg-p3-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `á'
256
257 <verb-perfective-indicative-future-pl-p1-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `áme'
258
259 <verb-perfective-indicative-future-pl-p2-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `áte'
260
261 <verb-perfective-indicative-future-pl-p3-g1-a> $::=$ <verb-prefix> <verb-stem-g1-a> `ajú'
262
263 <verb-prefix> $::=$ `u' | `na' | `vy' | `pre' | `po' | `pod' | `za' | `pri' | `o' | `ob'
264\end{grammar}
265#+end_figure
266
267На рис. [[verb-stem]] представлены корни глаголов, разделённые по группам
268и подгруппам.
269
270#+name: verb-stem
271#+caption: Корень глагола
272#+attr_latex: :options [H]
273#+begin_figure
274\begin{grammar}
275 <verb-stem> $::=$ <verb-stem-g1> | <verb-stem-g2> | <verb-stem-g3> | <verb-stem-g4>
276
277 <verb-stem-g1> $::=$ <verb-stem-g1-a> | <verb-stem-g1-b>
278
279 <verb-stem-g2> $::=$ <verb-stem-g2-a> | <verb-stem-g2-b>
280
281 <verb-stem-g1-a> $::=$ `m' | `hľad' | `pozn' | `hr'
282
283 <verb-stem-g1-b> $::=$ `čít' | `pláv' | `umýv' | `liet'
284
285 <verb-stem-g2-a> $::=$ `rob' | `uč' | `var' | `lieč'
286
287 <verb-stem-g2-b> $::=$ `kúp' | `ľúb' | `pál'
288
289 <verb-stem-g3> $::=$ `kup' | `okup' | `poráb' | `vyráb' | `preráb' | `štud' | `prac' | `tanc' | `telefon' | `fotograf' | `mail' | `maľ'
290
291 <verb-stem-g4> $::=$ `rozum' | `ved'
292\end{grammar}
293#+end_figure
294
295В словацком языке, существительные склоняются по типовым примерам, но
296и здесь возможны исключения, их можно заметить на примере
297\synt{noun-chlap-pl-nominative}. На рис. [[noun]] представлены
298существительные склоняющиеся по типу chlap -- мужчина.
299
300#+name: noun
301#+caption: Существительнео
302#+attr_latex: :options [H]
303#+begin_figure
304\setlength{\grammarindent}{15em}
305\begin{grammar}
306 <noun> $::=$ <noun-chlap> | ...
307
308 <noun-chlap> $::=$ <noun-chlap-sg> | <noun-chlap-pl>
309
310 <noun-chlap-sg> $::=$ <noun-chlap-sg-nominative> | ...
311
312 <noun-chlap-pl> $::=$ <noun-chlap-pl-nominative> | ...
313
314 <noun-chlap-sg-nominative> $::=$ <noun-stem-chlap-i>
315 \alt <noun-stem-chlap-ia>
316 \alt <noun-stem-chlap-ovia> `o'
317
318 <noun-chlap-sg-genitive> $::=$ <noun-stem-chlap> `a'
319
320 <noun-chlap-sg-dative> $::=$ <noun-stem-chlap> `ovi'
321
322 <noun-chlap-sg-accusative> $::=$ <noun-stem-chlap> `a'
323
324 <noun-chlap-sg-locative> $::=$ <noun-stem-chlap> `ovi'
325
326 <noun-chlap-sg-instrumental> $::=$ <noun-stem-chlap> `om'
327
328 <noun-chlap-pl-nominative> $::=$ <noun-stem-chlap-i> `i'
329 \alt <noun-stem-chlap-ia> `ia'
330 \alt <noun-stem-chlap-ovia> `ovia'
331
332 <noun-chlap-pl-genitive> $::=$ <noun-stem-chlap> `ov'
333
334 <noun-chlap-pl-dative> $::=$ <noun-stem-chlap> `om'
335
336 <noun-chlap-pl-accusative> $::=$ <noun-stem-chlap> `ov'
337
338 <noun-chlap-pl-locative> $::=$ <noun-stem-chlap> `och'
339
340 <noun-chlap-pl-instrumental> $::=$ <noun-stem-chlap> `mi'
341
342 <noun-stem-chlap> $::=$ <noun-stem-chlap-i>
343 \alt <noun-stem-chlap-ia>
344 \alt <noun-stem-chlap-ovia>
345
346 <noun-stem-chlap-i> $::=$ `chlap' | `rytier'
347
348 <noun-stem-chlap-ia> $::=$ `brat'
349
350 <noun-stem-chlap-ovia> $::=$ `uj' | `ded' | `Pal' | `strýk'
351\end{grammar}
352#+end_figure
353
354** Синтаксический анализ построенной грамматики
355Даже при применений факторизации левых префиксов, грамматику не
356получится привести к LL(1) из-за того, что такая факторизация
357выполняется для каждого терминала отдельно, и не заходит во внутрь
358продукции. Упрощённый пример такой проблемы представлен на
359рис. [[problem]].
360
361#+name: problem
362#+caption: Пример проблемной грамматики
363#+attr_latex: :options [H]
364#+begin_figure
365\setlength{\grammarindent}{7em}
366\begin{grammar}
367 <subject> $::=$ <pronoun> | <noun>
368
369 <pronoun> $::=$ `she' | ...
370
371 <noun> $::=$ `sheep' | ...
372\end{grammar}
373#+end_figure
374
375Для приведения грамматики к LL(1) пришлось бы выполнить более глубокую
376факторизацию, которая нарушила бы структуру дерева разбора.
377
378* Программная реализация
379Грамматика загружается из файла в формате =bnf=. Составленный файл
380предоставлен в приложений [[#bnf][A]]. Реализация лексического и
381синтаксического анализа BNF с семантическим дополнением рассмотрена в
382лабораторной работе №5, в этой работе обратим внимание на составление
383таблицы выбора для синтаксического анализатора.
384
385** Данные
386Данные получаемые из синтаксического анализатора BNF структурированы
387следующим образом у синтаксиса ~bnf_syntax~ массив правил ~bnf_rule~.
388Каждое такое правило определяет несколько продукции грамматики, у
389которых в левой части нетерминал ~name~, а в правой одна из альтернатив
390из ~is_replaced_be~. Альтернативы ~bnf_sequence~ состоят из массива
391лексем ~bnf_lexeme~ у которых ~kind~ либо нетерминал либо терминал. Они
392имеют следующий вид:
393#+begin_src c
394struct bnf_lexeme {
395 struct string_view sv;
396 enum bnf_lexeme_kind kind;
397};
398
399struct bnf_sequence {
400 struct bnf_lexeme *items;
401 uint32_t count;
402 uint32_t capacity;
403};
404
405struct bnf_rule {
406 struct bnf_lexeme name;
407 struct {
408 struct bnf_sequence *items;
409 uint32_t count;
410 uint32_t capacity;
411 } is_replaced_by;
412};
413
414struct bnf_syntax {
415 struct bnf_rule *items;
416 uint32_t count;
417 uint32_t capacity;
418};
419#+end_src
420
421Эту структуру данных переведём для более удобной работы к следующему
422виду. Грамматика ~grammar~ будет состоять из начального нетерминала,
423описания нетерминалов и продукции. Каждая продукция состоит из терма
424нетерминала ~from~ и последовательности термов ~to~. Ограничимся
425максимальным количеством различных термов ~symbol~ в 2^{32}, где первых
426256 будут отображать терминалы -- все разные значения байта, и
427следующих 2 конец строки и конец файла соответственно. Остальные
428термы выделены под нетерминалы. Эти типы имеют следующий вид:
429#+begin_src c
430typedef uint32_t symbol;
431
432struct symbols {
433 symbol *items;
434 uint32_t count;
435 uint32_t capacity;
436};
437
438struct production {
439 symbol from;
440 struct symbols to;
441};
442
443struct productions {
444 struct production *items;
445 uint32_t count;
446 uint32_t capacity;
447};
448
449struct selections {
450 struct selection {
451 symbol input;
452 uint32_t production;
453 } *items;
454 uint32_t count;
455 uint32_t capacity;
456};
457
458struct nonterminal {
459 const char *name;
460 struct selections selections;
461};
462
463struct nonterminals {
464 struct nonterminal *items;
465 uint32_t count;
466 uint32_t capacity;
467};
468
469struct grammar {
470 symbol initial_nonterminal;
471 struct nonterminals nonterminals;
472 struct productions productions;
473};
474#+end_src
475
476** Построение грамматики
477*** Функция построения грамматики на основе BNF синтаксиса
478Устанавливает начальный нетерминал, сохраняет информацию о
479нетерминалах, заполняет грамматику продукциями из BNF синтаксиса.
480- Вход: :: BNF синтаксис, распознанный из текста.
481- Выход: :: грамматика, для распознавания текста.
482#+begin_src c
483static struct grammar
484build_grammar (struct bnf_syntax syntax)
485{
486 struct grammar grammar = { .initial_nonterminal = TERMINAL_COUNT };
487
488 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
489 size_t nonterminal_name_len = STRING_VIEW_LEN (rule->name.sv) - 2;
490 char *nonterminal_name = malloc (nonterminal_name_len + 1);
491 nonterminal_name[nonterminal_name_len] = '\0';
492 memcpy (nonterminal_name, rule->name.sv.beg + 1, nonterminal_name_len);
493 DYNAMIC_ARRAY_APPEND (grammar.nonterminals,
494 ((struct nonterminal) { .name = nonterminal_name }));
495 }
496
497 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
498 symbol from = TERMINAL_COUNT + (rule - syntax.items);
499 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
500 struct production production = { .from = from };
501 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
502 switch (term->kind) {
503 case BNF_LEXEME_KIND_TERMINAL:
504 for (const char *p = term->sv.beg + 1; p < term->sv.end - 1; ++p)
505 DYNAMIC_ARRAY_APPEND (production.to, (uint8_t) *p);
506 break;
507 case BNF_LEXEME_KIND_NONTERMINAL:
508 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) {
509 DYNAMIC_ARRAY_APPEND (production.to, 256);
510 } else if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) {
511 DYNAMIC_ARRAY_APPEND (production.to, 257);
512 } else {
513 size_t term_len = STRING_VIEW_LEN (term->sv) - 2;
514 DYNAMIC_ARRAY_FOREACH (nonterminal, grammar.nonterminals) {
515 size_t nonterminal_name_len = strlen (nonterminal->name);
516 if (nonterminal_name_len != term_len) continue;
517 if (memcmp (nonterminal->name, term->sv.beg + 1, term_len)) continue;
518 DYNAMIC_ARRAY_APPEND (production.to,
519 TERMINAL_COUNT +
520 (nonterminal - grammar.nonterminals.items));
521 break;
522 }
523 } break;
524 default: UNREACHABLE ();
525 };
526 }
527 DYNAMIC_ARRAY_APPEND (grammar.productions, production);
528 }
529 }
530
531 return grammar;
532}
533#+end_src
534
535*** Функция факторизации общих левых префиксов
536Производит факторизацию общих левых префиксов, изменяя указанную
537грамматику. Названия новых нетерминалов суффиксируются с ='=.
538- Вход: :: грамматика.
539- Выход: :: грамматика, с проведённой факторизацией.
540#+begin_src c
541static void
542grammar_left_factor_common_prefixes (struct grammar *grammar)
543{
544 struct symbols handled = {0};
545
546 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
547 DYNAMIC_ARRAY_FOREACH (symbol, handled)
548 if (*symbol == production->from) goto next_production;
549
550 symbol from = production->from;
551
552 size_t factored = 0;
553 factor_single:
554 struct {
555 struct production **items;
556 uint32_t count;
557 uint32_t capacity;
558 } same = {0};
559 DYNAMIC_ARRAY_FOREACH (other, grammar->productions) {
560 if (other->from != from) continue;
561 DYNAMIC_ARRAY_APPEND (same, other);
562 }
563
564 qsort (same.items, same.count, sizeof (same.items[0]),
565 compare_production_pointers);
566
567 DYNAMIC_ARRAY_FOREACH (production, same) {
568 if (production + 1 == same.items + same.count) break;
569 struct production *prod = *(production + 0);
570 struct production *next = *(production + 1);
571
572 struct symbols prefix = {0};
573 for (uint32_t i = 0; i < MIN (prod->to.count, next->to.count); ++i) {
574 if (prod->to.items[i] != next->to.items[i]) break;
575 DYNAMIC_ARRAY_APPEND (prefix, prod->to.items[i]);
576 } if (prefix.count == 0) continue;
577
578 const char *nonterminal_name =
579 grammar->nonterminals.items[prod->from - TERMINAL_COUNT].name;
580 size_t nonterminal_name_len = strlen (nonterminal_name);
581 char *nonterminal_name_new = malloc (nonterminal_name_len + 2 + factored);
582 symbol from_new = TERMINAL_COUNT + grammar->nonterminals.count;
583 memcpy (nonterminal_name_new, nonterminal_name, nonterminal_name_len);
584 for (size_t i = nonterminal_name_len; i < nonterminal_name_len + factored + 1; ++i)
585 nonterminal_name_new[i] = '\'';
586 nonterminal_name_new[nonterminal_name_len + factored + 1] = '\0';
587 DYNAMIC_ARRAY_APPEND (grammar->nonterminals,
588 ((struct nonterminal) { .name = nonterminal_name_new }));
589
590 struct production prod_new = { .from = prod->from };
591 DYNAMIC_ARRAY_APPEND_MANY (prod_new.to, prefix.items, prefix.count);
592 DYNAMIC_ARRAY_APPEND (prod_new.to, from_new);
593 DYNAMIC_ARRAY_APPEND (grammar->productions, prod_new);
594
595 struct {
596 struct production **items;
597 uint32_t count;
598 uint32_t capacity;
599 } rewrite = {0};
600 DYNAMIC_ARRAY_APPEND (rewrite, prod);
601 DYNAMIC_ARRAY_APPEND (rewrite, next);
602 for (uint32_t i = production + 2 - same.items; i < same.count; ++i) {
603 struct production *p = same.items[i];
604 if (p->to.count < prefix.count) continue;
605 if (memcmp (p->to.items, prefix.items,
606 prefix.count*sizeof (*prefix.items))) continue;
607 DYNAMIC_ARRAY_APPEND (rewrite, p);
608 }
609
610 DYNAMIC_ARRAY_FOREACH (p, rewrite) {
611 struct production *prod = *p;
612 prod->from = from_new;
613 memmove (prod->to.items,
614 prod->to.items + prefix.count,
615 (prod->to.count - prefix.count) *
616 sizeof (prod->to.items[0]));
617 prod->to.count -= prefix.count;
618 }
619
620 factored += 1;
621 goto factor_single;
622 }
623
624 DYNAMIC_ARRAY_APPEND (handled, production->from);
625 next_production:
626 }
627}
628#+end_src
629
630** Построение таблицы выбора
631*** Функция построения множества FIRST
632Рекурсивно добавляет подходящие термы в множество, следя за наличием
633эпсилона.
634- Вход: :: грамматика, последовательность термов, подмножество FIRST.
635- Выход: :: наличие эпсилона, расширенное подмножество FIRST.
636#+begin_src c
637static bool
638first (struct grammar grammar, struct symbols syms, struct symbols *set)
639{
640 if (syms.count == 0) return true;
641
642 symbol first_sym = syms.items[0];
643 if (first_sym < TERMINAL_COUNT) {
644 DYNAMIC_ARRAY_FOREACH (sym, *set)
645 if (*sym == first_sym) return false;
646 DYNAMIC_ARRAY_APPEND (*set, first_sym);
647 return false;
648 }
649
650 bool has_epsilon = false;
651 DYNAMIC_ARRAY_FOREACH (production, grammar.productions) {
652 if (production->from != first_sym) continue;
653 has_epsilon = first (grammar, production->to, set);
654 }
655
656 if (has_epsilon) {
657 syms.items += 1;
658 syms.count -= 1;
659
660 return first (grammar, syms, set);
661 }
662
663 return false;
664}
665#+end_src
666
667*** Функция построения множества FOLLOW
668Рекурсивно добавляет подходящие термы в множество, с использованием
669стека для предотвращения бесконечной рекурсии.
670- Вход: :: грамматика, нетерминал, подмножество FOLLOW, стек
671 рассмотренных нетерминалов.
672- Выход: :: расширенное подмножество FOLLOW.
673#+begin_src c
674static void
675follow (struct grammar grammar, symbol nonterm,
676 struct symbols *set, struct symbols *stack)
677{
678 DYNAMIC_ARRAY_FOREACH (nt, *stack)
679 if (*nt == nonterm) return;
680
681 DYNAMIC_ARRAY_APPEND (*stack, nonterm);
682 DYNAMIC_ARRAY_FOREACH (production, grammar.productions) {
683 DYNAMIC_ARRAY_FOREACH (sym, production->to) {
684 if (*sym != nonterm) continue;
685 if (sym == &DYNAMIC_ARRAY_LAST (production->to)) {
686 if (*sym == production->from) continue;
687 follow (grammar, production->from, set, stack);
688 continue;
689 }
690
691 struct symbols syms = {
692 .items = sym + 1,
693 .count = production->to.count - (sym - production->to.items),
694 };
695 if (first (grammar, syms, set))
696 follow (grammar, production->from, set, stack);
697 }
698 }
699 stack->count -= 1;
700}
701#+end_src
702
703*** Функция построения таблицы выбора
704К описанию нетерминалов грамматики добавляет выбор продукции при
705определённом входе. Надо отдельно отметить, что одному входу может
706соответствовать множество продукции.
707- Вход: :: грамматика.
708- Выход: :: грамматика, оснащенная таблицей выбора в описаний
709 нетерминалов.
710#+begin_src c
711static void
712build_lookup_table (struct grammar *grammar)
713{
714 struct symbols selection = {0};
715 struct symbols stack = {0};
716 DYNAMIC_ARRAY_FOREACH (nonterminal, grammar->nonterminals) {
717 DYNAMIC_ARRAY_FOREACH (production, grammar->productions) {
718 if (production->from != TERMINAL_COUNT +
719 (nonterminal - grammar->nonterminals.items)) continue;
720 selection.count = 0;
721 stack.count = 0;
722 if (first (*grammar, production->to, &selection))
723 follow (*grammar, production->from, &selection, &stack);
724
725 for (uint32_t i = 0; i < selection.count - 1; ++i) {
726 for (uint32_t j = i + 1; j < selection.count; ++j) {
727 if (selection.items[j] != selection.items[i]) continue;
728 selection.items[j] = selection.items[--selection.count];
729 }
730 }
731
732 DYNAMIC_ARRAY_FOREACH (sym, selection) {
733 DYNAMIC_ARRAY_APPEND (
734 nonterminal->selections,
735 ((struct selection) {
736 .input = *sym,
737 .production = production - grammar->productions.items,
738 }));
739 }
740 }
741 }
742 DYNAMIC_ARRAY_FREE (selection);
743 DYNAMIC_ARRAY_FREE (stack);
744}
745#+end_src
746
747** Дерево разбора
748Каждый узел дерева разбора содержит потомков, терм, которому он
749соответствует, начало в тексте и указатель на родителя.
750#+begin_src c
751struct tree {
752 struct children {
753 struct tree *items;
754 uint32_t count;
755 uint32_t capacity;
756 } children;
757 struct tree *parent;
758 const char *begin;
759 symbol symbol;
760};
761#+end_src
762
763*** Функция перехода к предыдущему листу
764Находит предыдущий лист, или возвращает =NULL=.
765- Вход: :: указатель на поддерево.
766- Выход: :: указатель на поддерево или =NULL=.
767#+begin_src c
768static struct tree *
769tree_prev_leaf (struct tree *tree)
770{
771 ASSERT (tree);
772
773 if (tree->children.count > 0) {
774 while (tree->parent && tree == tree->parent->children.items)
775 tree = tree->parent;
776 if (!tree->parent) return NULL;
777 tree -= 1;
778 while (tree->children.count > 0)
779 tree = &DYNAMIC_ARRAY_LAST (tree->children);
780 return tree;
781 }
782
783 if (!tree->parent) return NULL;
784 if (tree > tree->parent->children.items) {
785 tree -= 1;
786 while (tree->children.count > 0)
787 tree = &DYNAMIC_ARRAY_LAST (tree->children);
788 return tree;
789 }
790
791 return NULL;
792}
793#+end_src
794
795*** Функция перехода к следующему листу
796Находит следующий лист, или возвращает =NULL=.
797- Вход: :: указатель на поддерево.
798- Выход: :: указатель на поддерево.
799#+begin_src c
800static struct tree *
801tree_next_leaf (struct tree *tree)
802{
803 ASSERT (tree);
804
805 if (tree->children.count > 0) {
806 do tree = tree->children.items;
807 while (tree->children.count > 0);
808 return tree;
809 }
810
811 if (!tree->parent) return NULL;
812
813 if (tree < &DYNAMIC_ARRAY_LAST (tree->parent->children)) {
814 tree += 1;
815 while (tree->children.count > 0)
816 tree = tree->children.items;
817 return tree;
818 }
819
820 do tree = tree->parent;
821 while (tree->parent && tree == &DYNAMIC_ARRAY_LAST (tree->parent->children));
822 if (!tree->parent) return NULL;
823 return tree + 1;
824}
825#+end_src
826
827*** Функция удаления потомка
828Удаляет потомка, если его родитель становится бездетным, удаляет и
829его, и так далее.
830- Вход: :: указатель на поддерево.
831- Выход: :: изменена структура дерева.
832#+begin_src c
833static void
834tree_remove_child (struct tree *child)
835{
836 assert (child);
837
838 while (child->parent && child->children.count == 0) {
839 struct tree *parent = child->parent;
840 if (child != &DYNAMIC_ARRAY_LAST (parent->children))
841 memmove (child, child + 1,
842 (&DYNAMIC_ARRAY_LAST (parent->children) - child)*sizeof (*child));
843 parent->children.count -= 1;
844 child = parent;
845 }
846}
847#+end_src
848
849** Разбор текста
850За счёт того, что грамматику не получается привести к LL(1),
851реализован алгоритм возвращение назад.
852
853*** Функция построения дерева разбора
854Запускает рекурсивную функцию построения дерева разбора.
855- Вход: :: грамматика, строка.
856- Выход: :: дерево разбора.
857#+begin_src c
858static struct tree
859parse (struct grammar grammar, const char *str)
860{
861 struct tree tree = {
862 .symbol = grammar.initial_nonterminal,
863 .begin = str,
864 };
865 parse_impl (grammar, &tree);
866 return tree;
867}
868#+end_src
869
870*** Рекурсивная функция построения дерева разбора
871Строит дерево разбора, рекурсивно детализируя узлы дерева. При
872многозначном выборе продукции, поочередно применяются все, пока с этим
873выбором не получится разобрать текст до конца.
874- Вход: :: грамматика, вершина дерева.
875- Выход: :: признак соответствия грамматике, построенное поддерево разбора.
876#+begin_src c
877static bool
878parse_impl (struct grammar grammar, struct tree *leaf)
879{
880 do {
881 if (leaf->parent) {
882 leaf->begin = leaf->parent->begin;
883 DYNAMIC_ARRAY_FOREACH (child, leaf->parent->children) {
884 if (child == leaf) break;
885 leaf->begin += tree_count_terminals_within (child);
886 }
887 }
888
889 if (leaf->symbol < TERMINAL_COUNT) {
890 if (!(*leaf->begin == '\n' && leaf->symbol == 256 ||
891 ,,*leaf->begin == '\0' && leaf->symbol == 257) &&
892 (uint8_t) *leaf->begin != leaf->symbol) {
893 return false;
894 };
895
896 } else { // nonterminal
897 struct selections selections =
898 grammar.nonterminals.items[leaf->symbol - TERMINAL_COUNT].selections;
899 DYNAMIC_ARRAY_FOREACH (selection, selections) {
900 if (!(*leaf->begin == '\n' && selection->input == 256 ||
901 ,,*leaf->begin == '\0' && selection->input == 257 ||
902 selection->input == (uint8_t) *leaf->begin))
903 continue;
904
905 struct production production =
906 grammar.productions.items[selection->production];
907 if (production.to.count == 0) {
908 if (parse_impl (grammar, tree_next_leaf (leaf)))
909 return true;
910 } else {
911 DYNAMIC_ARRAY_FOREACH (sym, production.to) {
912 DYNAMIC_ARRAY_APPEND (leaf->children, ((struct tree) {
913 .symbol = *sym,
914 .parent = leaf,
915 }));
916 }
917
918 if (parse_impl (grammar, tree_next_leaf (leaf)))
919 return true;
920 DYNAMIC_ARRAY_RESET (leaf->children);
921 }
922 }
923 return false;
924 }
925 } while (leaf = tree_next_leaf (leaf));
926 return true;
927}
928#+end_src
929
930* Результаты работы
931На рис. [[generated]] представлены сгенерированные предложения. Можно
932заметить, что они состоят из разного количества фрагментов, имеют
933разные окончания и в некоторых фрагментах опущен субъект.
934
935#+name: generated
936#+caption: Сгенерированные предложения
937#+begin_src text
938Ty preľúbiš Kraskov, ona bude vedieť počítači, podliečíte dážď, cibuľa vyhľadá kuratá, ale oni ovaria morami, ty očítaš knihe, ono bude vedieť umenieie.
939Ja načítam Kraskovi, ty budeš mať ruka, keď budeš vedieť stretnutia, ty prelietaš huslu, ale ono bude vedieť princeznej, keď vy učítate mláďatá, ale ty budeš plávať bruchom?
940My budeme rozumieť dlaňe, bude robiť oleja.
941Púšť bude páliť chlápät, keď ono podrozumie úskalia, keď my budeme mať orchideu, vy budete maľovať lístím, ale oni budú vedieť chlápäťu, keď ukupuje vysvedčeniach, ja utelefonujem pozadím.
942Ty budeš telefonovať Nikaragua, keď ono bude vedieť Kraskovi, my budeme rozumieť noci, ale budem maľovať dážďmi?
943Vy zaľúbite stromoch, budeš páliť bratoch...
944Ty budeš tancovať uja.
945Ty ukúpiš huslovi, lístia budú fotografovať Kraskovi, vy opálite umenieia, polia budú učiť mláďa, keď obľúbim knihe, keď my budeme tancovať chvíľe, vy privaríte trolejbusy, ony budú liečiť kosťou, vy budete liečiť vodopádi, bude učiť chvíľou!
946Vy budete kupovať pieseňi, ale dážďe budú prerábovať nástupištia, my budeme robiť huslom?
947Budú robiť rodiny, keď ja pohľadám bratoch.
948Budem umývať sluhami, keď ty obliečíš kráľovnej.
949My vypracujeme reportáž, keď ony budú ľúbiť úskaliam, vy budete rozumieť šľachtičnej, zarobia auto?
950Nástupište opozná brata, keď ja ukúpim dlaňi, ale ja budem ľúbiť vodopád, ona prevedie kuliami, ona preliečí pážaťa...
951Vody obhľadajú kôša, ale vy budete rozumieť zmesiach, ale vyčítam báseňiach, vy budete rozumieť košeľíc...
952Vy obrozumiete huslov...
953My oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
954Ty budeš mailovať stredám?
955#+end_src
956
957На рис. [[no-match-first]] указан пример с не соответствием грамматике по
958причине начала предложения с маленькой, а не большой буквы.
959
960#+name: no-match-first
961#+caption: Предложение не соответсвующее грамматике -- не начинается с большой буквы
962#+begin_src text
963Enter string to parse: my oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
964didn't match!
965#+end_src
966
967На рис. [[no-match-number]] указан пример с не соответствием грамматике по
968причине не согласования числа у субъекта и глагола. У `My oučím' можно
969согласовать число следующими способами: `My oučíme', `Ja oučím'.
970
971#+name: no-match-number
972#+caption: Предложение не соответсвующее грамматике -- не согласованное число
973#+begin_src text
974Enter string to parse: My oučím stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
975didn't match!
976#+end_src
977
978На рис. [[match]] указан пример с предложением соответствующим
979грамматике. И на рис. [[tree]] представлено автоматически сгенерированно
980его дерево разбора.
981
982#+name: match
983#+caption: Предложение соответсвующее грамматике
984#+begin_src text
985Enter string to parse: My oučíme stromi, keď obtancuje pecou, ty budeš liečiť hrdinovi?
986matched
987./tmp/tree.dot:1:0: info: generated parsing tree
988#+end_src
989
990@@latex:\clearpage@@
991@@latex:\KOMAoptions{paper=A3,DIV=36}@@
992@@latex:\recalctypearea@@
993@@latex:\begin{landscape}@@
994@@latex:\thispagestyle{empty}@@
995#+name: tree
996#+caption: Сгенерированное дерево разбора
997#+attr_latex: :float nil :width 1.4\textwidth
998[[./tree.png]]
999@@latex:\vfill\raisebox{-10pt}{\makebox[\linewidth]{\thepage}}@@
1000@@latex:\end{landscape}@@
1001@@latex:\KOMAoptions{paper=A4,DIV=12}@@
1002@@latex:\recalctypearea@@
1003
1004* ЗАКЛЮЧЕНИЕ
1005:PROPERTIES:
1006:UNNUMBERED: t
1007:END:
1008В данной работе была разработана и формально описана КС‑грамматика для
1009подмножества естественного языка: словацкий язык, будущее время.
1010Полученная грамматика является контекстно-свободной, так как все
1011продукции имеют вид $A \to \gamma, где $A$ - нетерминал, и $\gamma \in
1012(T \cup N)^*$ - цепочка из терминалов и нетерминалов.
1013
1014Был сделан вывод, что в КС-грамматиках громоздко выразить
1015морфологические правила о согласований склонения слов.
1016
1017Разработанный синтаксический анализатор представляет собой
1018модифицированную LL(1)-грамматику с поддержкой механизма возврата
1019(backtracking), которая срабатывает при неоднозначности выбора
1020продукции.
1021
1022*Достоинства:*
1023- грамматика согласует число и лицо субъекта и глагола;
1024- загрузка грамматики из файла в формате BNF;
1025- автоматическая факторизация левых префиксов;
1026- автоматическая генерация дерева разбора.
1027
1028*Недостатки:*
1029- грамматику не получилось привести к удобной LL(1) грамматике;
1030- синтаксический анализатор не может разобрать текст частично;
1031- при не соответствий грамматике нет сообщения о том где именно
1032 настала проблема.
1033
1034*Масшатабируемость:*
1035- генерировать КС-грамматику по морфологическим правилам;
1036- реализовать алгоритм восстановления синтаксического анализ при
1037 обнаружении не соответствия грамматике;
1038- реализовать алгоритм глубокой факторизация левых префиксов без
1039 сильного ухудшения структуры дерева разбора.
1040
1041* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
1042:PROPERTIES:
1043:UNNUMBERED: t
1044:END:
1045#+latex: \nocite{VOSTROV2024}
1046#+print_bibliography: :heading none
1047
1048* ПРИЛОЖЕНИЕ А
1049:PROPERTIES:
1050:UNNUMBERED: t
1051:CUSTOM_ID: bnf
1052:END:
1053#+attr_latex: :options fontsize=\footnotesize
1054#+include: "../build/slovak.bnf" src bnf
1055
1056# Local Variables:
1057# org-confirm-babel-evaluate: nil
1058# org-export-async-init-file: "ox-init.el"
1059# org-export-in-background: t
1060# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..f5a41e3
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,34 @@
1#+options: ':nil *:t -:t ::t <:t H:4 \n:nil ^:{} arch:headline
2#+options: author:t broken-links:nil c:nil creator:nil
3#+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+options: timestamp:nil title:t toc:t todo:t |:t
6
7#+select_tags: export
8#+exclude_tags: noexport
9
10#+bibliography: biblio.bib
11#+cite_export: biblatex
12
13#+latex_compiler: xelatex
14#+latex_class: spbstu-report
15# #+latex_class_options: [draft]
16
17#+latex_header: \usepackage{enumitem}
18
19#+latex_header: \usepackage{float}
20#+latex_header: \usepackage[newfloat]{minted}
21#+latex_header: \usemintedstyle{bw}
22#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors}
23
24#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
25
26#+latex_header: \usepackage[paper=A4,DIV=14]{typearea}
27#+latex_header: \usepackage{pdflscape}
28#+latex_header: \usepackage{afterpage}
29
30#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
31#+latex_header: \setmainfont{Times New Roman}
32#+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff]
33
34#+latex_header: \usepackage[rounded]{syntax}
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls
new file mode 100644
index 0000000..7c8466e
--- /dev/null
+++ b/doc/spbstu-report.cls
@@ -0,0 +1,78 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18\RequirePackage{fancyhdr}
19
20\RequirePackage{etoolbox}
21\patchcmd{\maketitle}{\thispagestyle{plain}}{\thispagestyle{title}}{}{}
22
23\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
24\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}}
25\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}}
26\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}}
27\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}}
28\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
29\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
30\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
31\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
32\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}}
33\renewcommand{\maketitle}{
34 \begin{titlepage}
35 \begin{center}
36 \vspace{2cm}
37 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
38
39 \normalsize{\@university}
40
41 \vspace{0.5cm}
42 \normalsize{\@institute}
43
44 \normalsize{\@school}
45
46 \normalsize{Направление \@direction}
47
48 \vspace{2cm}
49 \LARGE{ОТЧЁТ}
50
51 \normalsize{\@reportof}
52
53 \large{\@subject}
54
55 \large{\textit{\@title}}
56 \end{center}
57
58 \vspace{2cm}
59 \small{
60 \begin{tabular}{lrrl}
61 \!\!\!Студент, & \hspace{0} & & \\
62 \!\!\!группы 5130201/20102 & \hspace{0} & \underline{\hspace{3cm}} & \@author \\\\
63 \!\!\!Преподаватель, & \hspace{0} & \\
64 \!\!\!\@reviewertitle & \hspace{0} & \underline{\hspace{3cm}} & \@reviewer \\\\
65 &&\hspace{5cm}
66 \end{tabular}
67 \begin{flushright}
68 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
69 \end{flushright}
70 }
71
72 \vspace*{\fill}
73 \begin{center}
74 \small{\@city, \@date}
75 \end{center}
76 \end{titlepage}
77 \setcounter{page}{2}
78}
diff --git a/lib/bnf-mode.el b/lib/bnf-mode.el
new file mode 100644
index 0000000..04b1afb
--- /dev/null
+++ b/lib/bnf-mode.el
@@ -0,0 +1,40 @@
1;;; bnf-mode.el --- simple major mode for BNF -*- lexical-binding: t; -*-
2
3;; Copyright (C) 2025 Michalec Martin
4
5;; Author: Michalec Martin <martin@michalec.dev>
6;; Keywords: convenience, faces, extensions
7
8;; This program is free software; you can redistribute it and/or modify
9;; it under the terms of the GNU General Public License as published by
10;; the Free Software Foundation, either version 3 of the License, or
11;; (at your option) any later version.
12
13;; This program is distributed in the hope that it will be useful,
14;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16;; GNU General Public License for more details.
17
18;; You should have received a copy of the GNU General Public License
19;; along with this program. If not, see <https://www.gnu.org/licenses/>.
20
21;;; Commentary:
22
23;; reference: http://xahlee.info/emacs/emacs/elisp_syntax_coloring.html
24
25;;; Code:
26
27(defvar-local bnf-mode-fontlock
28 '(("#.*" . 'font-lock-comment-face)
29 ("<EOL>\\|<EOF>" . 'font-lock-builtin-face)
30 ("::=\\||" . 'font-lock-operator-face)
31 ("\"[^\"]*\"\\|'[^']*'" . 'font-lock-string-face)
32 ("<[^>]+>" . 'font-lock-variable-name-face)))
33
34(define-derived-mode bnf-mode fundamental-mode "bnf"
35 "Major mode for editing bnf grammars."
36 (setq font-lock-defaults '(bnf-mode-fontlock)))
37
38(provide 'bnf-mode)
39
40;;; bnf-mode.el ends here
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 @@
1#include "bnf-lexeme.h"
2
3#define X(SYM, ...) [BNF_LEXEME_KIND_##SYM] = #SYM,
4const char *bnf_lexeme_kind_names[BNF_LEXEME_KIND_COUNT] = {
5 BNF_LEXEME_KINDS ()
6 [BNF_LEXEME_KIND_END_OF_LINE] = "END_OF_LINE",
7 [BNF_LEXEME_KIND_END_OF_FILE] = "END_OF_FILE",
8 [BNF_LEXEME_KIND_INVALID ] = "INVALID",
9};
10#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 @@
1#ifndef INCLUDED_BNF_LEXEME_H
2#define INCLUDED_BNF_LEXEME_H
3
4#include <stddef.h>
5#include <stdint.h>
6#include "utils.h"
7#include "string-view.h"
8
9#define BNF_LEXEME_KINDS() \
10 X (TERMINAL, "\"[^\"]*\"|'[^']*'") \
11 X (NONTERMINAL, "<[^>]*>" ) \
12 X (SYMBOL_ALTERNATIVE, "\\|" ) \
13 X (SYMBOL_IS_REPLACED_BY, "::=" ) \
14 X (COMMENT, "#[^\n]*" )
15
16#define X(SYM, ...) BNF_LEXEME_KIND_##SYM,
17enum bnf_lexeme_kind {
18 BNF_LEXEME_KINDS ()
19 BNF_LEXEME_KIND_END_OF_LINE,
20 BNF_LEXEME_KIND_END_OF_FILE,
21 BNF_LEXEME_KIND_INVALID,
22 BNF_LEXEME_KIND_COUNT,
23};
24#undef X
25
26#define BNF_LEXEME_REGEX_COUNT (BNF_LEXEME_KIND_COUNT - 3)
27
28struct bnf_lexeme {
29 struct string_view sv;
30 enum bnf_lexeme_kind kind;
31};
32
33extern const char *bnf_lexeme_kind_names[BNF_LEXEME_KIND_COUNT];
34
35#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 @@
1#include "bnf-lexer.h"
2#include <regex.h>
3#include <assert.h>
4#include <stdlib.h>
5#include <stdio.h>
6#include <ctype.h>
7#include "dynamic-array.h"
8
9#define X(SYM, REG, ...) [BNF_LEXEME_KIND_##SYM] = "^(" REG ")",
10static const char *lexeme_regex_strings[BNF_LEXEME_REGEX_COUNT] = { BNF_LEXEME_KINDS () };
11#undef X
12
13static regex_t lexeme_regexes[BNF_LEXEME_REGEX_COUNT];
14
15static void
16print_regex_error (const regex_t *comp, const char *regex, int errcode)
17{
18 size_t length = regerror (errcode, comp, NULL, 0);
19 char *buffer = malloc (length);
20 regerror (errcode, comp, buffer, length);
21 fprintf (stderr, "error: regcomp (\"%s\"): %s\n",
22 regex, buffer);
23 free (buffer);
24}
25
26static void __attribute__((constructor))
27compile_regexes (void)
28{
29 for (enum bnf_lexeme_kind kind = 0; kind < BNF_LEXEME_REGEX_COUNT; ++kind) {
30 regex_t *compiled = &lexeme_regexes[kind];
31 const char *pattern = lexeme_regex_strings[kind];
32 int errcode = regcomp (compiled, pattern, REG_EXTENDED);
33 if (errcode) {
34 print_regex_error (compiled, pattern, errcode);
35 exit (1);
36 }
37 }
38}
39
40struct bnf_lexer
41bnf_lexer_from_string_view (struct string_view sv, const char *filename)
42{
43 return (struct bnf_lexer) {
44 .sv = sv,
45 .cursor = sv.beg,
46 .filename = filename,
47 };
48}
49
50static void
51lexer_skip_whitespace (struct bnf_lexer *lexer)
52{
53 while (lexer->cursor < lexer->sv.end && (*lexer->cursor == ' ' ||
54 *lexer->cursor == '\t'))
55 lexer->cursor += 1;
56}
57
58struct bnf_lexeme
59bnf_lexer_next_lexeme (struct bnf_lexer *lexer)
60{
61 lexer_skip_whitespace (lexer);
62 struct bnf_lexeme lexeme = {
63 .sv.beg = lexer->cursor,
64 .kind = BNF_LEXEME_KIND_INVALID,
65 };
66
67 if (lexer->cursor >= lexer->sv.end) {
68 lexeme.kind = BNF_LEXEME_KIND_END_OF_FILE;
69 lexeme.sv.end = lexer->sv.end;
70 return lexeme;
71 }
72
73 if (*lexer->cursor == '\n') {
74 lexeme.kind = BNF_LEXEME_KIND_END_OF_LINE;
75 lexeme.sv.end = ++lexer->cursor;
76 return lexeme;
77 }
78
79 regmatch_t regmatch;
80 enum bnf_lexeme_kind longest_matching_lexeme_kind = BNF_LEXEME_KIND_INVALID;
81 int longest_matching_lexeme_kind_length = 0;
82 for (enum bnf_lexeme_kind kind = 0; kind < BNF_LEXEME_REGEX_COUNT; ++kind) {
83 if (regexec (&lexeme_regexes[kind], lexer->cursor, 1, &regmatch, 0)) continue;
84 if (regmatch.rm_eo <= longest_matching_lexeme_kind_length) continue;
85 longest_matching_lexeme_kind_length = regmatch.rm_eo;
86 longest_matching_lexeme_kind = kind;
87 }
88
89 if (longest_matching_lexeme_kind != BNF_LEXEME_KIND_INVALID) {
90 lexeme.kind = longest_matching_lexeme_kind;
91 lexeme.sv.end = lexer->cursor += longest_matching_lexeme_kind_length;
92
93 switch (lexeme.kind) {
94 case BNF_LEXEME_KIND_COMMENT: return bnf_lexer_next_lexeme (lexer);
95 default: return lexeme;
96 }
97 }
98
99 lexeme.sv.end = ++lexer->cursor;
100 return lexeme;
101}
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 @@
1#ifndef INCLUDED_BNF_LEXER_H
2#define INCLUDED_BNF_LEXER_H
3
4#include <stddef.h>
5#include "utils.h"
6#include "bnf-lexeme.h"
7
8struct bnf_lexer {
9 struct string_view sv;
10 const char *cursor;
11 const char *filename;
12};
13
14extern struct bnf_lexer bnf_lexer_from_string_view (struct string_view, const char *filename);
15extern struct bnf_lexer bnf_lexer_from_filename (const char *);
16extern struct bnf_lexeme bnf_lexer_next_lexeme (struct bnf_lexer *);
17
18#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 @@
1#include <stdarg.h>
2#include "bnf-parser.h"
3#include "dynamic-array.h"
4
5void
6print_error (struct bnf_lexer *lexer, const char *point,
7 const char *template, ...)
8{
9 int row = 1;
10 int col = 0;
11
12 for (const char *head = lexer->sv.beg; head < point; ++head) {
13 col += 1;
14 if (*head == '\n') {
15 row += 1;
16 col = 0;
17 }
18 };
19
20 fprintf (stderr, "%s:%d:%d: error: ", lexer->filename, row, col);
21
22 va_list ap;
23 va_start (ap, template);
24 vfprintf (stderr, template, ap);
25 va_end (ap);
26
27 putc ('\n', stderr);
28}
29
30bool
31is_bnf_lexeme_valid (struct bnf_lexeme lexeme)
32{
33 return lexeme.kind != BNF_LEXEME_KIND_INVALID;
34}
35
36bool
37bnf_parse_lexeme (struct bnf_lexer *lexer, enum bnf_lexeme_kind kind)
38{
39 const char *checkpoint = lexer->cursor;
40 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
41
42 if (lexeme.kind != kind) goto revert;
43
44 return true;
45
46revert:
47 lexer->cursor = checkpoint;
48 return false;
49}
50
51struct bnf_lexeme
52bnf_parse_nonterminal (struct bnf_lexer *lexer)
53{
54 const char *checkpoint = lexer->cursor;
55 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
56 if (lexeme.kind == BNF_LEXEME_KIND_NONTERMINAL)
57 return lexeme;
58
59revert:
60 lexer->cursor = checkpoint;
61 return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID };
62}
63
64struct bnf_lexeme
65bnf_parse_terminal (struct bnf_lexer *lexer)
66{
67 const char *checkpoint = lexer->cursor;
68
69 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
70 if (lexeme.kind == BNF_LEXEME_KIND_TERMINAL)
71 return lexeme;
72
73revert:
74 lexer->cursor = checkpoint;
75 return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID };
76}
77
78bool
79is_bnf_sequence_valid (struct bnf_sequence sequence)
80{
81 return sequence.term_count != 0;
82}
83
84struct bnf_sequence
85bnf_parse_sequence (struct bnf_lexer *lexer)
86{
87 struct bnf_sequence sequence = {0};
88 const char *checkpoint = lexer->cursor;
89
90 for (;;) {
91 struct bnf_lexeme lexeme = bnf_parse_nonterminal (lexer);
92 if (!is_bnf_lexeme_valid (lexeme))
93 lexeme = bnf_parse_terminal (lexer);
94 if (!is_bnf_lexeme_valid (lexeme))
95 break;
96
97 DYNAMIC_ARRAY_APPEND (sequence, lexeme);
98 } if (!is_bnf_sequence_valid (sequence)) goto revert;
99
100 if (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_ALTERNATIVE) ||
101 bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE))
102 return sequence;
103
104revert:
105 DYNAMIC_ARRAY_FREE (sequence);
106 lexer->cursor = checkpoint;
107 return (struct bnf_sequence) {0};
108}
109
110bool
111is_bnf_rule_valid (struct bnf_rule rule)
112{
113 return rule.is_replaced_by.sequence_count != 0;
114}
115
116struct bnf_rule
117bnf_parse_rule (struct bnf_lexer *lexer)
118{
119 struct bnf_rule rule = {0};
120 const char *checkpoint = lexer->cursor;
121
122 rule.name = bnf_parse_nonterminal (lexer);
123 if (!is_bnf_lexeme_valid (rule.name))
124 goto revert;
125
126 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_IS_REPLACED_BY))
127 goto revert;
128
129 for (;;) {
130 struct bnf_sequence sequence = bnf_parse_sequence (lexer);
131 if (!is_bnf_sequence_valid (sequence)) break;
132 DYNAMIC_ARRAY_APPEND (rule.is_replaced_by, sequence);
133 } if (is_bnf_rule_valid (rule)) return rule;
134
135revert:
136 DYNAMIC_ARRAY_FREE (rule.is_replaced_by);
137 lexer->cursor = checkpoint;
138 return (struct bnf_rule) {0};
139}
140
141struct bnf_syntax
142bnf_parse_syntax (struct bnf_lexer *lexer)
143{
144 struct bnf_syntax syntax = {0};
145
146 for (;;) {
147 while (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE));
148 struct bnf_rule rule = bnf_parse_rule (lexer);
149 if (!is_bnf_rule_valid (rule)) {
150 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_FILE)) {
151 print_error (lexer, lexer->cursor, "unable to parse rule");
152 }
153 break;
154 }
155
156 DYNAMIC_ARRAY_APPEND (syntax, rule);
157 }
158
159 return syntax;
160}
161
162bool
163bnf_check_syntax (struct bnf_lexer *lexer, struct bnf_syntax syntax)
164{
165 bool no_errors = true;
166 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
167 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
168 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
169 if (term->kind != BNF_LEXEME_KIND_NONTERMINAL) continue;
170 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) continue;
171 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) continue;
172
173 bool rule_found = false;
174 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
175 if (!STRING_VIEW_EQUALS (rule->name.sv, term->sv)) continue;
176 rule_found = true;
177 break;
178 }
179
180 if (!rule_found) {
181 no_errors = false;
182 print_error (lexer, term->sv.beg,
183 "rule not found: %.*s",
184 (int) STRING_VIEW_LEN (term->sv), term->sv.beg);
185 }
186 }
187 }
188 }
189
190 return no_errors;
191}
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 @@
1#ifndef INCLUDED_BNF_PARSER_H
2#define INCLUDED_BNF_PARSER_H
3
4#include <stdint.h>
5#include <stdbool.h>
6#include "bnf-lexer.h"
7
8struct bnf_sequence {
9 union { struct bnf_lexeme *items, *terms; };
10 union { uint32_t count, term_count; };
11 uint32_t capacity;
12};
13
14struct bnf_rule {
15 struct bnf_lexeme name;
16 struct {
17 union { struct bnf_sequence *items, *sequences; };
18 union { uint32_t count, sequence_count; };
19 uint32_t capacity;
20 } is_replaced_by;
21};
22
23struct bnf_syntax {
24 union { struct bnf_rule *items, *rules; };
25 union { uint32_t count, rule_count; };
26 uint32_t capacity;
27};
28
29// struct term_table {
30// union { struct bnf_lexeme *items, *terms; };
31// union { uint32_t count, term_count; };
32// uint32_t capacity;
33// };
34
35struct bnf_parser {
36 struct bnf_lexer lexer;
37};
38
39bool is_bnf_lexeme_valid (struct bnf_lexeme);
40bool is_bnf_sequence_valid (struct bnf_sequence);
41bool is_bnf_rule_valid (struct bnf_rule);
42
43bool bnf_check_syntax (struct bnf_lexer *, struct bnf_syntax);
44bool bnf_parse_lexeme (struct bnf_lexer *, enum bnf_lexeme_kind);
45struct bnf_lexeme bnf_parse_nonterminal (struct bnf_lexer *);
46struct bnf_lexeme bnf_parse_terminal (struct bnf_lexer *);
47struct bnf_sequence bnf_parse_sequence (struct bnf_lexer *);
48struct bnf_rule bnf_parse_rule (struct bnf_lexer *);
49struct bnf_syntax bnf_parse_syntax (struct bnf_lexer *);
50
51#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 @@
1#include "bnf-preprocessor.h"
2#include "string-builder.h"
3#include <errno.h>
4#include <fcntl.h>
5#include <unistd.h>
6#include <sys/stat.h>
7#include <sys/mman.h>
8
9struct preprocessor {
10 struct {
11 struct open_file {
12 struct string_view sv;
13 const char *filename;
14 const char *cursor;
15 } *items;
16 uint32_t count;
17 uint32_t capacity;
18 } open_files;
19 struct string_builder sb;
20};
21
22static const char import_cstr[] = "import";
23static struct string_view import_sv = {
24 .beg = import_cstr,
25 .end = import_cstr + sizeof (import_cstr) - 1,
26};
27
28
29static void
30preprocess_file (struct string_builder *sb, const char *filename)
31{
32 struct string_view file_contents;
33 const char *cursor;
34
35 int fd = open (filename, O_RDONLY);
36 if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename);
37
38 struct stat st;
39 fstat (fd, &st);
40 cursor = file_contents.beg =
41 mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
42 close (fd);
43 file_contents.end = file_contents.beg + st.st_size;
44 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, STRING_VIEW_LEN (file_contents));
45
46 do {
47 if (*cursor == '!') {
48 cursor += 1;
49 while (*cursor == ' ') cursor += 1;
50 if ()
51 while (*cursor != '\n') cursor += 1;
52 cursor += 1;
53 preprocess_file (sb, import_filename);
54 continue;
55 }
56
57 DYNAMIC_ARRAY_APPEND_FAST (*sb, *cursor++);
58 } while (1);
59
60 munmap ((char *) file_contents.beg, STRING_VIEW_LEN (file_contents));
61}
62
63struct string_view
64bnf_preprocess_file (const char *filename)
65{
66 struct string_builder sb = {0};
67
68 preprocess_file (&sb, filename);
69
70 struct string_view output = {
71 .beg = sb.string,
72 .end = sb.string + sb.count,
73 };
74
75 return output;
76}
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 @@
1#ifndef INCLUDED_BNF_PREPROCESSOR_H
2#define INCLUDED_BNF_PREPROCESSOR_H
3
4#include "string-view.h"
5
6struct string_view bnf_preprocess_file (const char *filename);
7
8#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 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DA, COUNT) \
11 ({ \
12 if ((DA).count + (COUNT) > (DA).capacity) { \
13 if ((DA).capacity == 0) \
14 (DA).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DA).count + (COUNT) > (DA).capacity) \
16 (DA).capacity *= 2; \
17 (DA).items = REALLOC((DA).items, \
18 (DA).capacity * \
19 sizeof (*(DA).items)); \
20 ASSERT((DA).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DA) \
25 ({ \
26 (DA).capacity = (DA).count; \
27 (DA).items = REALLOC((DA).items, \
28 (DA).capacity * \
29 sizeof (*(DA).items)); \
30 ASSERT((DA).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DA, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), 1); \
37 (DA).items[(DA).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_FAST(DA, ITEM) \
41 (DA).items[(DA).count++] = (ITEM);
42
43#define DYNAMIC_ARRAY_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \
44 ({ \
45 DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), (NEW_ITEMS_COUNT)); \
46 memcpy ((DA).items + (DA).count, (NEW_ITEMS), \
47 (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \
48 (DA).count += (NEW_ITEMS_COUNT); \
49 })
50
51#define DYNAMIC_ARRAY_APPEND_DYNAMIC_ARRAY(TO, FROM) \
52 DYNAMIC_ARRAY_APPEND_MANY ((TO), \
53 (FROM).items, \
54 (FROM).count)
55
56#define DYNAMIC_ARRAY_LAST(DA) \
57 (DA).items[(DA).count - 1]
58
59#define DYNAMIC_ARRAY_POP(DA) \
60 (DA).items[--(DA).count]
61
62#define DYNAMIC_ARRAY_RESET(DA) ({ (DA).count = 0; })
63
64#define DYNAMIC_ARRAY_FREE(DA) FREE((DA).items)
65
66// NOTE(cmmm): resizing will invalidate!
67#define DYNAMIC_ARRAY_FOREACH(ITEM, DA) for ( \
68 typeof ((DA).items) ITEM = (DA).items; \
69 ITEM < (DA).items + (DA).count; ++ITEM)
70
71#define DYNAMIC_ARRAY_FOREACH_REVERSED(ITEM, DA) for ( \
72 typeof ((DA).items) ITEM = &DYNAMIC_ARRAY_LAST (DA); \
73 ITEM >= (DA).items; --ITEM)
74
75#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 @@
1#include <stdlib.h>
2#include <stdio.h>
3
4int
5main (int argc, char *argv[])
6{
7 FILE *fp = stdout;
8
9 verb {
10 imperfective {
11 indicative {
12 present {
13 sg {
14 p1;
15 p2;
16 p3;
17 };
18 pl {
19 p1;
20 p2;
21 p3;
22 };
23 };
24 past {
25 masculine {
26 sg {
27 p1;
28 p2;
29 p3;
30 };
31 pl {
32 p1 {
33 animate;
34 inanimate;
35 };
36 p2 {
37 animate;
38 inanimate;
39 };
40 p3 {
41 animate;
42 inanimate;
43 };
44 };
45 };
46 feminine {
47 sg {
48 p1;
49 p2;
50 p3;
51 };
52 pl {
53 p1;
54 p2;
55 p3;
56 };
57 };
58 neuter {
59 sg {
60 p1;
61 p2;
62 p3;
63 };
64 pl {
65 p1;
66 p2;
67 p3;
68 };
69 };
70 };
71 future {
72 sg {
73 p1;
74 p2;
75 p3;
76 };
77 pl {
78 p1;
79 p2;
80 p3;
81 };
82 };
83 };
84 conditional {
85 present {
86 masculine {
87 sg {
88 p1;
89 p2;
90 p3;
91 };
92 pl {
93 p1 {
94 animate;
95 inanimate;
96 };
97 p2 {
98 animate;
99 inanimate;
100 };
101 p3 {
102 animate;
103 inanimate;
104 };
105 };
106 };
107 feminine {
108 sg {
109 p1;
110 p2;
111 p3;
112 };
113 pl {
114 p1;
115 p2;
116 p3;
117 };
118 };
119 neuter {
120 sg {
121 p1;
122 p2;
123 p3;
124 };
125 pl {
126 p1;
127 p2;
128 p3;
129 };
130 };
131 };
132 past {
133 masculine {
134 sg {
135 p1;
136 p2;
137 p3;
138 };
139 pl {
140 p1 {
141 animate;
142 inanimate;
143 };
144 p2 {
145 animate;
146 inanimate;
147 };
148 p3 {
149 animate;
150 inanimate;
151 };
152 };
153 };
154 feminine {
155 sg {
156 p1;
157 p2;
158 p3;
159 };
160 pl {
161 p1;
162 p2;
163 p3;
164 };
165 };
166 neuter {
167 sg {
168 p1;
169 p2;
170 p3;
171 };
172 pl {
173 p1;
174 p2;
175 p3;
176 };
177 };
178 };
179 };
180 imperative {
181 sg {
182 p2;
183 };
184 pl {
185 p1;
186 p2;
187 };
188 };
189 participle {
190 sg {
191 masculine;
192 feminine;
193 neuter;
194 };
195 pl {
196 masculine {
197 animate;
198 inanimate;
199 };
200 feminine;
201 neuter;
202 };
203 };
204 };
205 perfective {
206 indicative {
207 present {
208 sg {
209 p1;
210 p2;
211 p3;
212 };
213 pl {
214 p1;
215 p2;
216 p3;
217 };
218 };
219 past {
220 masculine {
221 sg {
222 p1;
223 p2;
224 p3;
225 };
226 pl {
227 p1 {
228 animate;
229 inanimate;
230 };
231 p2 {
232 animate;
233 inanimate;
234 };
235 p3 {
236 animate;
237 inanimate;
238 };
239 };
240 };
241 feminine {
242 sg {
243 p1;
244 p2;
245 p3;
246 };
247 pl {
248 p1;
249 p2;
250 p3;
251 };
252 };
253 neuter {
254 sg {
255 p1;
256 p2;
257 p3;
258 };
259 pl {
260 p1;
261 p2;
262 p3;
263 };
264 };
265 };
266 };
267 conditional {
268 present {
269 masculine {
270 sg {
271 p1;
272 p2;
273 p3;
274 };
275 pl {
276 p1 {
277 animate;
278 inanimate;
279 };
280 p2 {
281 animate;
282 inanimate;
283 };
284 p3 {
285 animate;
286 inanimate;
287 };
288 };
289 };
290 feminine {
291 sg {
292 p1;
293 p2;
294 p3;
295 };
296 pl {
297 p1;
298 p2;
299 p3;
300 };
301 };
302 neuter {
303 sg {
304 p1;
305 p2;
306 p3;
307 };
308 pl {
309 p1;
310 p2;
311 p3;
312 };
313 };
314 };
315 past {
316 masculine {
317 sg {
318 p1;
319 p2;
320 p3;
321 };
322 pl {
323 p1 {
324 animate;
325 inanimate;
326 };
327 p2 {
328 animate;
329 inanimate;
330 };
331 p3 {
332 animate;
333 inanimate;
334 };
335 };
336 };
337 feminine {
338 sg {
339 p1;
340 p2;
341 p3;
342 };
343 pl {
344 p1;
345 p2;
346 p3;
347 };
348 };
349 neuter {
350 sg {
351 p1;
352 p2;
353 p3;
354 };
355 pl {
356 p1;
357 p2;
358 p3;
359 };
360 };
361 };
362 };
363 imperative {
364 sg {
365 p2;
366 };
367 pl {
368 p1;
369 p2;
370 };
371 };
372 participle {
373 sg {
374 masculine;
375 feminine;
376 neuter;
377 };
378 pl {
379 masculine {
380 animate;
381 inanimate;
382 };
383 feminine;
384 neuter;
385 };
386 };
387 };
388 };
389
390 return EXIT_SUCCESS;
391}
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}
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 @@
1# -*- BNF -*-
2# resources:
3# - https://www.naturalminevita.sk/portal/slovencina/pridavne-mena-vzory-a-sklonovanie-pridavnych-mien/
4
5<adjectives-sg-masculine-nominative> ::= <adjective-sg-masculine-nominative> " a " <adjective-sg-masculine-nominative> | <adjective-sg-masculine-nominative> ", " <adjectives-sg-masculine-nominative>
6<adjectives-sg-masculine-genitive> ::= <adjective-sg-masculine-genitive> " a " <adjective-sg-masculine-genitive> | <adjective-sg-masculine-genitive> ", " <adjectives-sg-masculine-genitive>
7<adjectives-sg-masculine-dative> ::= <adjective-sg-masculine-dative> " a " <adjective-sg-masculine-dative> | <adjective-sg-masculine-dative> ", " <adjectives-sg-masculine-dative>
8<adjectives-sg-masculine-accusative> ::= <adjective-sg-masculine-accusative> " a " <adjective-sg-masculine-accusative> | <adjective-sg-masculine-accusative> ", " <adjectives-sg-masculine-accusative>
9<adjectives-sg-masculine-locative> ::= <adjective-sg-masculine-locative> " a " <adjective-sg-masculine-locative> | <adjective-sg-masculine-locative> ", " <adjectives-sg-masculine-locative>
10<adjectives-sg-masculine-instrumental> ::= <adjective-sg-masculine-instrumental> " a " <adjective-sg-masculine-instrumental> | <adjective-sg-masculine-instrumental> ", " <adjectives-sg-masculine-instrumental>
11<adjectives-sg-feminine-nominative> ::= <adjective-sg-feminine-nominative> " a " <adjective-sg-feminine-nominative> | <adjective-sg-feminine-nominative> ", " <adjectives-sg-feminine-nominative>
12<adjectives-sg-feminine-genitive> ::= <adjective-sg-feminine-genitive> " a " <adjective-sg-feminine-genitive> | <adjective-sg-feminine-genitive> ", " <adjectives-sg-feminine-genitive>
13<adjectives-sg-feminine-dative> ::= <adjective-sg-feminine-dative> " a " <adjective-sg-feminine-dative> | <adjective-sg-feminine-dative> ", " <adjectives-sg-feminine-dative>
14<adjectives-sg-feminine-accusative> ::= <adjective-sg-feminine-accusative> " a " <adjective-sg-feminine-accusative> | <adjective-sg-feminine-accusative> ", " <adjectives-sg-feminine-accusative>
15<adjectives-sg-feminine-locative> ::= <adjective-sg-feminine-locative> " a " <adjective-sg-feminine-locative> | <adjective-sg-feminine-locative> ", " <adjectives-sg-feminine-locative>
16<adjectives-sg-feminine-instrumental> ::= <adjective-sg-feminine-instrumental> " a " <adjective-sg-feminine-instrumental> | <adjective-sg-feminine-instrumental> ", " <adjectives-sg-feminine-instrumental>
17<adjectives-sg-neuter-nominative> ::= <adjective-sg-neuter-nominative> " a " <adjective-sg-neuter-nominative> | <adjective-sg-neuter-nominative> ", " <adjectives-sg-neuter-nominative>
18<adjectives-sg-neuter-genitive> ::= <adjective-sg-neuter-genitive> " a " <adjective-sg-neuter-genitive> | <adjective-sg-neuter-genitive> ", " <adjectives-sg-neuter-genitive>
19<adjectives-sg-neuter-dative> ::= <adjective-sg-neuter-dative> " a " <adjective-sg-neuter-dative> | <adjective-sg-neuter-dative> ", " <adjectives-sg-neuter-dative>
20<adjectives-sg-neuter-accusative> ::= <adjective-sg-neuter-accusative> " a " <adjective-sg-neuter-accusative> | <adjective-sg-neuter-accusative> ", " <adjectives-sg-neuter-accusative>
21<adjectives-sg-neuter-locative> ::= <adjective-sg-neuter-locative> " a " <adjective-sg-neuter-locative> | <adjective-sg-neuter-locative> ", " <adjectives-sg-neuter-locative>
22<adjectives-sg-neuter-instrumental> ::= <adjective-sg-neuter-instrumental> " a " <adjective-sg-neuter-instrumental> | <adjective-sg-neuter-instrumental> ", " <adjectives-sg-neuter-instrumental>
23<adjectives-pl-masculine-nominative> ::= <adjective-pl-masculine-nominative> " a " <adjective-pl-masculine-nominative> | <adjective-pl-masculine-nominative> ", " <adjectives-pl-masculine-nominative>
24<adjectives-pl-masculine-genitive> ::= <adjective-pl-masculine-genitive> " a " <adjective-pl-masculine-genitive> | <adjective-pl-masculine-genitive> ", " <adjectives-pl-masculine-genitive>
25<adjectives-pl-masculine-dative> ::= <adjective-pl-masculine-dative> " a " <adjective-pl-masculine-dative> | <adjective-pl-masculine-dative> ", " <adjectives-pl-masculine-dative>
26<adjectives-pl-masculine-accusative> ::= <adjective-pl-masculine-accusative> " a " <adjective-pl-masculine-accusative> | <adjective-pl-masculine-accusative> ", " <adjectives-pl-masculine-accusative>
27<adjectives-pl-masculine-locative> ::= <adjective-pl-masculine-locative> " a " <adjective-pl-masculine-locative> | <adjective-pl-masculine-locative> ", " <adjectives-pl-masculine-locative>
28<adjectives-pl-masculine-instrumental> ::= <adjective-pl-masculine-instrumental> " a " <adjective-pl-masculine-instrumental> | <adjective-pl-masculine-instrumental> ", " <adjectives-pl-masculine-instrumental>
29<adjectives-pl-other-nominative> ::= <adjective-pl-other-nominative> " a " <adjective-pl-other-nominative> | <adjective-pl-other-nominative> ", " <adjectives-pl-other-nominative>
30<adjectives-pl-other-genitive> ::= <adjective-pl-other-genitive> " a " <adjective-pl-other-genitive> | <adjective-pl-other-genitive> ", " <adjectives-pl-other-genitive>
31<adjectives-pl-other-dative> ::= <adjective-pl-other-dative> " a " <adjective-pl-other-dative> | <adjective-pl-other-dative> ", " <adjectives-pl-other-dative>
32<adjectives-pl-other-accusative> ::= <adjective-pl-other-accusative> " a " <adjective-pl-other-accusative> | <adjective-pl-other-accusative> ", " <adjectives-pl-other-accusative>
33<adjectives-pl-other-locative> ::= <adjective-pl-other-locative> " a " <adjective-pl-other-locative> | <adjective-pl-other-locative> ", " <adjectives-pl-other-locative>
34<adjectives-pl-other-instrumental> ::= <adjective-pl-other-instrumental> " a " <adjective-pl-other-instrumental> | <adjective-pl-other-instrumental> ", " <adjectives-pl-other-instrumental>
35
36<adjective-sg-masculine-nominative> ::= <adjective-pekny-sg-masculine-nominative>
37<adjective-sg-masculine-genitive> ::= <adjective-pekny-sg-masculine-genitive>
38<adjective-sg-masculine-dative> ::= <adjective-pekny-sg-masculine-dative>
39<adjective-sg-masculine-accusative> ::= <adjective-pekny-sg-masculine-accusative>
40<adjective-sg-masculine-locative> ::= <adjective-pekny-sg-masculine-locative>
41<adjective-sg-masculine-instrumental> ::= <adjective-pekny-sg-masculine-instrumental>
42<adjective-sg-feminine-nominative> ::= <adjective-pekny-sg-feminine-nominative>
43<adjective-sg-feminine-genitive> ::= <adjective-pekny-sg-feminine-genitive>
44<adjective-sg-feminine-dative> ::= <adjective-pekny-sg-feminine-dative>
45<adjective-sg-feminine-accusative> ::= <adjective-pekny-sg-feminine-accusative>
46<adjective-sg-feminine-locative> ::= <adjective-pekny-sg-feminine-locative>
47<adjective-sg-feminine-instrumental> ::= <adjective-pekny-sg-feminine-instrumental>
48<adjective-sg-neuter-nominative> ::= <adjective-pekny-sg-neuter-nominative>
49<adjective-sg-neuter-genitive> ::= <adjective-pekny-sg-neuter-genitive>
50<adjective-sg-neuter-dative> ::= <adjective-pekny-sg-neuter-dative>
51<adjective-sg-neuter-accusative> ::= <adjective-pekny-sg-neuter-accusative>
52<adjective-sg-neuter-locative> ::= <adjective-pekny-sg-neuter-locative>
53<adjective-sg-neuter-instrumental> ::= <adjective-pekny-sg-neuter-instrumental>
54<adjective-pl-masculine-nominative> ::= <adjective-pekny-pl-masculine-nominative>
55<adjective-pl-masculine-genitive> ::= <adjective-pekny-pl-masculine-genitive>
56<adjective-pl-masculine-dative> ::= <adjective-pekny-pl-masculine-dative>
57<adjective-pl-masculine-accusative> ::= <adjective-pekny-pl-masculine-accusative>
58<adjective-pl-masculine-locative> ::= <adjective-pekny-pl-masculine-locative>
59<adjective-pl-masculine-instrumental> ::= <adjective-pekny-pl-masculine-instrumental>
60<adjective-pl-other-nominative> ::= <adjective-pekny-pl-other-nominative>
61<adjective-pl-other-genitive> ::= <adjective-pekny-pl-other-genitive>
62<adjective-pl-other-dative> ::= <adjective-pekny-pl-other-dative>
63<adjective-pl-other-accusative> ::= <adjective-pekny-pl-other-accusative>
64<adjective-pl-other-locative> ::= <adjective-pekny-pl-other-locative>
65<adjective-pl-other-instrumental> ::= <adjective-pekny-pl-other-instrumental>
66
67<adjective-pekny-sg-masculine-nominative> ::= <adjective-stem-pekny> "ý"
68<adjective-pekny-sg-masculine-genitive> ::= <adjective-stem-pekny> "ého"
69<adjective-pekny-sg-masculine-dative> ::= <adjective-stem-pekny> "émy"
70<adjective-pekny-sg-masculine-accusative> ::= <adjective-stem-pekny> "ého"
71<adjective-pekny-sg-masculine-locative> ::= <adjective-stem-pekny> "om"
72<adjective-pekny-sg-masculine-instrumental> ::= <adjective-stem-pekny> "ým"
73<adjective-pekny-sg-feminine-nominative> ::= <adjective-stem-pekny> "á"
74<adjective-pekny-sg-feminine-genitive> ::= <adjective-stem-pekny> "ej"
75<adjective-pekny-sg-feminine-dative> ::= <adjective-stem-pekny> "ej"
76<adjective-pekny-sg-feminine-accusative> ::= <adjective-stem-pekny> "ú"
77<adjective-pekny-sg-feminine-locative> ::= <adjective-stem-pekny> "ej"
78<adjective-pekny-sg-feminine-instrumental> ::= <adjective-stem-pekny> "ou"
79<adjective-pekny-sg-neuter-nominative> ::= <adjective-stem-pekny> "é"
80<adjective-pekny-sg-neuter-genitive> ::= <adjective-stem-pekny> "ého"
81<adjective-pekny-sg-neuter-dative> ::= <adjective-stem-pekny> "émy"
82<adjective-pekny-sg-neuter-accusative> ::= <adjective-stem-pekny> "é"
83<adjective-pekny-sg-neuter-locative> ::= <adjective-stem-pekny> "om"
84<adjective-pekny-sg-neuter-instrumental> ::= <adjective-stem-pekny> "ým"
85<adjective-pekny-pl-masculine-nominative> ::= <adjective-stem-pekny> "í"
86<adjective-pekny-pl-masculine-genitive> ::= <adjective-stem-pekny> "ých"
87<adjective-pekny-pl-masculine-dative> ::= <adjective-stem-pekny> "ým"
88<adjective-pekny-pl-masculine-accusative> ::= <adjective-stem-pekny> "ých"
89<adjective-pekny-pl-masculine-locative> ::= <adjective-stem-pekny> "ých"
90<adjective-pekny-pl-masculine-instrumental> ::= <adjective-stem-pekny> "ými"
91<adjective-pekny-pl-other-nominative> ::= <adjective-stem-pekny> "é"
92<adjective-pekny-pl-other-genitive> ::= <adjective-stem-pekny> "ých"
93<adjective-pekny-pl-other-dative> ::= <adjective-stem-pekny> "ým"
94<adjective-pekny-pl-other-accusative> ::= <adjective-stem-pekny> "é"
95<adjective-pekny-pl-other-locative> ::= <adjective-stem-pekny> "ých"
96<adjective-pekny-pl-other-instrumental> ::= <adjective-stem-pekny> "ými"
97<adjective-stem-pekny> ::= "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 @@
1# -*- BNF -*-
2# resources:
3# - 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 @@
1# slovak-noun.bnf -*- BNF -*-
2# resources:
3# - https://www.naturalminevita.sk/portal/slovencina/podstatne-mena/
4
5<noun> ::= <noun-masculine> | <noun-feminine> | <noun-neuter>
6<noun-sg> ::= <noun-masculine-sg> | <noun-feminine-sg> | <noun-neuter-sg>
7<noun-pl> ::= <noun-masculine-pl> | <noun-feminine-pl> | <noun-neuter-pl>
8
9<noun-sg-nominative> ::= <noun-masculine-sg-nominative> | <noun-feminine-sg-nominative> | <noun-neuter-sg-nominative>
10<noun-pl-nominative> ::= <noun-masculine-pl-nominative> | <noun-feminine-pl-nominative> | <noun-neuter-pl-nominative>
11
12<noun-masculine> ::= <noun-masculine-sg> | <noun-masculine-pl>
13<noun-masculine-sg> ::= <noun-masculine-sg-nominative> | <noun-masculine-sg-genitive> | <noun-masculine-sg-dative> | <noun-masculine-sg-accusative> | <noun-masculine-sg-locative> | <noun-masculine-sg-instrumental>
14<noun-masculine-pl> ::= <noun-masculine-pl-nominative> | <noun-masculine-pl-genitive> | <noun-masculine-pl-dative> | <noun-masculine-pl-accusative> | <noun-masculine-pl-locative> | <noun-masculine-pl-instrumental>
15<noun-masculine-sg-nominative> ::= <noun-chlap-sg-nominative> | <noun-hrdina-sg-nominative> | <noun-dub-sg-nominative> | <noun-stroj-sg-nominative> | <noun-kuli-sg-nominative>
16<noun-masculine-sg-genitive> ::= <noun-chlap-sg-genitive> | <noun-hrdina-sg-genitive> | <noun-dub-sg-genitive> | <noun-stroj-sg-genitive> | <noun-kuli-sg-genitive>
17<noun-masculine-sg-dative> ::= <noun-chlap-sg-dative> | <noun-hrdina-sg-dative> | <noun-dub-sg-dative> | <noun-stroj-sg-dative> | <noun-kuli-sg-dative>
18<noun-masculine-sg-accusative> ::= <noun-chlap-sg-accusative> | <noun-hrdina-sg-accusative> | <noun-dub-sg-accusative> | <noun-stroj-sg-accusative> | <noun-kuli-sg-accusative>
19<noun-masculine-sg-locative> ::= <noun-chlap-sg-locative> | <noun-hrdina-sg-locative> | <noun-dub-sg-locative> | <noun-stroj-sg-locative> | <noun-kuli-sg-locative>
20<noun-masculine-sg-instrumental> ::= <noun-chlap-sg-instrumental> | <noun-hrdina-sg-instrumental> | <noun-dub-sg-instrumental> | <noun-stroj-sg-instrumental> | <noun-kuli-sg-instrumental>
21<noun-masculine-pl-nominative> ::= <noun-chlap-pl-nominative> | <noun-hrdina-pl-nominative> | <noun-dub-pl-nominative> | <noun-stroj-pl-nominative> | <noun-kuli-pl-nominative>
22<noun-masculine-pl-genitive> ::= <noun-chlap-pl-genitive> | <noun-hrdina-pl-genitive> | <noun-dub-pl-genitive> | <noun-stroj-pl-genitive> | <noun-kuli-pl-genitive>
23<noun-masculine-pl-dative> ::= <noun-chlap-pl-dative> | <noun-hrdina-pl-dative> | <noun-dub-pl-dative> | <noun-stroj-pl-dative> | <noun-kuli-pl-dative>
24<noun-masculine-pl-accusative> ::= <noun-chlap-pl-accusative> | <noun-hrdina-pl-accusative> | <noun-dub-pl-accusative> | <noun-stroj-pl-accusative> | <noun-kuli-pl-accusative>
25<noun-masculine-pl-locative> ::= <noun-chlap-pl-locative> | <noun-hrdina-pl-locative> | <noun-dub-pl-locative> | <noun-stroj-pl-locative> | <noun-kuli-pl-locative>
26<noun-masculine-pl-instrumental> ::= <noun-chlap-pl-instrumental> | <noun-hrdina-pl-instrumental> | <noun-dub-pl-instrumental> | <noun-stroj-pl-instrumental> | <noun-kuli-pl-instrumental>
27
28<noun-chlap> ::= <noun-chlap-sg> | <noun-chlap-pl>
29<noun-chlap-sg> ::= <noun-chlap-sg-nominative> | <noun-chlap-sg-genitive> | <noun-chlap-sg-dative> | <noun-chlap-sg-accusative> | <noun-chlap-sg-locative> | <noun-chlap-sg-instrumental>
30<noun-chlap-pl> ::= <noun-chlap-pl-nominative> | <noun-chlap-pl-genitive> | <noun-chlap-pl-dative> | <noun-chlap-pl-accusative> | <noun-chlap-pl-locative> | <noun-chlap-pl-instrumental>
31<noun-chlap-sg-nominative> ::= <noun-stem-chlap-i> | <noun-stem-chlap-ia> | <noun-stem-chlap-ovia> "o"
32<noun-chlap-sg-genitive> ::= <noun-stem-chlap> "a"
33<noun-chlap-sg-dative> ::= <noun-stem-chlap> "ovi"
34<noun-chlap-sg-accusative> ::= <noun-stem-chlap> "a"
35<noun-chlap-sg-locative> ::= <noun-stem-chlap> "ovi"
36<noun-chlap-sg-instrumental> ::= <noun-stem-chlap> "om"
37<noun-chlap-pl-nominative> ::= <noun-stem-chlap-i> "i" | <noun-stem-chlap-ia> "ia" | <noun-stem-chlap-ovia> "ovia"
38<noun-chlap-pl-genitive> ::= <noun-stem-chlap> "ov"
39<noun-chlap-pl-dative> ::= <noun-stem-chlap> "om"
40<noun-chlap-pl-accusative> ::= <noun-stem-chlap> "ov"
41<noun-chlap-pl-locative> ::= <noun-stem-chlap> "och"
42<noun-chlap-pl-instrumental> ::= <noun-stem-chlap> "mi"
43<noun-stem-chlap> ::= <noun-stem-chlap-i> | <noun-stem-chlap-ia> | <noun-stem-chlap-ovia>
44<noun-stem-chlap-i> ::= "chlap" | "rytier" | # "chlapec" | "otec" | "pes"
45<noun-stem-chlap-ia> ::= "brat" # | "učiteľ"
46<noun-stem-chlap-ovia> ::= "uj" | "ded" | "Pal" | "strýk" # | "syn"
47
48<noun-hrdina> ::= <noun-hrdina-sg> | <noun-hrdina-pl>
49<noun-hrdina-sg> ::= <noun-hrdina-sg-nominative> | <noun-hrdina-sg-genitive> | <noun-hrdina-sg-dative> | <noun-hrdina-sg-accusative> | <noun-hrdina-sg-locative> | <noun-hrdina-sg-instrumental>
50<noun-hrdina-pl> ::= <noun-hrdina-pl-nominative> | <noun-hrdina-pl-genitive> | <noun-hrdina-pl-dative> | <noun-hrdina-pl-accusative> | <noun-hrdina-pl-locative> | <noun-hrdina-pl-instrumental>
51<noun-hrdina-sg-nominative> ::= <noun-stem-hrdina-a> "a" | <noun-stem-hrdina-o> "o" | <noun-stem-hrdina-ista> "ista"
52<noun-hrdina-sg-genitive> ::= <noun-stem-hrdina> "u"
53<noun-hrdina-sg-dative> ::= <noun-stem-hrdina> "ovi"
54<noun-hrdina-sg-accusative> ::= <noun-stem-hrdina> "u"
55<noun-hrdina-sg-locative> ::= <noun-stem-hrdina> "ovi"
56<noun-hrdina-sg-instrumental> ::= <noun-stem-hrdina> "om"
57<noun-hrdina-pl-nominative> ::= <noun-stem-hrdina-a> "ovia" | <noun-stem-hrdina-o> "ovia" | <noun-stem-hrdina-ista> "i"
58<noun-hrdina-pl-genitive> ::= <noun-stem-hrdina> "ov"
59<noun-hrdina-pl-dative> ::= <noun-stem-hrdina> "om"
60<noun-hrdina-pl-accusative> ::= <noun-stem-hrdina> "ov"
61<noun-hrdina-pl-locative> ::= <noun-stem-hrdina> "och"
62<noun-hrdina-pl-instrumental> ::= <noun-stem-hrdina> "ami"
63<noun-stem-hrdina> ::= <noun-stem-hrdina-a> | <noun-stem-hrdina-o> | <noun-stem-hrdina-ista>
64<noun-stem-hrdina-a> ::= "hrdin" | "sluh" | "sudc"
65<noun-stem-hrdina-o> ::= "Krask"
66<noun-stem-hrdina-ista> ::= "husl"
67
68<noun-dub> ::= <noun-dub-sg> | <noun-dub-pl>
69<noun-dub-sg> ::= <noun-dub-sg-nominative> | <noun-dub-sg-genitive> | <noun-dub-sg-dative> | <noun-dub-sg-accusative> | <noun-dub-sg-locative> | <noun-dub-sg-instrumental>
70<noun-dub-pl> ::= <noun-dub-pl-nominative> | <noun-dub-pl-genitive> | <noun-dub-pl-dative> | <noun-dub-pl-accusative> | <noun-dub-pl-locative> | <noun-dub-pl-instrumental>
71<noun-dub-sg-nominative> ::= <noun-stem-dub> ""
72<noun-dub-sg-genitive> ::= <noun-stem-dub> "a"
73<noun-dub-sg-dative> ::= <noun-stem-dub> "u"
74<noun-dub-sg-accusative> ::= <noun-stem-dub> ""
75<noun-dub-sg-locative> ::= <noun-stem-dub> "e"
76<noun-dub-sg-instrumental> ::= <noun-stem-dub> "om"
77<noun-dub-pl-nominative> ::= <noun-stem-dub> "y"
78<noun-dub-pl-genitive> ::= <noun-stem-dub> "ov"
79<noun-dub-pl-dative> ::= <noun-stem-dub> "om"
80<noun-dub-pl-accusative> ::= <noun-stem-dub> "y"
81<noun-dub-pl-locative> ::= <noun-stem-dub> "och"
82<noun-dub-pl-instrumental> ::= <noun-stem-dub> "i"
83<noun-stem-dub> ::= "dub" | "dom" | "strom" | "vodopád" | "obraz" | "autobus" | "trolejbus" | "pot"
84
85<noun-stroj> ::= <noun-stroj-sg> | <noun-stroj-pl>
86<noun-stroj-sg> ::= <noun-stroj-sg-nominative> | <noun-stroj-sg-genitive> | <noun-stroj-sg-dative> | <noun-stroj-sg-accusative> | <noun-stroj-sg-locative> | <noun-stroj-sg-instrumental>
87<noun-stroj-pl> ::= <noun-stroj-pl-nominative> | <noun-stroj-pl-genitive> | <noun-stroj-pl-dative> | <noun-stroj-pl-accusative> | <noun-stroj-pl-locative> | <noun-stroj-pl-instrumental>
88<noun-stroj-sg-nominative> ::= <noun-stem-stroj> ""
89<noun-stroj-sg-genitive> ::= <noun-stem-stroj> "a"
90<noun-stroj-sg-dative> ::= <noun-stem-stroj> "u"
91<noun-stroj-sg-accusative> ::= <noun-stem-stroj> ""
92<noun-stroj-sg-locative> ::= <noun-stem-stroj> "i"
93<noun-stroj-sg-instrumental> ::= <noun-stem-stroj> "om"
94<noun-stroj-pl-nominative> ::= <noun-stem-stroj> "e"
95<noun-stroj-pl-genitive> ::= <noun-stem-stroj> "ov"
96<noun-stroj-pl-dative> ::= <noun-stem-stroj> "om"
97<noun-stroj-pl-accusative> ::= <noun-stem-stroj> "e"
98<noun-stroj-pl-locative> ::= <noun-stem-stroj> "och"
99<noun-stroj-pl-instrumental> ::= <noun-stem-stroj> "mi"
100<noun-stem-stroj> ::= "stroj" | "počítač" | "dážď" | "máj" | "kameň" | "kôš" | "nôž" | "terč" | "olej" | "čaj" # | "oheň"
101
102<noun-kuli> ::= <noun-kuli-sg> | <noun-kuli-pl>
103<noun-kuli-sg> ::= <noun-kuli-sg-nominative> | <noun-kuli-sg-genitive> | <noun-kuli-sg-dative> | <noun-kuli-sg-accusative> | <noun-kuli-sg-locative> | <noun-kuli-sg-instrumental>
104<noun-kuli-pl> ::= <noun-kuli-pl-nominative> | <noun-kuli-pl-genitive> | <noun-kuli-pl-dative> | <noun-kuli-pl-accusative> | <noun-kuli-pl-locative> | <noun-kuli-pl-instrumental>
105<noun-kuli-sg-nominative> ::= <noun-stem-kuli> ""
106<noun-kuli-sg-genitive> ::= <noun-stem-kuli> "ho"
107<noun-kuli-sg-dative> ::= <noun-stem-kuli> "mu"
108<noun-kuli-sg-accusative> ::= <noun-stem-kuli> "ho"
109<noun-kuli-sg-locative> ::= <noun-stem-kuli> "m"
110<noun-kuli-sg-instrumental> ::= <noun-stem-kuli> "m"
111<noun-kuli-pl-nominative> ::= <noun-stem-kuli> "ovia"
112<noun-kuli-pl-genitive> ::= <noun-stem-kuli> "ov"
113<noun-kuli-pl-dative> ::= <noun-stem-kuli> "om"
114<noun-kuli-pl-accusative> ::= <noun-stem-kuli> "ob"
115<noun-kuli-pl-locative> ::= <noun-stem-kuli> "och"
116<noun-kuli-pl-instrumental> ::= <noun-stem-kuli> "ami"
117<noun-stem-kuli> ::= "kuli" | "pony" | "grizly" | "Goethe" | "Pálfy" | "Škultéty" | "Goethe" | "Krčméry"
118
119<noun-feminine> ::= <noun-feminine-sg> | <noun-feminine-pl>
120<noun-feminine-sg> ::= <noun-feminine-sg-nominative> | <noun-feminine-sg-genitive> | <noun-feminine-sg-dative> | <noun-feminine-sg-accusative> | <noun-feminine-sg-locative> | <noun-feminine-sg-instrumental>
121<noun-feminine-pl> ::= <noun-feminine-pl-nominative> | <noun-feminine-pl-genitive> | <noun-feminine-pl-dative> | <noun-feminine-pl-accusative> | <noun-feminine-pl-locative> | <noun-feminine-pl-instrumental>
122<noun-feminine-sg-nominative> ::= <noun-zena-sg-nominative> | <noun-ulica-sg-nominative> | <noun-dlan-sg-nominative> | <noun-kost-sg-nominative> | <noun-gazdina-sg-nominative> | <noun-idea-sg-nominative>
123<noun-feminine-sg-genitive> ::= <noun-zena-sg-genitive> | <noun-ulica-sg-genitive> | <noun-dlan-sg-genitive> | <noun-kost-sg-genitive> | <noun-gazdina-sg-genitive> | <noun-idea-sg-genitive>
124<noun-feminine-sg-dative> ::= <noun-zena-sg-dative> | <noun-ulica-sg-dative> | <noun-dlan-sg-dative> | <noun-kost-sg-dative> | <noun-gazdina-sg-dative> | <noun-idea-sg-dative>
125<noun-feminine-sg-accusative> ::= <noun-zena-sg-accusative> | <noun-ulica-sg-accusative> | <noun-dlan-sg-accusative> | <noun-kost-sg-accusative> | <noun-gazdina-sg-accusative> | <noun-idea-sg-accusative>
126<noun-feminine-sg-locative> ::= <noun-zena-sg-locative> | <noun-ulica-sg-locative> | <noun-dlan-sg-locative> | <noun-kost-sg-locative> | <noun-gazdina-sg-locative> | <noun-idea-sg-locative>
127<noun-feminine-sg-instrumental> ::= <noun-zena-sg-instrumental> | <noun-ulica-sg-instrumental> | <noun-dlan-sg-instrumental> | <noun-kost-sg-instrumental> | <noun-gazdina-sg-instrumental> | <noun-idea-sg-instrumental>
128<noun-feminine-pl-nominative> ::= <noun-zena-pl-nominative> | <noun-ulica-pl-nominative> | <noun-dlan-pl-nominative> | <noun-kost-pl-nominative> | <noun-gazdina-pl-nominative> | <noun-idea-pl-nominative>
129<noun-feminine-pl-genitive> ::= <noun-zena-pl-genitive> | <noun-ulica-pl-genitive> | <noun-dlan-pl-genitive> | <noun-kost-pl-genitive> | <noun-gazdina-pl-genitive> | <noun-idea-pl-genitive>
130<noun-feminine-pl-dative> ::= <noun-zena-pl-dative> | <noun-ulica-pl-dative> | <noun-dlan-pl-dative> | <noun-kost-pl-dative> | <noun-gazdina-pl-dative> | <noun-idea-pl-dative>
131<noun-feminine-pl-accusative> ::= <noun-zena-pl-accusative> | <noun-ulica-pl-accusative> | <noun-dlan-pl-accusative> | <noun-kost-pl-accusative> | <noun-gazdina-pl-accusative> | <noun-idea-pl-accusative>
132<noun-feminine-pl-locative> ::= <noun-zena-pl-locative> | <noun-ulica-pl-locative> | <noun-dlan-pl-locative> | <noun-kost-pl-locative> | <noun-gazdina-pl-locative> | <noun-idea-pl-locative>
133<noun-feminine-pl-instrumental> ::= <noun-zena-pl-instrumental> | <noun-ulica-pl-instrumental> | <noun-dlan-pl-instrumental> | <noun-kost-pl-instrumental> | <noun-gazdina-pl-instrumental> | <noun-idea-pl-instrumental>
134
135<noun-zena> ::= <noun-zena-sg> | <noun-zena-pl>
136<noun-zena-sg> ::= <noun-zena-sg-nominative> | <noun-zena-sg-genitive> | <noun-zena-sg-dative> | <noun-zena-sg-accusative> | <noun-zena-sg-locative> | <noun-zena-sg-instrumental>
137<noun-zena-pl> ::= <noun-zena-pl-nominative> | <noun-zena-pl-genitive> | <noun-zena-pl-dative> | <noun-zena-pl-accusative> | <noun-zena-pl-locative> | <noun-zena-pl-instrumental>
138<noun-zena-sg-nominative> ::= <noun-stem-zena> "a"
139<noun-zena-sg-genitive> ::= <noun-stem-zena> "y"
140<noun-zena-sg-dative> ::= <noun-stem-zena> "e"
141<noun-zena-sg-accusative> ::= <noun-stem-zena> "y"
142<noun-zena-sg-locative> ::= <noun-stem-zena> "e"
143<noun-zena-sg-instrumental> ::= <noun-stem-zena> "ou"
144<noun-zena-pl-nominative> ::= <noun-stem-zena> "y"
145<noun-zena-pl-genitive> ::= <noun-stem-zena> "í" # meh
146<noun-zena-pl-dative> ::= <noun-stem-zena> "ám"
147<noun-zena-pl-accusative> ::= <noun-stem-zena> "y"
148<noun-zena-pl-locative> ::= <noun-stem-zena> "ách"
149<noun-zena-pl-instrumental> ::= <noun-stem-zena> "ami"
150<noun-stem-zena> ::= "žen" | "dcér" | "mam" |"vnučk" | "rodin" | "knih" | "cest" | "vod" | "ruk" | "noh" | "hlav" | "stred" | "sobot"
151
152<noun-ulica> ::= <noun-ulica-sg> | <noun-ulica-pl>
153<noun-ulica-sg> ::= <noun-ulica-sg-nominative> | <noun-ulica-sg-genitive> | <noun-ulica-sg-dative> | <noun-ulica-sg-accusative> | <noun-ulica-sg-locative> | <noun-ulica-sg-instrumental>
154<noun-ulica-pl> ::= <noun-ulica-pl-nominative> | <noun-ulica-pl-genitive> | <noun-ulica-pl-dative> | <noun-ulica-pl-accusative> | <noun-ulica-pl-locative> | <noun-ulica-pl-instrumental>
155<noun-ulica-sg-nominative> ::= <noun-stem-ulica> "a"
156<noun-ulica-sg-genitive> ::= <noun-stem-ulica> "e"
157<noun-ulica-sg-dative> ::= <noun-stem-ulica> "i"
158<noun-ulica-sg-accusative> ::= <noun-stem-ulica> "u"
159<noun-ulica-sg-locative> ::= <noun-stem-ulica> "i"
160<noun-ulica-sg-instrumental> ::= <noun-stem-ulica> "ou"
161<noun-ulica-pl-nominative> ::= <noun-stem-ulica> "e"
162<noun-ulica-pl-genitive> ::= <noun-stem-ulica> "íc" # ulíc
163<noun-ulica-pl-dative> ::= <noun-stem-ulica> "iam"
164<noun-ulica-pl-accusative> ::= <noun-stem-ulica> "e"
165<noun-ulica-pl-locative> ::= <noun-stem-ulica> "iach"
166<noun-ulica-pl-instrumental> ::= <noun-stem-ulica> "ami"
167<noun-stem-ulica> ::= "ulic" | "lodenic" | "vež" | "košeľ" | "prác" | "stanic" | "schôdz" | "tabuľ" | "ruž" | "cibuľ" | "vaň" | "fľaš" | "nedeľ" | "chvíľ"
168
169<noun-dlan> ::= <noun-dlan-sg> | <noun-dlan-pl>
170<noun-dlan-sg> ::= <noun-dlan-sg-nominative> | <noun-dlan-sg-genitive> | <noun-dlan-sg-dative> | <noun-dlan-sg-accusative> | <noun-dlan-sg-locative> | <noun-dlan-sg-instrumental>
171<noun-dlan-pl> ::= <noun-dlan-pl-nominative> | <noun-dlan-pl-genitive> | <noun-dlan-pl-dative> | <noun-dlan-pl-accusative> | <noun-dlan-pl-locative> | <noun-dlan-pl-instrumental>
172<noun-dlan-sg-nominative> ::= <noun-stem-dlan> ""
173<noun-dlan-sg-genitive> ::= <noun-stem-dlan> "e"
174<noun-dlan-sg-dative> ::= <noun-stem-dlan> "i"
175<noun-dlan-sg-accusative> ::= <noun-stem-dlan> ""
176<noun-dlan-sg-locative> ::= <noun-stem-dlan> "i"
177<noun-dlan-sg-instrumental> ::= <noun-stem-dlan> "ou"
178<noun-dlan-pl-nominative> ::= <noun-stem-dlan> "e"
179<noun-dlan-pl-genitive> ::= <noun-stem-dlan> "í"
180<noun-dlan-pl-dative> ::= <noun-stem-dlan> "iam"
181<noun-dlan-pl-accusative> ::= <noun-stem-dlan> "e"
182<noun-dlan-pl-locative> ::= <noun-stem-dlan> "iach"
183<noun-dlan-pl-instrumental> ::= <noun-stem-dlan> "ami"
184<noun-stem-dlan> ::= "dlaň" | "púšť" | "čakáreň" | "pec" | "pieseň" | "loď" | "báseň" | "reportáž" | "posteľ" | "predpoveď"
185
186<noun-kost> ::= <noun-kost-sg> | <noun-kost-pl>
187<noun-kost-sg> ::= <noun-kost-sg-nominative> | <noun-kost-sg-genitive> | <noun-kost-sg-dative> | <noun-kost-sg-accusative> | <noun-kost-sg-locative> | <noun-kost-sg-instrumental>
188<noun-kost-pl> ::= <noun-kost-pl-nominative> | <noun-kost-pl-genitive> | <noun-kost-pl-dative> | <noun-kost-pl-accusative> | <noun-kost-pl-locative> | <noun-kost-pl-instrumental>
189<noun-kost-sg-nominative> ::= <noun-stem-kost> ""
190<noun-kost-sg-genitive> ::= <noun-stem-kost> "i"
191<noun-kost-sg-dative> ::= <noun-stem-kost> "i"
192<noun-kost-sg-accusative> ::= <noun-stem-kost> ""
193<noun-kost-sg-locative> ::= <noun-stem-kost> "i"
194<noun-kost-sg-instrumental> ::= <noun-stem-kost> "ou"
195<noun-kost-pl-nominative> ::= <noun-stem-kost> "i"
196<noun-kost-pl-genitive> ::= <noun-stem-kost> "í"
197<noun-kost-pl-dative> ::= <noun-stem-kost> "iam"
198<noun-kost-pl-accusative> ::= <noun-stem-kost> "i"
199<noun-kost-pl-locative> ::= <noun-stem-kost> "iach"
200<noun-kost-pl-instrumental> ::= <noun-stem-kost> "ami"
201<noun-stem-kost> ::= "kosť" | "radosť" | "vec" | "noc" | "step" | "pomoc" | "zmes" | "krv" | "tvrdosť"
202
203<noun-gazdina> ::= <noun-gazdina-sg> | <noun-gazdina-pl>
204<noun-gazdina-sg> ::= <noun-gazdina-sg-nominative> | <noun-gazdina-sg-genitive> | <noun-gazdina-sg-dative> | <noun-gazdina-sg-accusative> | <noun-gazdina-sg-locative> | <noun-gazdina-sg-instrumental>
205<noun-gazdina-pl> ::= <noun-gazdina-pl-nominative> | <noun-gazdina-pl-genitive> | <noun-gazdina-pl-dative> | <noun-gazdina-pl-accusative> | <noun-gazdina-pl-locative> | <noun-gazdina-pl-instrumental>
206<noun-gazdina-sg-nominative> ::= <noun-stem-gazdina> "á"
207<noun-gazdina-sg-genitive> ::= <noun-stem-gazdina> "ej"
208<noun-gazdina-sg-dative> ::= <noun-stem-gazdina> "ej"
209<noun-gazdina-sg-accusative> ::= <noun-stem-gazdina> "ú"
210<noun-gazdina-sg-locative> ::= <noun-stem-gazdina> "ej"
211<noun-gazdina-sg-instrumental> ::= <noun-stem-gazdina> "ou"
212<noun-gazdina-pl-nominative> ::= <noun-stem-gazdina> "é"
213<noun-gazdina-pl-genitive> ::= <noun-stem-gazdina> "ín" # meh
214<noun-gazdina-pl-dative> ::= <noun-stem-gazdina> "ám"
215<noun-gazdina-pl-accusative> ::= <noun-stem-gazdina> "é"
216<noun-gazdina-pl-locative> ::= <noun-stem-gazdina> "ách"
217<noun-gazdina-pl-instrumental> ::= <noun-stem-gazdina> "ami"
218<noun-stem-gazdina> ::= "gazdin" | "princezn" | "kráľovn" | "cisárovn" | "šľachtičn" | "kňažn"
219
220<noun-idea> ::= <noun-idea-sg> | <noun-idea-pl>
221<noun-idea-sg> ::= <noun-idea-sg-nominative> | <noun-idea-sg-genitive> | <noun-idea-sg-dative> | <noun-idea-sg-accusative> | <noun-idea-sg-locative> | <noun-idea-sg-instrumental>
222<noun-idea-pl> ::= <noun-idea-pl-nominative> | <noun-idea-pl-genitive> | <noun-idea-pl-dative> | <noun-idea-pl-accusative> | <noun-idea-pl-locative> | <noun-idea-pl-instrumental>
223<noun-idea-sg-nominative> ::= <noun-stem-idea> "a"
224<noun-idea-sg-genitive> ::= <noun-stem-idea> "y"
225<noun-idea-sg-dative> ::= <noun-stem-idea> "i"
226<noun-idea-sg-accusative> ::= <noun-stem-idea> "u"
227<noun-idea-sg-locative> ::= <noun-stem-idea> "i"
228<noun-idea-sg-instrumental> ::= <noun-stem-idea> "ou"
229<noun-idea-pl-nominative> ::= <noun-stem-idea> "y"
230<noun-idea-pl-genitive> ::= <noun-stem-idea> "í"
231<noun-idea-pl-dative> ::= <noun-stem-idea> "ám"
232<noun-idea-pl-accusative> ::= <noun-stem-idea> "y"
233<noun-idea-pl-locative> ::= <noun-stem-idea> "ách"
234<noun-idea-pl-instrumental> ::= <noun-stem-idea> "ami"
235<noun-stem-idea> ::= "ide" | "orchide" | "Nikaragu" | "Ike" | "Andre" | "alo"
236
237<noun-neuter> ::= <noun-neuter-sg> | <noun-neuter-pl>
238<noun-neuter-sg> ::= <noun-neuter-sg-nominative> | <noun-neuter-sg-genitive> | <noun-neuter-sg-dative> | <noun-neuter-sg-accusative> | <noun-neuter-sg-locative> | <noun-neuter-sg-instrumental>
239<noun-neuter-pl> ::= <noun-neuter-pl-nominative> | <noun-neuter-pl-genitive> | <noun-neuter-pl-dative> | <noun-neuter-pl-accusative> | <noun-neuter-pl-locative> | <noun-neuter-pl-instrumental>
240<noun-neuter-sg-nominative> ::= <noun-mesto-sg-nominative> | <noun-srdce-sg-nominative> | <noun-vysvedcenie-sg-nominative> | <noun-dievca-sg-nominative>
241<noun-neuter-sg-genitive> ::= <noun-mesto-sg-genitive> | <noun-srdce-sg-genitive> | <noun-vysvedcenie-sg-genitive> | <noun-dievca-sg-genitive>
242<noun-neuter-sg-dative> ::= <noun-mesto-sg-dative> | <noun-srdce-sg-dative> | <noun-vysvedcenie-sg-dative> | <noun-dievca-sg-dative>
243<noun-neuter-sg-accusative> ::= <noun-mesto-sg-accusative> | <noun-srdce-sg-accusative> | <noun-vysvedcenie-sg-accusative> | <noun-dievca-sg-accusative>
244<noun-neuter-sg-locative> ::= <noun-mesto-sg-locative> | <noun-srdce-sg-locative> | <noun-vysvedcenie-sg-locative> | <noun-dievca-sg-locative>
245<noun-neuter-sg-instrumental> ::= <noun-mesto-sg-instrumental> | <noun-srdce-sg-instrumental> | <noun-vysvedcenie-sg-instrumental> | <noun-dievca-sg-instrumental>
246<noun-neuter-pl-nominative> ::= <noun-mesto-pl-nominative> | <noun-srdce-pl-nominative> | <noun-vysvedcenie-pl-nominative> | <noun-dievca-pl-nominative>
247<noun-neuter-pl-genitive> ::= <noun-mesto-pl-genitive> | <noun-srdce-pl-genitive> | <noun-vysvedcenie-pl-genitive> | <noun-dievca-pl-genitive>
248<noun-neuter-pl-dative> ::= <noun-mesto-pl-dative> | <noun-srdce-pl-dative> | <noun-vysvedcenie-pl-dative> | <noun-dievca-pl-dative>
249<noun-neuter-pl-accusative> ::= <noun-mesto-pl-accusative> | <noun-srdce-pl-accusative> | <noun-vysvedcenie-pl-accusative> | <noun-dievca-pl-accusative>
250<noun-neuter-pl-locative> ::= <noun-mesto-pl-locative> | <noun-srdce-pl-locative> | <noun-vysvedcenie-pl-locative> | <noun-dievca-pl-locative>
251<noun-neuter-pl-instrumental> ::= <noun-mesto-pl-instrumental> | <noun-srdce-pl-instrumental> | <noun-vysvedcenie-pl-instrumental> | <noun-dievca-pl-instrumental>
252
253<noun-mesto> ::= <noun-mesto-sg> | <noun-mesto-pl>
254<noun-mesto-sg> ::= <noun-mesto-sg-nominative> | <noun-mesto-sg-genitive> | <noun-mesto-sg-dative> | <noun-mesto-sg-accusative> | <noun-mesto-sg-locative> | <noun-mesto-sg-instrumental>
255<noun-mesto-pl> ::= <noun-mesto-pl-nominative> | <noun-mesto-pl-genitive> | <noun-mesto-pl-dative> | <noun-mesto-pl-accusative> | <noun-mesto-pl-locative> | <noun-mesto-pl-instrumental>
256<noun-mesto-sg-nominative> ::= <noun-stem-mesto> "o"
257<noun-mesto-sg-genitive> ::= <noun-stem-mesto> "a"
258<noun-mesto-sg-dative> ::= <noun-stem-mesto> "u"
259<noun-mesto-sg-accusative> ::= <noun-stem-mesto> "o"
260<noun-mesto-sg-locative> ::= <noun-stem-mesto> "e" # -u
261<noun-mesto-sg-instrumental> ::= <noun-stem-mesto> "om"
262<noun-mesto-pl-nominative> ::= <noun-stem-mesto> "á"
263<noun-mesto-pl-genitive> ::= <noun-stem-mesto> "í" # miest
264<noun-mesto-pl-dative> ::= <noun-stem-mesto> "ám"
265<noun-mesto-pl-accusative> ::= <noun-stem-mesto> "á"
266<noun-mesto-pl-locative> ::= <noun-stem-mesto> "ách"
267<noun-mesto-pl-instrumental> ::= <noun-stem-mesto> "ami"
268<noun-stem-mesto> ::= "mest" | "mravenisk" | "aut" | "let" | "aut" | "koles" | "jablk" | "Slovensk" | "kaka" | "drev" | "diel" | "vedr" | "ok" | "uch" | "bruch" | "mydl" | "rádi" # | "gymnázium", "štúdium"
269
270<noun-srdce> ::= <noun-srdce-sg> | <noun-srdce-pl>
271<noun-srdce-sg> ::= <noun-srdce-sg-nominative> | <noun-srdce-sg-genitive> | <noun-srdce-sg-dative> | <noun-srdce-sg-accusative> | <noun-srdce-sg-locative> | <noun-srdce-sg-instrumental>
272<noun-srdce-pl> ::= <noun-srdce-pl-nominative> | <noun-srdce-pl-genitive> | <noun-srdce-pl-dative> | <noun-srdce-pl-accusative> | <noun-srdce-pl-locative> | <noun-srdce-pl-instrumental>
273<noun-srdce-sg-nominative> ::= <noun-stem-srdce> "e"
274<noun-srdce-sg-genitive> ::= <noun-stem-srdce> "a"
275<noun-srdce-sg-dative> ::= <noun-stem-srdce> "u"
276<noun-srdce-sg-accusative> ::= <noun-stem-srdce> "e"
277<noun-srdce-sg-locative> ::= <noun-stem-srdce> "i" # -u
278<noun-srdce-sg-instrumental> ::= <noun-stem-srdce> "om"
279<noun-srdce-pl-nominative> ::= <noun-stem-srdce> "ia"
280<noun-srdce-pl-genitive> ::= <noun-stem-srdce> "" # sŕdc
281<noun-srdce-pl-dative> ::= <noun-stem-srdce> "iam"
282<noun-srdce-pl-accusative> ::= <noun-stem-srdce> "ia"
283<noun-srdce-pl-locative> ::= <noun-stem-srdce> "iach"
284<noun-srdce-pl-instrumental> ::= <noun-stem-srdce> "ami"
285<noun-stem-srdce> ::= "srdc" | "pol" | "mor" | "vrec" | "vajc" | "mor" | "nástupišt" | "pol"
286
287<noun-vysvedcenie> ::= <noun-vysvedcenie-sg> | <noun-vysvedcenie-pl>
288<noun-vysvedcenie-sg> ::= <noun-vysvedcenie-sg-nominative> | <noun-vysvedcenie-sg-genitive> | <noun-vysvedcenie-sg-dative> | <noun-vysvedcenie-sg-accusative> | <noun-vysvedcenie-sg-locative> | <noun-vysvedcenie-sg-instrumental>
289<noun-vysvedcenie-pl> ::= <noun-vysvedcenie-pl-nominative> | <noun-vysvedcenie-pl-genitive> | <noun-vysvedcenie-pl-dative> | <noun-vysvedcenie-pl-accusative> | <noun-vysvedcenie-pl-locative> | <noun-vysvedcenie-pl-instrumental>
290<noun-vysvedcenie-sg-nominative> ::= <noun-stem-vysvedcenie> "ie"
291<noun-vysvedcenie-sg-genitive> ::= <noun-stem-vysvedcenie> "ia"
292<noun-vysvedcenie-sg-dative> ::= <noun-stem-vysvedcenie> "iu"
293<noun-vysvedcenie-sg-accusative> ::= <noun-stem-vysvedcenie> "ie"
294<noun-vysvedcenie-sg-locative> ::= <noun-stem-vysvedcenie> "í"
295<noun-vysvedcenie-sg-instrumental> ::= <noun-stem-vysvedcenie> "ím"
296<noun-vysvedcenie-pl-nominative> ::= <noun-stem-vysvedcenie> "ia"
297<noun-vysvedcenie-pl-genitive> ::= <noun-stem-vysvedcenie> "í"
298<noun-vysvedcenie-pl-dative> ::= <noun-stem-vysvedcenie> "iam"
299<noun-vysvedcenie-pl-accusative> ::= <noun-stem-vysvedcenie> "ia"
300<noun-vysvedcenie-pl-locative> ::= <noun-stem-vysvedcenie> "iach"
301<noun-vysvedcenie-pl-instrumental> ::= <noun-stem-vysvedcenie> "iami"
302<noun-stem-vysvedcenie> ::= "vysvedčen" | "pozad" | "úskal" | "obdob" | "líst" | "stretnut" | "zahranič" | "námest" | "umenie"
303
304<noun-dievca> ::= <noun-dievca-sg> | <noun-dievca-pl>
305<noun-dievca-sg> ::= <noun-dievca-sg-nominative> | <noun-dievca-sg-genitive> | <noun-dievca-sg-dative> | <noun-dievca-sg-accusative> | <noun-dievca-sg-locative> | <noun-dievca-sg-instrumental>
306<noun-dievca-pl> ::= <noun-dievca-pl-nominative> | <noun-dievca-pl-genitive> | <noun-dievca-pl-dative> | <noun-dievca-pl-accusative> | <noun-dievca-pl-locative> | <noun-dievca-pl-instrumental>
307<noun-dievca-sg-nominative> ::= <noun-stem-dievca> ""
308<noun-dievca-sg-genitive> ::= <noun-stem-dievca> "ťa"
309<noun-dievca-sg-dative> ::= <noun-stem-dievca> "ťu"
310<noun-dievca-sg-accusative> ::= <noun-stem-dievca> ""
311<noun-dievca-sg-locative> ::= <noun-stem-dievca> "ti"
312<noun-dievca-sg-instrumental> ::= <noun-stem-dievca> "ťom"
313<noun-dievca-pl-nominative> ::= <noun-stem-dievca> "tá"
314<noun-dievca-pl-genitive> ::= <noun-stem-dievca> "t"
315<noun-dievca-pl-dative> ::= <noun-stem-dievca> "tám"
316<noun-dievca-pl-accusative> ::= <noun-stem-dievca> "tá"
317<noun-dievca-pl-locative> ::= <noun-stem-dievca> "tách"
318<noun-dievca-pl-instrumental> ::= <noun-stem-dievca> "tami"
319<noun-stem-dievca> ::= "dievča" | "vnúča" | "zviera" | "páža" | "knieža" | "mláďa" | "kura" | "chlápä" | "žriebä" # | "dieťa"
320
321# 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 @@
1# -*- BNF -*-
2
3<objects> ::= <object> | <object> " " <objects>
4
5<object> ::= <object-masculine> | <object-feminine> | <object-neuter>
6<object-masculine> ::= <object-masculine-sg> | <object-masculine-pl>
7<object-feminine> ::= <object-feminine-sg> | <object-feminine-sg>
8<object-neuter> ::= <object-neuter-sg> | <object-neuter-sg>
9
10<object-masculine-sg> ::= <object-masculine-sg-nominative> | <object-masculine-sg-genitive> | <object-masculine-sg-dative> | <object-masculine-sg-accusative> | <object-masculine-sg-locative> | <object-masculine-sg-instrumental>
11<object-masculine-sg-nominative> ::= <noun-masculine-sg-nominative> | <adjective-sg-masculine-nominative> " " <noun-masculine-sg-nominative> | <adjectives-sg-masculine-nominative> " " <noun-masculine-sg-nominative>
12<object-masculine-sg-genitive> ::= <noun-masculine-sg-genitive> | <adjective-sg-masculine-genitive> " " <noun-masculine-sg-genitive> | <adjectives-sg-masculine-genitive> " " <noun-masculine-sg-genitive>
13<object-masculine-sg-dative> ::= <noun-masculine-sg-dative> | <adjective-sg-masculine-dative> " " <noun-masculine-sg-dative> | <adjectives-sg-masculine-dative> " " <noun-masculine-sg-dative>
14<object-masculine-sg-accusative> ::= <noun-masculine-sg-accusative> | <adjective-sg-masculine-accusative> " " <noun-masculine-sg-accusative> | <adjectives-sg-masculine-accusative> " " <noun-masculine-sg-accusative>
15<object-masculine-sg-locative> ::= <noun-masculine-sg-locative> | <adjective-sg-masculine-locative> " " <noun-masculine-sg-locative> | <adjectives-sg-masculine-locative> " " <noun-masculine-sg-locative>
16<object-masculine-sg-instrumental> ::= <noun-masculine-sg-instrumental> | <adjective-sg-masculine-instrumental> " " <noun-masculine-sg-instrumental> | <adjectives-sg-masculine-instrumental> " " <noun-masculine-sg-instrumental>
17
18<object-masculine-pl> ::= <object-masculine-pl-nominative> | <object-masculine-pl-genitive> | <object-masculine-pl-dative> | <object-masculine-pl-accusative> | <object-masculine-pl-locative> | <object-masculine-pl-instrumental>
19<object-masculine-pl-nominative> ::= <noun-masculine-pl-nominative> | <adjective-pl-masculine-nominative> " " <noun-masculine-pl-nominative> | <adjectives-pl-masculine-nominative> " " <noun-masculine-pl-nominative>
20<object-masculine-pl-genitive> ::= <noun-masculine-pl-genitive> | <adjective-pl-masculine-genitive> " " <noun-masculine-pl-genitive> | <adjectives-pl-masculine-genitive> " " <noun-masculine-pl-genitive>
21<object-masculine-pl-dative> ::= <noun-masculine-pl-dative> | <adjective-pl-masculine-dative> " " <noun-masculine-pl-dative> | <adjectives-pl-masculine-dative> " " <noun-masculine-pl-dative>
22<object-masculine-pl-accusative> ::= <noun-masculine-pl-accusative> | <adjective-pl-masculine-accusative> " " <noun-masculine-pl-accusative> | <adjectives-pl-masculine-accusative> " " <noun-masculine-pl-accusative>
23<object-masculine-pl-locative> ::= <noun-masculine-pl-locative> | <adjective-pl-masculine-locative> " " <noun-masculine-pl-locative> | <adjectives-pl-masculine-locative> " " <noun-masculine-pl-locative>
24<object-masculine-pl-instrumental> ::= <noun-masculine-pl-instrumental> | <adjective-pl-masculine-instrumental> " " <noun-masculine-pl-instrumental> | <adjectives-pl-masculine-instrumental> " " <noun-masculine-pl-instrumental>
25
26<object-feminine-sg> ::= <object-feminine-sg-nominative> | <object-feminine-sg-genitive> | <object-feminine-sg-dative> | <object-feminine-sg-accusative> | <object-feminine-sg-locative> | <object-feminine-sg-instrumental>
27<object-feminine-sg-nominative> ::= <noun-feminine-sg-nominative> | <adjective-sg-feminine-nominative> " " <noun-feminine-sg-nominative> | <adjectives-sg-feminine-nominative> " " <noun-feminine-sg-nominative>
28<object-feminine-sg-genitive> ::= <noun-feminine-sg-genitive> | <adjective-sg-feminine-genitive> " " <noun-feminine-sg-genitive> | <adjectives-sg-feminine-genitive> " " <noun-feminine-sg-genitive>
29<object-feminine-sg-dative> ::= <noun-feminine-sg-dative> | <adjective-sg-feminine-dative> " " <noun-feminine-sg-dative> | <adjectives-sg-feminine-dative> " " <noun-feminine-sg-dative>
30<object-feminine-sg-accusative> ::= <noun-feminine-sg-accusative> | <adjective-sg-feminine-accusative> " " <noun-feminine-sg-accusative> | <adjectives-sg-feminine-accusative> " " <noun-feminine-sg-accusative>
31<object-feminine-sg-locative> ::= <noun-feminine-sg-locative> | <adjective-sg-feminine-locative> " " <noun-feminine-sg-locative> | <adjectives-sg-feminine-locative> " " <noun-feminine-sg-locative>
32<object-feminine-sg-instrumental> ::= <noun-feminine-sg-instrumental> | <adjective-sg-feminine-instrumental> " " <noun-feminine-sg-instrumental> | <adjectives-sg-feminine-instrumental> " " <noun-feminine-sg-instrumental>
33
34<object-feminine-pl> ::= <object-feminine-pl-nominative> | <object-feminine-pl-genitive> | <object-feminine-pl-dative> | <object-feminine-pl-accusative> | <object-feminine-pl-locative> | <object-feminine-pl-instrumental>
35<object-feminine-pl-nominative> ::= <noun-feminine-pl-nominative> | <adjective-pl-other-nominative> " " <noun-feminine-pl-nominative> | <adjectives-pl-other-nominative> " " <noun-feminine-pl-nominative>
36<object-feminine-pl-genitive> ::= <noun-feminine-pl-genitive> | <adjective-pl-other-genitive> " " <noun-feminine-pl-genitive> | <adjectives-pl-other-genitive> " " <noun-feminine-pl-genitive>
37<object-feminine-pl-dative> ::= <noun-feminine-pl-dative> | <adjective-pl-other-dative> " " <noun-feminine-pl-dative> | <adjectives-pl-other-dative> " " <noun-feminine-pl-dative>
38<object-feminine-pl-accusative> ::= <noun-feminine-pl-accusative> | <adjective-pl-other-accusative> " " <noun-feminine-pl-accusative> | <adjectives-pl-other-accusative> " " <noun-feminine-pl-accusative>
39<object-feminine-pl-locative> ::= <noun-feminine-pl-locative> | <adjective-pl-other-locative> " " <noun-feminine-pl-locative> | <adjectives-pl-other-locative> " " <noun-feminine-pl-locative>
40<object-feminine-pl-instrumental> ::= <noun-feminine-pl-instrumental> | <adjective-pl-other-instrumental> " " <noun-feminine-pl-instrumental> | <adjectives-pl-other-instrumental> " " <noun-feminine-pl-instrumental>
41
42<object-neuter-sg> ::= <object-neuter-sg-nominative> | <object-neuter-sg-genitive> | <object-neuter-sg-dative> | <object-neuter-sg-accusative> | <object-neuter-sg-locative> | <object-neuter-sg-instrumental>
43<object-neuter-sg-nominative> ::= <noun-neuter-sg-nominative> | <adjective-sg-neuter-nominative> " " <noun-neuter-sg-nominative> | <adjectives-sg-neuter-nominative> " " <noun-neuter-sg-nominative>
44<object-neuter-sg-genitive> ::= <noun-neuter-sg-genitive> | <adjective-sg-neuter-genitive> " " <noun-neuter-sg-genitive> | <adjectives-sg-neuter-genitive> " " <noun-neuter-sg-genitive>
45<object-neuter-sg-dative> ::= <noun-neuter-sg-dative> | <adjective-sg-neuter-dative> " " <noun-neuter-sg-dative> | <adjectives-sg-neuter-dative> " " <noun-neuter-sg-dative>
46<object-neuter-sg-accusative> ::= <noun-neuter-sg-accusative> | <adjective-sg-neuter-accusative> " " <noun-neuter-sg-accusative> | <adjectives-sg-neuter-accusative> " " <noun-neuter-sg-accusative>
47<object-neuter-sg-locative> ::= <noun-neuter-sg-locative> | <adjective-sg-neuter-locative> " " <noun-neuter-sg-locative> | <adjectives-sg-neuter-locative> " " <noun-neuter-sg-locative>
48<object-neuter-sg-instrumental> ::= <noun-neuter-sg-instrumental> | <adjective-sg-neuter-instrumental> " " <noun-neuter-sg-instrumental> | <adjectives-sg-neuter-instrumental> " " <noun-neuter-sg-instrumental>
49
50<object-neuter-pl> ::= <object-neuter-pl-nominative> | <object-neuter-pl-genitive> | <object-neuter-pl-dative> | <object-neuter-pl-accusative> | <object-neuter-pl-locative> | <object-neuter-pl-instrumental>
51<object-neuter-pl-nominative> ::= <noun-neuter-pl-nominative> | <adjective-pl-other-nominative> " " <noun-neuter-pl-nominative> | <adjectives-pl-other-nominative> " " <noun-neuter-pl-nominative>
52<object-neuter-pl-genitive> ::= <noun-neuter-pl-genitive> | <adjective-pl-other-genitive> " " <noun-neuter-pl-genitive> | <adjectives-pl-other-genitive> " " <noun-neuter-pl-genitive>
53<object-neuter-pl-dative> ::= <noun-neuter-pl-dative> | <adjective-pl-other-dative> " " <noun-neuter-pl-dative> | <adjectives-pl-other-dative> " " <noun-neuter-pl-dative>
54<object-neuter-pl-accusative> ::= <noun-neuter-pl-accusative> | <adjective-pl-other-accusative> " " <noun-neuter-pl-accusative> | <adjectives-pl-other-accusative> " " <noun-neuter-pl-accusative>
55<object-neuter-pl-locative> ::= <noun-neuter-pl-locative> | <adjective-pl-other-locative> " " <noun-neuter-pl-locative> | <adjectives-pl-other-locative> " " <noun-neuter-pl-locative>
56<object-neuter-pl-instrumental> ::= <noun-neuter-pl-instrumental> | <adjective-pl-other-instrumental> " " <noun-neuter-pl-instrumental> | <adjectives-pl-other-instrumental> " " <noun-neuter-pl-instrumental>
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 @@
1# slovak-sentence.bnf -*- BNF -*-
2# references:
3# - https://www.zones.sk/studentske-prace/gramatika/11209-morfologia-slovenskeho-jazyka/
4# - https://yourslovakteacher.com/grammar_theory/introduction-to-slovak-syntax-and-sentence-structure/
5
6<initial> ::= <sentence> <EOF>
7<sentence> ::= <fragment> <sentence-end> | <fragment> ", " <sentence> | <fragment> ", " <fragment-joiner> " " <sentence>
8<fragment> ::= <verb> " " <object> | <fragment-sg> | <fragment-pl>
9<fragment-sg> ::= <fragment-sg-p1> | <fragment-sg-p2> | <fragment-sg-p3>
10<fragment-pl> ::= <fragment-pl-p1> | <fragment-pl-p2> | <fragment-pl-p3>
11<fragment-sg-p1> ::= <subject-sg-p1> " " <verb-sg-p1> " " <object>
12<fragment-sg-p2> ::= <subject-sg-p2> " " <verb-sg-p2> " " <object>
13<fragment-sg-p3> ::= <subject-sg-p3> " " <verb-sg-p3> " " <object>
14<fragment-pl-p1> ::= <subject-pl-p1> " " <verb-pl-p1> " " <object>
15<fragment-pl-p2> ::= <subject-pl-p2> " " <verb-pl-p2> " " <object>
16<fragment-pl-p3> ::= <subject-pl-p3> " " <verb-pl-p3> " " <object>
17
18<fragment-joiner> ::= "ale" | "keď"
19<sentence-end> ::= "." | "?" | "!" | "..."
20
21<object> ::= <noun>
22
23<subject> ::= <subject-sg> | <subject-pl>
24<subject-sg> ::= <subject-sg-p1> | <subject-sg-p2> | <subject-sg-p3>
25<subject-pl> ::= <subject-pl-p1> | <subject-pl-p2> | <subject-pl-p3>
26<subject-sg-p1> ::= <pronoun-sg-p1>
27<subject-sg-p2> ::= <pronoun-sg-p2>
28<subject-sg-p3> ::= <pronoun-sg-p3> | <noun-sg-nominative>
29<subject-pl-p1> ::= <pronoun-pl-p1>
30<subject-pl-p2> ::= <pronoun-pl-p2>
31<subject-pl-p3> ::= <pronoun-pl-p3> | <noun-pl-nominative>
32
33<pronoun> ::= <pronoun-sg> | <pronoun-pl>
34<pronoun-sg> ::= <pronoun-sg-p1> | <pronoun-sg-p2> | <pronoun-sg-p3>
35<pronoun-pl> ::= <pronoun-pl-p1> | <pronoun-pl-p2> | <pronoun-pl-p3>
36<pronoun-sg-p1> ::= "ja"
37<pronoun-sg-p2> ::= "ty"
38<pronoun-sg-p3> ::= "on" | "ona" | "ono"
39<pronoun-pl-p1> ::= "my"
40<pronoun-pl-p2> ::= "vy"
41<pronoun-pl-p3> ::= "oni" | "ony"
42
43# 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 @@
1# slovak-verb.bnf -*- BNF -*-
2# resources:
3# - https://www.verbix.com/languages/slovak
4# - https://slovake.eu/grammar/classes/verbs
5# - https://www.eduself.sk/slovensky-jazyk/gramatika/slovesa
6# - https://yourslovakteacher.com/patterns-in-slovak-verb-conjugation/
7# - https://yourslovakteacher.com/grammar_theory/overview-of-slovak-verb-tenses/
8# - https://www.zones.sk/studentske-prace/gramatika/11209-morfologia-slovenskeho-jazyka/
9
10<verb> ::= <verb-imperfective> | <verb-perfective>
11<verb-sg> ::= <verb-sg-p1> | <verb-sg-p2> | <verb-sg-p3>
12<verb-pl> ::= <verb-pl-p1> | <verb-pl-p2> | <verb-pl-p3>
13<verb-sg-p1> ::= <verb-imperfective-indicative-future-sg-p1> | <verb-perfective-indicative-future-sg-p1>
14<verb-sg-p2> ::= <verb-imperfective-indicative-future-sg-p2> | <verb-perfective-indicative-future-sg-p2>
15<verb-sg-p3> ::= <verb-imperfective-indicative-future-sg-p3> | <verb-perfective-indicative-future-sg-p3>
16<verb-pl-p1> ::= <verb-imperfective-indicative-future-pl-p1> | <verb-perfective-indicative-future-pl-p1>
17<verb-pl-p2> ::= <verb-imperfective-indicative-future-pl-p2> | <verb-perfective-indicative-future-pl-p2>
18<verb-pl-p3> ::= <verb-imperfective-indicative-future-pl-p3> | <verb-perfective-indicative-future-pl-p3>
19
20<verb-imperfective> ::= <verb-imperfective-indicative> # |
21<verb-imperfective-indicative> ::= <verb-imperfective-indicative-future> # |
22<verb-imperfective-indicative-future> ::= <verb-imperfective-indicative-future-sg> | <verb-imperfective-indicative-future-pl>
23<verb-imperfective-indicative-future-sg> ::= <verb-imperfective-indicative-future-sg-p1> | <verb-imperfective-indicative-future-sg-p2> | <verb-imperfective-indicative-future-sg-p3>
24<verb-imperfective-indicative-future-pl> ::= <verb-imperfective-indicative-future-pl-p1> | <verb-imperfective-indicative-future-pl-p2> | <verb-imperfective-indicative-future-pl-p3>
25<verb-imperfective-indicative-future-sg-p1> ::= "budem " <verb-infinitive>
26<verb-imperfective-indicative-future-sg-p2> ::= "budeš " <verb-infinitive>
27<verb-imperfective-indicative-future-sg-p3> ::= "bude " <verb-infinitive>
28<verb-imperfective-indicative-future-pl-p1> ::= "budeme " <verb-infinitive>
29<verb-imperfective-indicative-future-pl-p2> ::= "budete " <verb-infinitive>
30<verb-imperfective-indicative-future-pl-p3> ::= "budú " <verb-infinitive>
31
32<verb-perfective> ::= <verb-perfective-indicative> # |
33<verb-perfective-indicative> ::= <verb-perfective-indicative-future> # |
34<verb-perfective-indicative-future> ::= <verb-perfective-indicative-future-sg> | <verb-perfective-indicative-future-pl>
35<verb-perfective-indicative-future-sg> ::= <verb-perfective-indicative-future-sg-p1> | <verb-perfective-indicative-future-sg-p2> | <verb-perfective-indicative-future-sg-p3>
36<verb-perfective-indicative-future-pl> ::= <verb-perfective-indicative-future-pl-p1> | <verb-perfective-indicative-future-pl-p2> | <verb-perfective-indicative-future-pl-p3>
37<verb-perfective-indicative-future-sg-p1> ::= <verb-perfective-indicative-future-sg-p1-g1-a> | <verb-perfective-indicative-future-sg-p1-g1-b> | <verb-perfective-indicative-future-sg-p1-g2-a> | <verb-perfective-indicative-future-sg-p1-g2-b> | <verb-perfective-indicative-future-sg-p1-g3> | <verb-perfective-indicative-future-sg-p1-g4>
38<verb-perfective-indicative-future-sg-p2> ::= <verb-perfective-indicative-future-sg-p2-g1-a> | <verb-perfective-indicative-future-sg-p2-g1-b> | <verb-perfective-indicative-future-sg-p2-g2-a> | <verb-perfective-indicative-future-sg-p2-g2-b> | <verb-perfective-indicative-future-sg-p2-g3> | <verb-perfective-indicative-future-sg-p2-g4>
39<verb-perfective-indicative-future-sg-p3> ::= <verb-perfective-indicative-future-sg-p3-g1-a> | <verb-perfective-indicative-future-sg-p3-g1-b> | <verb-perfective-indicative-future-sg-p3-g2-a> | <verb-perfective-indicative-future-sg-p3-g2-b> | <verb-perfective-indicative-future-sg-p3-g3> | <verb-perfective-indicative-future-sg-p3-g4>
40<verb-perfective-indicative-future-pl-p1> ::= <verb-perfective-indicative-future-pl-p1-g1-a> | <verb-perfective-indicative-future-pl-p1-g1-b> | <verb-perfective-indicative-future-pl-p1-g2-a> | <verb-perfective-indicative-future-pl-p1-g2-b> | <verb-perfective-indicative-future-pl-p1-g3> | <verb-perfective-indicative-future-pl-p1-g4>
41<verb-perfective-indicative-future-pl-p2> ::= <verb-perfective-indicative-future-pl-p2-g1-a> | <verb-perfective-indicative-future-pl-p2-g1-b> | <verb-perfective-indicative-future-pl-p2-g2-a> | <verb-perfective-indicative-future-pl-p2-g2-b> | <verb-perfective-indicative-future-pl-p2-g3> | <verb-perfective-indicative-future-pl-p2-g4>
42<verb-perfective-indicative-future-pl-p3> ::= <verb-perfective-indicative-future-pl-p3-g1-a> | <verb-perfective-indicative-future-pl-p3-g1-b> | <verb-perfective-indicative-future-pl-p3-g2-a> | <verb-perfective-indicative-future-pl-p3-g2-b> | <verb-perfective-indicative-future-pl-p3-g3> | <verb-perfective-indicative-future-pl-p3-g4>
43
44<verb-perfective-indicative-future-sg-p1-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "ám"
45<verb-perfective-indicative-future-sg-p2-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "áš"
46<verb-perfective-indicative-future-sg-p3-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "á"
47<verb-perfective-indicative-future-pl-p1-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "áme"
48<verb-perfective-indicative-future-pl-p2-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "áte"
49<verb-perfective-indicative-future-pl-p3-g1-a> ::= <verb-prefix> <verb-stem-g1-a> "ajú"
50
51<verb-perfective-indicative-future-sg-p1-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "am"
52<verb-perfective-indicative-future-sg-p2-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "aš"
53<verb-perfective-indicative-future-sg-p3-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "a"
54<verb-perfective-indicative-future-pl-p1-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "ame"
55<verb-perfective-indicative-future-pl-p2-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "ate"
56<verb-perfective-indicative-future-pl-p3-g1-b> ::= <verb-prefix> <verb-stem-g1-b> "ajú"
57
58<verb-perfective-indicative-future-sg-p1-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "ím"
59<verb-perfective-indicative-future-sg-p2-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "íš"
60<verb-perfective-indicative-future-sg-p3-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "í"
61<verb-perfective-indicative-future-pl-p1-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "íme"
62<verb-perfective-indicative-future-pl-p2-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "íte"
63<verb-perfective-indicative-future-pl-p3-g2-a> ::= <verb-prefix> <verb-stem-g2-a> "ia"
64
65<verb-perfective-indicative-future-sg-p1-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "im"
66<verb-perfective-indicative-future-sg-p2-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "iš"
67<verb-perfective-indicative-future-sg-p3-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "i"
68<verb-perfective-indicative-future-pl-p1-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "ime"
69<verb-perfective-indicative-future-pl-p2-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "ite"
70<verb-perfective-indicative-future-pl-p3-g2-b> ::= <verb-prefix> <verb-stem-g2-b> "ia"
71
72<verb-perfective-indicative-future-sg-p1-g3> ::= <verb-prefix> <verb-stem-g3> "ujem"
73<verb-perfective-indicative-future-sg-p2-g3> ::= <verb-prefix> <verb-stem-g3> "uješ"
74<verb-perfective-indicative-future-sg-p3-g3> ::= <verb-prefix> <verb-stem-g3> "uje"
75<verb-perfective-indicative-future-pl-p1-g3> ::= <verb-prefix> <verb-stem-g3> "ujeme"
76<verb-perfective-indicative-future-pl-p2-g3> ::= <verb-prefix> <verb-stem-g3> "ujete"
77<verb-perfective-indicative-future-pl-p3-g3> ::= <verb-prefix> <verb-stem-g3> "ujú"
78
79<verb-perfective-indicative-future-sg-p1-g4> ::= <verb-prefix> <verb-stem-g4> "iem"
80<verb-perfective-indicative-future-sg-p2-g4> ::= <verb-prefix> <verb-stem-g4> "ieš"
81<verb-perfective-indicative-future-sg-p3-g4> ::= <verb-prefix> <verb-stem-g4> "ie"
82<verb-perfective-indicative-future-pl-p1-g4> ::= <verb-prefix> <verb-stem-g4> "ieme"
83<verb-perfective-indicative-future-pl-p2-g4> ::= <verb-prefix> <verb-stem-g4> "iete"
84<verb-perfective-indicative-future-pl-p3-g4> ::= <verb-prefix> <verb-stem-g4> "ejú"
85
86<verb-infinitive> ::= <verb-intinifive-g1> | <verb-intinifive-g2> | <verb-intinifive-g3> | <verb-intinifive-g4>
87<verb-intinifive-g1> ::= <verb-stem-g1> "ať"
88<verb-intinifive-g2> ::= <verb-stem-g2> "iť"
89<verb-intinifive-g3> ::= <verb-stem-g3> "ovať"
90<verb-intinifive-g4> ::= <verb-stem-g4> "ieť"
91
92<verb-stem> ::= <verb-stem-g1> | <verb-stem-g2> | <verb-stem-g3> | <verb-stem-g4> # ať | iť | ovať | ieť
93<verb-stem-g1> ::= <verb-stem-g1-a> | <verb-stem-g1-b>
94<verb-stem-g2> ::= <verb-stem-g2-a> | <verb-stem-g2-b>
95<verb-stem-g1-a> ::= "m" | "hľad" | "pozn" | "hr"
96<verb-stem-g1-b> ::= "čít" | "pláv" | "umýv" | "liet"
97<verb-stem-g2-a> ::= "rob" | "uč" | "var" | "lieč"
98<verb-stem-g2-b> ::= "kúp" | "ľúb" | "pál"
99<verb-stem-g3> ::= "kup" | "okup" | "poráb" | "vyráb" | "preráb" | "štud" | "prac" | "tanc" | "telefon" | "fotograf" | "mail" | "maľ"
100<verb-stem-g4> ::= "rozum" | "ved"
101
102<verb-prefix> ::= "u" | "na" | "vy" | "pre" | "po" | "pod" | "za" | "pri" | "o" | "ob"
103
104# NOTE(cmmm): modal verbs don't have prefixes
105# TODO(cmmm): separate modal verbs...
106# TODO(cmmm): ensure (using past tense conjugations for future tense)
107# budem rozumieť | budem sa rozumieť | porozumel by som | porozumel by som sa
108# 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
109# bude rozumieť | bude sa rozumieť | porozumel by | porozumela by | porozumelo by
110# budeme rozumieť | budeme sa rozumieť | budeme si rozumieť | porozumeli by sme | porozumeli by sme sa | porozumeli by sme si
111# budete rozumieť | budete sa rozumieť | budete si rozumieť | porozumeli by ste | porozumeli by ste sa | porozumeli by ste si
112# budú rozumieť | budú sa rozumieť | budú si rozumieť | porozumeli by sa | porozumeli by si
113# 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 @@
1#include "string-builder.h"
2#include <stdarg.h>
3#include <stdio.h>
4
5void
6string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n)
7{
8 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n);
9 memset (sb->items + sb->count, c, n);
10 sb->count += n;
11}
12
13void
14string_builder_append_cstrs (STRING_BUILDER sb, ...)
15{
16 va_list args;
17
18 va_start (args, sb);
19 const char *arg = va_arg (args, const char *);
20 while (arg) {
21 STRING_BUILDER_APPEND_CSTR(*sb, arg);
22 arg = va_arg (args, const char *);
23 } va_end (args);
24}
25
26void
27string_builder_printf (STRING_BUILDER sb, const char *format, ...)
28{
29 va_list args;
30
31 va_start (args, format);
32 int size = vsnprintf (NULL, 0, format, args);
33 va_end (args);
34 ASSERT (size >= 0);
35
36 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1);
37 va_start (args, format);
38 vsnprintf (&sb->items[sb->count], size + 1, format, args);
39 va_end (args);
40 sb->count += size;
41}
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 @@
1#ifndef INCLUDED_STRING_BUILDER_H
2#define INCLUDED_STRING_BUILDER_H
3
4#include <stddef.h>
5#include <string.h>
6#include "utils.h"
7#include "dynamic-array.h"
8
9struct string_builder {
10 union { char *items, *string; };
11 size_t count;
12 size_t capacity;
13};
14#define STRING_BUILDER struct string_builder *
15
16#define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \
17 DYNAMIC_ARRAY_APPEND (SB, CHAR)
18
19#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \
20 DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE)
21
22#define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \
23 ({ \
24 const char *s = (CSTR); \
25 size_t n = strlen (s); \
26 DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \
27 })
28
29#define STRING_BUILDER_APPEND_CSTRS(SB, ...) \
30 string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL)
31
32#define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV) \
33 DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).beg, STRING_VIEW_LEN (SV));
34
35#define STRING_BUILDER_APPEND_NULL(SB) \
36 DYNAMIC_ARRAY_APPEND (SB, '\0')
37
38#define STRING_BUILDER_RESET(SB) \
39 DYNAMIC_ARRAY_RESET (SB)
40
41#define STRING_BUILDER_FREE(SB) \
42 DYNAMIC_ARRAY_FREE(SB)
43
44extern void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n);
45extern void string_builder_append_cstrs (STRING_BUILDER, ...);
46extern void string_builder_printf (STRING_BUILDER, const char *format, ...);
47
48#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 @@
1#ifndef INCLUDED_STRING_VIEW_H
2#define INCLUDED_STRING_VIEW_H
3
4#include <string.h>
5
6struct string_view {
7 const char *beg;
8 const char *end;
9};
10
11#define STRING_VIEW_FROM_CSTR(CSTR) ((struct string_view) { .beg = (CSTR), .end = (CSTR) + strlen (CSTR) })
12#define STRING_VIEW_LEN(SV) ((SV).end - (SV).beg)
13#define STRING_VIEW_EQUALS(A, B) \
14 (STRING_VIEW_LEN (A) == STRING_VIEW_LEN (B) && \
15 !memcmp ((A).beg, (B).beg, STRING_VIEW_LEN (A)))
16
17#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 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <stdlib.h>
5#include <stdint.h>
6#include <stdio.h>
7#include <assert.h>
8
9#define UNUSED(X) ((void) (X))
10#define UNREACHABLE() ASSERT (!"reached the unreachable...")
11#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__)
12// #define TODO(...)
13#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
14
15#define ASSERT assert
16#define REALLOC realloc
17#define FREE free
18
19#define DIE(FMT, ...) \
20 ({ \
21 fprintf (stderr, FMT "\n" __VA_OPT__(,) __VA_ARGS__); \
22 exit (EXIT_FAILURE); \
23 })
24
25#define ARRAY_LEN(array) (sizeof (array)/sizeof (*array))
26#define ARRAY_GET(array, index) \
27 (ASSERT(index >= 0), ASSERT(index < ARRAY_LEN(array)), array[index])
28
29#define MIN(a, b) (((a) < (b)) ? (a) : (b))
30
31struct string_views {
32 struct string_view *items;
33 uint32_t count;
34 uint32_t capacity;
35};
36
37#endif