aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-08 08:19:44 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-08 08:23:19 +0000
commit5be0e39d0ce97849d7722bd1ac98563c7014faf3 (patch)
tree9dba821664337a6662a6da88dfe86291d269c36b
downloadlab-05-master.tar.gz
publishHEADmaster
-rw-r--r--.gitignore6
-rw-r--r--README.org130
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh14
-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.org763
-rw-r--r--doc/setup.org32
-rw-r--r--doc/spbstu-report.cls74
-rw-r--r--lib/bnf-mode.el40
-rw-r--r--src/bnf-lexeme.c10
-rw-r--r--src/bnf-lexeme.h36
-rw-r--r--src/bnf-lexer.c101
-rw-r--r--src/bnf-lexer.h18
-rw-r--r--src/bnf-parser.c213
-rw-r--r--src/bnf-parser.h52
-rw-r--r--src/dynamic-array.h59
-rw-r--r--src/main.c158
-rw-r--r--src/randomart-1.bnf10
-rw-r--r--src/randomart-2.bnf10
-rw-r--r--src/randomart-3.bnf10
-rw-r--r--src/string-view.h17
-rw-r--r--src/utils.h27
31 files changed, 2228 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..347a060
--- /dev/null
+++ b/README.org
@@ -0,0 +1,130 @@
1#+title: Grammar with semantics
2#+subtitle: Random-art generation
3#+date: 2025H1
4
5* Overview
6:PROPERTIES:
7:CUSTOM_ID: overview
8:END:
9- Augmented a standard context-free BNF grammar with production rule
10 weights (probabilities) to control expression generation density and
11 visual aesthetics.
12- Optimized and left-factorized the extended grammar to ensure
13 compatibility with deterministic parsing methods.
14- Implemented a custom C-based lexer and recursive descent parser to
15 process rules, terminals, nonterminals, and probabilities.
16- Engineered a stochastic expansion algorithm with depth thresholding
17 to synthesize complex GLSL fragment shaders driven by screen
18 coordinates, mouse input, and time.
19- Configured distinct semantic weight profiles to generate varying
20 aesthetic styles (smooth vs. noise-heavy procedural patterns).
21- Developed a custom GNU Emacs major mode (=bnf-mode.el=) for editing
22 BNF grammars.
23
24* Documentation
25:PROPERTIES:
26:CUSTOM_ID: documentation
27:END:
28The exported report can be found at [[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/report.pdf][this link]].
29
30* Showcase
31:PROPERTIES:
32:CUSTOM_ID: showcase
33:END:
34** Example 1
35:PROPERTIES:
36:CUSTOM_ID: example-1
37:UNNUMBERED: toc
38:END:
39*Input:*
40#+begin_src bnf
41 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | <trig> | 0 "abs(" <expr> ")" | "sqrt(abs(" <expr> "))"
42<value> ::= <coord> | 2 <mouse> | <time> | <const>
43<coord> ::= 4 "c.x" | 3 "c.y"
44<mouse> ::= 4 "m.x" | 3 "m.y"
45 <time> ::= "sin(t)" | 0 "cos(t)"
46<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
47<digit> ::= 2 "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
48<binop> ::= 10 "(" <expr> " + " <expr> ")" | 5 "(" <expr> " - " <expr> ")" | 3 <expr> "*" <expr> | 0 "(" <expr> "/" <expr> ")"
49 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | "tan(" <expr> ")"
50#+end_src
51
52*Output:*
53#+begin_src glsl
54(((((cos((tan(((cos(((((((cos(((((c.x + (((((sqrt(abs((((cos(sqrt(abs((sqrt(abs(tan(sin((((((((m.y*(sin((((((((((sqrt(abs(((( cos(((sqrt(abs(cos(c.x))) + ((((sqrt(abs(((m.y - ((((((.923344 - (.949094 + m.y)) + m.x) + sin(t)) - m.y)*m.x - sin(t)) + c.y)) - m.x)*sin(t))) - m.y) + m.y) + m.y)*m.y - sin(t))) - m.x)) + m.x) - sin(t)) + m.x))) - sin(t)) - m.x) + sin(t)) - .112088)*c.x - m.x) + .233916) - c.y) + m.x) + sin(t))) + m.x) + sin(t))*c.y*m.x + c.x) + .190365) - .887840) + sin(t)) + m.x) + m.y))*.291275))) - sin(t))))) + .287723) - m.x) - sin(t)))) - m.y) + sin(t))*c.x + m.y) + m.y) + .830306)*m.y*sin(t)) + c.y) + c.y)*m.y + c.x)) + m.x) - c.x) + m.x) - sin(t)) + c.y) + c.y)) + c.x) + c.y))*c.y*c.y + m.x)*.256283) - .585881) + .177134) + m.x) + c.x), (((((((((sqrt(abs(sin(((((((((cos((sqrt(abs((((((((((((sqrt(abs((((m.y - (sqrt(abs(m.x)) - sin((((((((m.x + ((((m.y - (((((((c.x + (((((((((m.x + .018174) - cos(sqrt(abs(((tan(m.x) - .689349) + m.x))))) - .420239) + m.x) + m.x) + sin(t)) + m.x) - m.x) + m.x)) - m.y)*sin(t) + sin(t)) + c.x) + .142664) - m.y) + m.x)) + c.x) + m.y)*.800054 - c.y)) - .509630) + m.y) - c.y) - sin(t))*m.x + .447933) - .237243)))) + m.x) + m.y)))*.733285 + c.x) - m.x) + m.x)*sin(t) + m.x) + .100814) + m.y) - m.x) - m.x) + sin(t)) + m.x) + .907417))) + m.y))*.388498 + sin(t)) + .016879) + c.y) + sin(t)) + .905070) - c.x) - c.x) + m.x)))) + .531642) - sin(t)) + m.y) + m.y) - .722737) + sin(t)) - c.y) - m.y) + m.x), sqrt(abs((m.x - tan(tan((sqrt(abs((((c.x - (((((((sin(sqrt(abs((sqrt(abs((((((m.y - (sin(((((sqrt(abs(((((sin(t) + (((((((((((((sin(t) - ((((((c.y*(((m.x + .127801) - (sqrt(abs((sin(t) + m.x))) + .900278)) + m.y)*m.y - m.x) + .191150) - m.x) + c.y)*sin(t) + .760660) + m.y)) + m.x) + m.y) - .470661) + .239425) + m.x) + m.y) - .085803) + m.x) - m.y) + m.x) + .304005) - .044509)) + m.x) + m.x) + c.x)*.156629)) - m.y) + m.x) - sin(t)) - m.x))*.501841 - m.x)) + m.y)*m.y + .098450) + m.x) - m.x))) + sin(t))))) - c.y) + m.y) + .005222)*m.y + m.x) + m.x) + .030531) + m.x)) + m.x) + c.x))) + m.x)))*c.x)))*m.x)
55#+end_src
56
57*Example frame:*
58#+attr_html: :width 100%
59[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/10.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/10.png]]
60
61** Example 2
62:PROPERTIES:
63:CUSTOM_ID: example-2
64:UNNUMBERED: toc
65:END:
66*Input:*
67#+begin_src bnf
68 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | 3 <trig> | 1 "abs(" <expr> ")" | 5 "sqrt(abs(" <expr> "))"
69<value> ::= 3 <coord> | <mouse> | <time> | <const>
70<coord> ::= 4 "c.x" | 3 "c.y"
71<mouse> ::= 4 "m.x" | 3 "m.y"
72 <time> ::= "sin(t)" | "cos(t)"
73<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
74<digit> ::= 10 "0" | 9 "1" | 8 "2" | 7 "3" | 6 "4" | 5 "5" | 4 "6" | 3 "7" | 2 "8" | 1 "9"
75<binop> ::= 1 "(" <expr> " + " <expr> ")" | 30 "(" <expr> " - " <expr> ")" | 5 <expr> "*" <expr> | 7 "(" <expr> "/" <expr> ")"
76 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | 0 "tan(" <expr> ")"
77#+end_src
78
79*Output:*
80#+begin_src glsl
81((sqrt(abs((sqrt(abs(sqrt(abs(((c.x/sqrt(abs(sqrt(abs(((((abs(((((((((abs(sqrt(abs(sin(((( cos(((cos(sqrt(abs(sqrt(abs(((sin((sqrt(abs(((sqrt(abs(sqrt(abs((((sqrt(abs((sqrt( abs((((sqrt(abs(sqrt(abs(((((((sqrt(abs(c.x))*(sqrt(abs((sqrt(abs(sin(abs((((c.x - (abs(abs((((sqrt(abs((sqrt(abs(sqrt(abs(((sqrt(abs((sin(sin(sin(((sin((cos(((cos(abs((( sqrt(abs(cos(c.x)))*cos((c.y - c.x)) - m.y) - c.x))) - c.x)/c.x)) - c.y)) - c.y) - sin(t)))))/.024006))) - c.x) - .183139))))) - m.x))) - c.y)/sin(t)) - sin(t)))) - sin(t))) - c.x) - m.y))))) - m.x))) - c.x) - c.x) - sin(t)) - c.x) - cos(t)) - c.y)/c.x)*m.x)))) - .223574) - c.x) - cos(t)))) - c.y)))/m.x) - c.x) - m.x))))) - c.x) - cos(t)))) - m.x)) - c.x) - c.x)))))) - c.x) - c.y)) - sin(t)) - .406444) - c.y))))) - m.y)/m.x) - c.x) - c.y)/cos(t))/.262350) - sin(t)) - c.y)) - c.x) - c.x)/c.x)/m.x)))))) - cos(t)))))) - c.x))) - c.x), cos(t), sin(((((((((cos(sqrt(abs((sqrt(abs(c.y)) - c.x)))) - (sqrt(abs((sqrt(abs(m.x)) - ((cos(sqrt(abs((m.y - c.y)))) - sqrt(abs(abs((sqrt(abs((((abs((sqrt(abs(sqrt(abs(cos((m.y - ((.254220 - (sqrt(abs(sqrt(abs(((m.y - sin(sqrt(abs((cos(sqrt(abs(sqrt(abs(sin(sqrt(abs(abs(sin(((((sqrt(abs(m.x)) - c.y)*.213340*c.x*cos(t) - .877721)/m.y) - .632123))))))))))) - c.x))))) - c.x))))) - cos(t))) + c.y))))))) - sin(t))) - c.y)/c.x) - c.x))) - c.y)))))*c.x - c.y))))/.123224))/m.x) - c.y)*.273026/c.x)/c.y) - cos(t)) - m.x)/m.y)))
82#+end_src
83
84*Example frame:*
85#+attr_html: :width 100%
86[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/13.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/13.png]]
87
88** Gallery
89:PROPERTIES:
90:CUSTOM_ID: gallery
91:UNNUMBERED: toc
92:END:
93#+attr_html: :width 100%
94[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/01.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/01.png]]
95
96#+attr_html: :width 100%
97[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/02.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/02.png]]
98
99#+attr_html: :width 100%
100[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/03.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/03.png]]
101
102#+attr_html: :width 100%
103[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/04.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/04.png]]
104
105#+attr_html: :width 100%
106[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/05.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/05.png]]
107
108#+attr_html: :width 100%
109[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/06.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/06.png]]
110
111#+attr_html: :width 100%
112[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/07.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/07.png]]
113
114#+attr_html: :width 100%
115[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/08.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/08.png]]
116
117#+attr_html: :width 100%
118[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/09.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/09.png]]
119
120#+attr_html: :width 100%
121[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/11.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/11.png]]
122
123#+attr_html: :width 100%
124[[https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/12.png][https://git.michalec.dev/files/uni/term-06/math-logic/lab-05/12.png]]
125
126* Unlicense
127:PROPERTIES:
128:CUSTOM_ID: unlicense
129:END:
130#+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/build.sh b/build.sh
new file mode 100755
index 0000000..2775702
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,14 @@
1#!/bin/sh
2
3set -xe
4
5mkdir -p ./build/
6
7# gcc ./src/bake-randomart-grammar.c -o ./build/bake-grammar
8# ./build/bake-grammar
9
10gcc -o ./build/main \
11 ./src/bnf-lexeme.c \
12 ./src/bnf-lexer.c \
13 ./src/bnf-parser.c \
14 ./src/main.c
diff --git a/doc/biblio.bib b/doc/biblio.bib
new file mode 100644
index 0000000..cc53e65
--- /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/algorithm/},
12urldate = {2024-12-01}
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..80d0b90
--- /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, position=below}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=below}
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..4f0d305
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,763 @@
1#+title: Оснащение грамматики семантикой
2#+subtitle: Генерация случайных изображений
3#+author: Михалец М.
4#+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №5}
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#+macro: caption @@latex:\vspace{0em}\captionof{listing}{$2\label{$1}}\vspace{0em}@@
15
16#+setupfile: setup.org
17#+latex: \sloppy
18#+latex: \setlength{\grammarparsep}{0pt}
19
20* ВВЕДЕНИЕ
21:PROPERTIES:
22:UNNUMBERED: t
23:END:
24В данной работе рассмотрена реализация грамматики с семантикой
25порождения случайных изображений в виде шейдера фрагментов.
26
27* Математическое описание
28/Случайное изображение/ -- случайным образом построенная функция, в
29данном случае 3 таких функции для каждой компоненты sRGB. На вход
30такой функции можно подавать произвольные количество значений, мы
31будем использовать канонические координаты фрагмента изображения $c$ и
32положения курсора $m$ и время $t$. Положение курсора сделает
33изображение реактивным, а время -- темпоральным.
34
35** Грамматика описывающая пространство порождаемых изображений
36Для описания пространства порождаемых изображений была за основу взята
37штатная грамматика BNF, которая представлена на рис. [[bnf-grammar]]. Для
38пояснения, \synt{EOF} означает конец файла, а \synt{EOL} -- конец
39строки.
40
41#+name: bnf-grammar
42#+caption: Грамматика BNF
43#+attr_latex: :options [H]
44#+begin_figure
45\setlength{\grammarindent}{9em}
46\begin{grammar}
47 <syntax> $::=$ <rule> <EOF> | <rule> <syntax>
48
49 <rule> $::=$ <opt-whitespace> `<' <rule-name> `>' <opt-whitespace> `::=' <opt-whitespace> <expression> <line-end>
50
51 <opt-whitespace> $::=$ ` ' <opt-whitespace> | $\varepsilon$
52
53 <expression> $::=$ <list> | <list> <opt-whitespace> `|' <opt-whitespace> <expression>
54
55 <line-end> $::=$ <opt-whitespace> <EOL> | <line-end> <line-end>
56
57 <list> $::=$ <term> | <term> <opt-whitespace> <list>
58
59 <term> $::=$ <literal> | `<' <rule-name> `>'
60
61 <literal> $::=$ `"' <text1> `"' | `\'' <text2> `\''
62
63 <text1> $::=$ $\varepsilon$ | <character1> <text1>
64
65 <text2> $::=$ $\varepsilon$ | <character2> <text2>
66
67 <character> $::=$ <letter> | <digit> | <symbol>
68
69 <letter> $::=$ `A' | `B' | `C' | `D' | `E' | `F' | `G' | `H' | `I' | `J' | `K' | `L' | `M' | `N' | `O' | `P' | `Q' | `R'
70 \alt `S' | `T' | `U' | `V' | `W' | `X' | `Y' | `Z' | `a' | `b' | `c' | `d' | `e' | `f' | `g' | `h' | `i' | `j'
71 \alt `k' | `l' | `m' | `n' | `o' | `p' | `q' | `r' | `s' | `t' | `u' | `v' | `w' | `x' | `y' | `z'
72
73 <digit> $::=$ `0' | `1' | `2' | `3' | `4' | `5' | `6' | `7' | `8' | `9'
74
75 <symbol> $::=$ `|' | ` ' | `!' | `#' | `\$' | `\%' | `&' | `(' | `)' | `*' | `+' | `,' | `-' | `.' | `/' | `:'
76 \alt `;' | `>' | `=' | `<' | `?' | `@' | `[' | `\\' | `]' | `^' | `\_' | \lit{\textasciigrave} | `{' | `}' | `~'
77
78 <character1> $::=$ <character> | `\''
79
80 <character2> $::=$ <character> | `"'
81
82 <rule-name> $::=$ <letter> | <rule-name> <rule-char>
83
84 <rule-char> $::=$ <letter> | <digit> | `-'
85\end{grammar}
86#+end_figure
87
88Если были бы всё продукции равноправными, было бы трудно управлять
89результатом порождаемых программ. Поэтому, BNF расширяется
90необязательным указанием вероятности использования продукции,
91посредством указания её объёма, в её начале. Если будет объём опущен,
92то оно принимает значение 1. Объём -- натуральное число или ноль,
93вероятность применения продукции -- отношение объёма продукции к сумме
94объёмов продукции нетерминала. Нужные расширения к BNF грамматике
95представлены на рис. [[bnf-grammar-extension]]. Таким образом
96пространство поражаемых изображений оснащается плотностью --
97производной Радона-Никодима.
98
99#+name: bnf-grammar-extension
100#+caption: Рассширение грамматики BNF
101#+attr_latex: :options [H]
102#+begin_figure
103\setlength{\grammarindent}{8em}
104\begin{grammar}
105 <expression> $::=$ <number> <list>
106 \alt <number> <list> <opt-whitespace> `|' <opt-whitespace> <expression>
107
108 <number> $::=$ <digit> | <digit> <number>
109\end{grammar}
110#+end_figure
111
112Полученная грамматика не является LL(1). Чтобы привести её,
113понадобится провести только факторизацию левых префиксов, так как в
114грамматике и так отсутствует левая рекурсия. Изменённые и новые
115правила представлены на рис. [[bnf-grammar-factorization]].
116
117#+name: bnf-grammar-factorization
118#+caption: Левая факторизация рассширённой грамматики BNF
119#+attr_latex: :options [H]
120#+begin_figure
121\setlength{\grammarindent}{8em}
122\begin{grammar}
123 <syntax> $::=$ <rule> <syntax'>
124
125 <syntax'> $::=$ <EOF> | <syntax>
126
127 <expression> $::=$ <number> <list> <expression'> | <list> <expression'>
128
129 <expression'> $::=$ $\varepsilon$ | <opt-whitespace> `|' <opt-whitespace> <expression>
130
131 <list> $::=$ <term> <list'>
132
133 <list'> $::=$ $\varepsilon$ | <opt-whitespace> <list>
134\end{grammar}
135#+end_figure
136
137По такой грамматике уже можно построить таблицу выбора, но мы её не
138будем приводит, поскольку она получится громоздкой.
139
140** Пример грамматики
141Данная грамматика позволяет описать простые выражения с константами,
142координатами фрагмента и курсора на экране, времени и бинарными,
143тригонометрическими и другими функциями над ними.
144
145#+begin_export latex
146\setlength{\grammarindent}{8em}
147\begin{grammar}
148 <expr> $::=$ \[[
149 \begin{stack}
150 $\overset{y_1}{\triangle}$ <value> \\
151 $\overset{y_2}{\triangle}$ `-' <expr> \\
152 $\overset{y_3}{\triangle}$ <binop> \\
153 $\overset{y_4}{\triangle}$ <trig> \\
154 $\overset{y_5}{\triangle}$ `abs(' <expr> `)' \\
155 $\overset{y_6}{\triangle}$ `sqrt(abs(' <expr> `))'
156 \end{stack}
157 \]]
158
159 <value> $::=$ \[[
160 \begin{stack}
161 $\overset{y_7}{\triangle}$ <coord> \\
162 $\overset{y_8}{\triangle}$ <mouse> \\
163 $\overset{y_9}{\triangle}$ <time> \\
164 $\overset{y_{10}}{\triangle}$ <const>
165 \end{stack}
166 \]]
167
168 <coord> $::=$ \[[
169 \begin{stack}
170 $\overset{y_{11}}{\triangle}$ `c.x' \\
171 $\overset{y_{12}}{\triangle}$ `c.y'
172 \end{stack}
173 \]]
174
175 <mouse> $::=$ \[[
176 \begin{stack}
177 $\overset{y_{13}}{\triangle}$ `m.x' \\
178 $\overset{y_{14}}{\triangle}$ `m.y'
179 \end{stack}
180 \]]
181
182 <time> $::=$ \[[
183 \begin{stack}
184 $\overset{y_{15}}{\triangle}$ `sin(t)' \\
185 $\overset{y_{16}}{\triangle}$ `cos(t)'
186 \end{stack}
187 \]]
188
189 <const> $::=$ \[[
190 $\overset{y_{17}}{\triangle}$ `.' <digit> <digit> <digit> <digit> <digit> <digit>
191 \]]
192
193 <digit> $::=$ \[[
194 \begin{stack}
195 $\overset{y_{18}}{\triangle}$ `0' \\
196 $\overset{y_{19}}{\triangle}$ `1' \\
197 $\overset{y_{20}}{\triangle}$ `2' \\
198 $\overset{y_{21}}{\triangle}$ `3' \\
199 $\overset{y_{22}}{\triangle}$ `4' \\
200 $\overset{y_{23}}{\triangle}$ `5' \\
201 $\overset{y_{24}}{\triangle}$ `6' \\
202 $\overset{y_{25}}{\triangle}$ `7' \\
203 $\overset{y_{26}}{\triangle}$ `8' \\
204 $\overset{y_{27}}{\triangle}$ `9'
205 \end{stack}
206 \]]
207
208 <binop> $::=$ \[[
209 \begin{stack}
210 $\overset{y_{28}}{\triangle}$ `(' <expr> ` + ' <expr> `)' \\
211 $\overset{y_{29}}{\triangle}$ `(' <expr> ` - ' <expr> `)' \\
212 $\overset{y_{30}}{\triangle}$ <expr> ` * ' <expr> \\
213 $\overset{y_{31}}{\triangle}$ <expr> ` / ' <expr>
214 \end{stack}
215 \]]
216
217 <trig> $::=$ \[[
218 \begin{stack}
219 $\overset{y_{32}}{\triangle}$ `sin(' <expr> `)' \\
220 $\overset{y_{33}}{\triangle}$ `cos(' <expr> `)' \\
221 $\overset{y_{34}}{\triangle}$ `tan(' <expr> `)'
222 \end{stack}
223 \]]
224\end{grammar}
225#+end_export
226
227Дальше можно назначить разные семантики одной и той же грамматике и
228получить сильно отличающиеся результаты.
229
230*** Семантика 1
231Данная семантика генерирует довольно плавне переходы за счёт большой
232вероятности у бинарных операции и сложения и отсутствии деления.
233
234#+begin_export latex
235\begin{displaymath}
236 \begin{array}{lc@{}>{\hspace*{1cm}}clc@{}>{\hspace*{1cm}}clc}
237 y_{ 1}: & \verb#p[0][0] = 1# & & y_{13}: & \verb#p[3][0] = 4# & & y_{24}: & \verb#p[6][6] = 1# \\
238 y_{ 2}: & \verb#p[0][1] = 0# & & y_{14}: & \verb#p[3][1] = 3# & & y_{25}: & \verb#p[6][7] = 1# \\
239 y_{ 3}: & \verb#p[0][2] = 10# & & y_{15}: & \verb#p[4][0] = 1# & & y_{26}: & \verb#p[6][8] = 1# \\
240 y_{ 4}: & \verb#p[0][3] = 1# & & y_{16}: & \verb#p[4][1] = 0# & & y_{27}: & \verb#p[6][9] = 1# \\
241 y_{ 5}: & \verb#p[0][4] = 0# & & y_{17}: & \verb#p[5][0] = 1# & & y_{28}: & \verb#p[7][0] = 10# \\
242 y_{ 6}: & \verb#p[0][1] = 1# & & y_{18}: & \verb#p[6][0] = 2# & & y_{29}: & \verb#p[7][1] = 5# \\
243 y_{ 7}: & \verb#p[1][0] = 1# & & y_{19}: & \verb#p[6][1] = 1# & & y_{30}: & \verb#p[7][2] = 3# \\
244 y_{ 8}: & \verb#p[1][1] = 2# & & y_{20}: & \verb#p[6][2] = 1# & & y_{31}: & \verb#p[7][3] = 0# \\
245 y_{ 9}: & \verb#p[1][2] = 1# & & y_{21}: & \verb#p[6][3] = 1# & & y_{32}: & \verb#p[8][0] = 1# \\
246 y_{10}: & \verb#p[1][3] = 1# & & y_{22}: & \verb#p[6][4] = 1# & & y_{33}: & \verb#p[8][1] = 1# \\
247 y_{11}: & \verb#p[2][0] = 4# & & y_{23}: & \verb#p[6][5] = 1# & & y_{34}: & \verb#p[8][2] = 1# \\
248 y_{12}: & \verb#p[2][1] = 3#
249 \end{array}
250\end{displaymath}
251#+end_export
252
253*** Семантика 2
254Данная семантика генерирует более шумные изображения за счёт большой
255вероятности деления и повышенной вероятности тригонометрических
256функций.
257
258#+begin_export latex
259\begin{displaymath}
260 \begin{array}{lc@{}>{\hspace*{1cm}}clc@{}>{\hspace*{1cm}}clc}
261 y_{ 1}: & \verb#p[0][0] = 1# & & y_{13}: & \verb#p[3][0] = 4# & & y_{24}: & \verb#p[6][6] = 4# \\
262 y_{ 2}: & \verb#p[0][1] = 0# & & y_{14}: & \verb#p[3][1] = 3# & & y_{25}: & \verb#p[6][7] = 3# \\
263 y_{ 3}: & \verb#p[0][2] = 10# & & y_{15}: & \verb#p[4][0] = 1# & & y_{26}: & \verb#p[6][8] = 2# \\
264 y_{ 4}: & \verb#p[0][3] = 3# & & y_{16}: & \verb#p[4][1] = 1# & & y_{27}: & \verb#p[6][9] = 1# \\
265 y_{ 5}: & \verb#p[0][4] = 1# & & y_{17}: & \verb#p[5][0] = 1# & & y_{28}: & \verb#p[7][0] = 1# \\
266 y_{ 6}: & \verb#p[0][1] = 5# & & y_{18}: & \verb#p[6][0] = 10# & & y_{29}: & \verb#p[7][1] = 30# \\
267 y_{ 7}: & \verb#p[1][0] = 3# & & y_{19}: & \verb#p[6][1] = 9# & & y_{30}: & \verb#p[7][2] = 5# \\
268 y_{ 8}: & \verb#p[1][1] = 1# & & y_{20}: & \verb#p[6][2] = 8# & & y_{31}: & \verb#p[7][3] = 7# \\
269 y_{ 9}: & \verb#p[1][2] = 1# & & y_{21}: & \verb#p[6][3] = 7# & & y_{32}: & \verb#p[8][0] = 1# \\
270 y_{10}: & \verb#p[1][3] = 1# & & y_{22}: & \verb#p[6][4] = 6# & & y_{33}: & \verb#p[8][1] = 1# \\
271 y_{11}: & \verb#p[2][0] = 4# & & y_{23}: & \verb#p[6][5] = 5# & & y_{34}: & \verb#p[8][2] = 0# \\
272 y_{12}: & \verb#p[2][1] = 3#
273 \end{array}
274\end{displaymath}
275#+end_export
276
277* Программная реализация
278** Синтаксический анализ
279*** Перечисление лексем
280#+begin_src c
281#define BNF_LEXEME_KINDS() \
282 X (TERMINAL, "\"[^\"]*\"|'[^']*'") \
283 X (NONTERMINAL, "<[^>]*>" ) \
284 X (PROBABILITY, "[0-9]+" ) \
285 X (SYMBOL_ALTERNATIVE, "\\|" ) \
286 X (SYMBOL_IS_REPLACED_BY, "::=" ) \
287 X (COMMENT, "#[^\n]*" )
288
289#define X(SYM, ...) BNF_LEXEME_KIND_##SYM,
290enum bnf_lexeme_kind {
291 BNF_LEXEME_KINDS ()
292 BNF_LEXEME_KIND_END_OF_LINE,
293 BNF_LEXEME_KIND_END_OF_FILE,
294 BNF_LEXEME_KIND_INVALID,
295 BNF_LEXEME_KIND_COUNT
296};
297#undef X
298#+end_src
299
300*** Функция разбора лексемы
301Читает лексему, если она не определённого типа, откатывает.
302- Вход: :: лексический анализатор, тип лексемы.
303- Выход: :: Истина и лексема съедена, или ложь.
304#+begin_src c
305bool
306bnf_parse_lexeme (struct bnf_lexer *lexer, enum bnf_lexeme_kind kind)
307{
308 const char *checkpoint = lexer->cursor;
309 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
310
311 if (lexeme.kind != kind) goto revert;
312
313 return true;
314
315revert:
316 lexer->cursor = checkpoint;
317 return false;
318}
319#+end_src
320
321*** Функция разбора нетерминала
322Читает лексему, если она не нетерминал, откатывает.
323- Вход: :: лексический анализатор.
324- Выход: :: лексема.
325#+begin_src c
326struct bnf_lexeme
327bnf_parse_nonterminal (struct bnf_lexer *lexer)
328{
329 const char *checkpoint = lexer->cursor;
330 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
331 if (lexeme.kind == BNF_LEXEME_KIND_NONTERMINAL)
332 return lexeme;
333
334revert:
335 lexer->cursor = checkpoint;
336 return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID };
337}
338#+end_src
339
340*** Функция разбора терминала
341Читает лексему, если она не терминал, откатывает.
342- Вход: :: лексический анализатор.
343- Выход: :: лексема.
344#+begin_src c
345struct bnf_lexeme
346bnf_parse_terminal (struct bnf_lexer *lexer)
347{
348 const char *checkpoint = lexer->cursor;
349
350 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
351 if (lexeme.kind == BNF_LEXEME_KIND_TERMINAL)
352 return lexeme;
353
354revert:
355 lexer->cursor = checkpoint;
356 return (struct bnf_lexeme) { .kind = BNF_LEXEME_KIND_INVALID };
357}
358#+end_src
359
360*** Функция разбора вероятности
361Читает лексему, если она не вероятность, откатывает и вероятность
362принимается за 1.
363- Вход: :: лексический анализатор.
364- Выход: :: вероятность.
365#+begin_src c
366uint32_t
367bnf_parse_probability (struct bnf_lexer *lexer)
368{
369 const char *checkpoint = lexer->cursor;
370
371 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
372 if (lexeme.kind == BNF_LEXEME_KIND_PROBABILITY) {
373 uint32_t probability = 0;
374 while (lexeme.sv.beg != lexeme.sv.end) {
375 probability *= 10;
376 probability += *lexeme.sv.beg++ - '0';
377 }
378 return probability;
379 }
380
381revert:
382 lexer->cursor = checkpoint;
383 return 1;
384}
385#+end_src
386
387*** Функция разбора альтернативы
388Разбирает вероятность и термы, при несоответствий откатывает.
389- Вход: :: лексический анализатор.
390- Выход: :: альтернатива.
391#+begin_src c
392struct bnf_sequence
393bnf_parse_sequence (struct bnf_lexer *lexer)
394{
395 struct bnf_sequence sequence = {0};
396 const char *checkpoint = lexer->cursor;
397
398 sequence.probability = bnf_parse_probability (lexer);
399
400 for (;;) {
401 struct bnf_lexeme lexeme = bnf_parse_nonterminal (lexer);
402 if (!is_bnf_lexeme_valid (lexeme))
403 lexeme = bnf_parse_terminal (lexer);
404 if (!is_bnf_lexeme_valid (lexeme))
405 break;
406
407 DYNAMIC_ARRAY_APPEND (sequence, lexeme);
408 } if (!is_bnf_sequence_valid (sequence)) goto revert;
409
410 if (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_ALTERNATIVE) ||
411 bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE))
412 return sequence;
413
414revert:
415 DYNAMIC_ARRAY_FREE (sequence);
416 lexer->cursor = checkpoint;
417 return (struct bnf_sequence) {0};
418}
419#+end_src
420
421*** Функция разбора правила
422Разбирает нетерминал, ~::=~ и альтернативы, при несоответствий откатывает.
423- Вход: :: лексический анализатор.
424- Выход: :: правило.
425#+begin_src c
426struct bnf_rule
427bnf_parse_rule (struct bnf_lexer *lexer)
428{
429 struct bnf_rule rule = {0};
430 const char *checkpoint = lexer->cursor;
431
432 rule.name = bnf_parse_nonterminal (lexer);
433 if (!is_bnf_lexeme_valid (rule.name))
434 goto revert;
435
436 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_IS_REPLACED_BY))
437 goto revert;
438
439 for (;;) {
440 struct bnf_sequence sequence = bnf_parse_sequence (lexer);
441 if (!is_bnf_sequence_valid (sequence)) break;
442 DYNAMIC_ARRAY_APPEND (rule.is_replaced_by, sequence);
443 } if (is_bnf_rule_valid (rule)) return rule;
444
445revert:
446 DYNAMIC_ARRAY_FREE (rule.is_replaced_by);
447 lexer->cursor = checkpoint;
448 return (struct bnf_rule) {0};
449}
450#+end_src
451
452*** Функция разбора синтаксиса
453Разбирает правила разделённые новыми строками, пока не придёт до конца
454файла. При несоответствий откатывает.
455- Вход: :: лексический анализатор.
456- Выход: :: синтаксис.
457#+begin_src c
458struct bnf_syntax
459bnf_parse_syntax (struct bnf_lexer *lexer)
460{
461 struct bnf_syntax syntax = {0};
462
463 for (;;) {
464 while (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE));
465 struct bnf_rule rule = bnf_parse_rule (lexer);
466 if (!is_bnf_rule_valid (rule)) {
467 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_FILE)) {
468 print_error (lexer, lexer->cursor, "unable to parse rule");
469 }
470 break;
471 }
472
473 DYNAMIC_ARRAY_APPEND (syntax, rule);
474 }
475
476 return syntax;
477}
478#+end_src
479
480*** Функция проверки синтаксиса
481Удостоверяет, что для каждого нетерминала есть правило.
482- Вход: :: лексический анализатор, синтаксис.
483- Выход: :: ложь, если для какого-либо нетерминала отсутствует
484 продукция, иначе истина.
485#+begin_src c
486bool
487bnf_check_syntax (struct bnf_lexer *lexer, struct bnf_syntax syntax)
488{
489 bool no_errors = true;
490 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
491 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
492 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
493 if (term->kind != BNF_LEXEME_KIND_NONTERMINAL) continue;
494 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) continue;
495 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) continue;
496
497 bool rule_found = false;
498 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
499 if (!STRING_VIEW_EQUALS (rule->name.sv, term->sv)) continue;
500 rule_found = true;
501 break;
502 }
503
504 if (!rule_found) {
505 no_errors = false;
506 print_error (lexer, term->sv.beg,
507 "rule not found: %.*s",
508 (int) STRING_VIEW_LEN (term->sv), term->sv.beg);
509 }
510 }
511 }
512 }
513
514 return no_errors;
515}
516#+end_src
517
518** Генератор
519*** Функция печати случайного раскрытия нетерминала
520По весам альтернатив, случайно применяет продукции к нетерминалам,
521пока они есть, получившиеся терминалы печатает.
522- Вход: :: файл, синтаксис, строка нетерминала.
523- Выход: :: в файл распечатано случайное раскрытие нетерминала.
524#+begin_src c
525static void
526print_random_nonterminal_expansion (FILE *fp,
527 struct bnf_syntax syntax,
528 struct string_view sv)
529{
530 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
531 if (!STRING_VIEW_EQUALS (rule->name.sv, sv)) continue;
532
533 uint32_t total_probability = 0;
534 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by)
535 total_probability += sequence->probability;
536 uint32_t selection = rand () % total_probability;
537 uint32_t sequence = 0;
538 for (uint32_t probability = rule->is_replaced_by.items[sequence].probability;
539 selection >= probability;
540 probability += rule->is_replaced_by.items[sequence].probability) {
541 sequence += 1;
542 }
543
544 DYNAMIC_ARRAY_FOREACH (term, rule->is_replaced_by.items[sequence])
545 print_term (fp, syntax, *term);
546
547 return;
548 }
549}
550#+end_src
551
552*** Функция печати терминала
553Печатает терминал.
554- Вход: :: файл, строка терминала.
555- Выход: :: в файл распечатан терминал.
556#+begin_src c
557static void
558print_terminal (FILE *fp, struct string_view sv)
559{
560 sv.beg += 1;
561 sv.end -= 1;
562 fprintf (fp, "%.*s", (int) STRING_VIEW_LEN (sv), sv.beg);
563}
564#+end_src
565
566*** Функция печати терма
567Печатает терм, используя функции определены выше, с особой обработкой
568нетерминалов =<EOL>= и =<EOF>= и применением ограничения роста выражения.
569- Вход: :: файл, синтаксис, строка терма.
570- Выход: :: в файл распечатан терм, со случайным раскрытием
571 нетерминалов и ограничением количества.
572#+begin_src c
573static int term_count = 0;
574static void
575print_term (FILE *fp, struct bnf_syntax syntax, struct bnf_lexeme term)
576{
577 switch (term.kind) {
578 case BNF_LEXEME_KIND_TERMINAL:
579 print_terminal (fp, term.sv);
580 break;
581 case BNF_LEXEME_KIND_NONTERMINAL:
582 if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) {
583 fprintf (fp, "\n");
584 } else if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) {
585 } else {
586 if (term_count > TERM_TRESHOLD &&
587 STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<expr>"))) {
588 print_random_nonterminal_expansion (fp, syntax, STRING_VIEW_FROM_CSTR ("<value>"));
589 } else {
590 print_random_nonterminal_expansion (fp, syntax, term.sv);
591 }
592 } break;
593 default: UNREACHABLE ();
594 }
595
596 term_count += 1;
597}
598#+end_src
599
600#+latex: \clearpage
601** Шаблон шейдера фрагментов
602В данный шаблон подставляются 3 компоненты цвета sRGB.
603#+begin_src glsl
604#version 330 core
605
606uniform float time;
607uniform vec2 resolution;
608uniform vec2 mouse;
609uniform float zoom;
610
611out vec4 color;
612
613void
614main ()
615{
616 float z = zoom;
617 vec2 c = gl_FragCoord.xy/resolution*2*z - z;
618 vec2 m = mouse/resolution;
619 float t = time*0.25;
620
621 vec3 g = vec3 (%s, %s, %s);
622 color = vec4 ((g + z)/2/z, 1);
623}
624#+end_src
625
626* Результаты программы
627** Семантика 1
628*Вход:*
629#+begin_src bnf
630# randomart.bnf -- syntax with semantics for generating random art -*- BNF -*-
631 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | <trig> | 0 "abs(" <expr> ")" | "sqrt(abs(" <expr> "))"
632<value> ::= <coord> | 2 <mouse> | <time> | <const>
633<coord> ::= 4 "c.x" | 3 "c.y"
634<mouse> ::= 4 "m.x" | 3 "m.y"
635 <time> ::= "sin(t)" | 0 "cos(t)"
636<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
637<digit> ::= 2 "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
638<binop> ::= 10 "(" <expr> " + " <expr> ")" | 5 "(" <expr> " - " <expr> ")" | 3 <expr> "*" <expr> | 0 "(" <expr> "/" <expr> ")"
639 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | "tan(" <expr> ")"
640#+end_src
641
642*Выход:*
643#+attr_latex: :options linenos=false
644#+begin_src glsl
645(((((cos((tan(((cos(((((((cos(((((c.x + (((((sqrt(abs(((( cos(sqrt(abs((sqrt(abs(tan(sin((((((((m.y*(sin((((((((((sqrt(abs(((( cos(((sqrt(abs(cos(c.x))) + ((((sqrt(abs(((m.y - ((((((.923344 - (.949094 + m.y)) + m.x) + sin(t)) - m.y)*m.x - sin(t)) + c.y)) - m.x)*sin(t))) - m.y) + m.y) + m.y)*m.y - sin(t))) - m.x)) + m.x) - sin(t)) + m.x))) - sin(t)) - m.x) + sin(t)) - .112088)*c.x - m.x) + .233916) - c.y) + m.x) + sin(t))) + m.x) + sin(t))*c.y*m.x + c.x) + .190365) - .887840) + sin(t)) + m.x) + m.y))*.291275))) - sin(t))))) + .287723) - m.x) - sin(t)))) - m.y) + sin(t))*c.x + m.y) + m.y) + .830306)*m.y*sin(t)) + c.y) + c.y)*m.y + c.x)) + m.x) - c.x) + m.x) - sin(t)) + c.y) + c.y)) + c.x) + c.y))*c.y*c.y + m.x)*.256283) - .585881) + .177134) + m.x) + c.x), (((((((((sqrt(abs(sin(((((((((cos((sqrt(abs((((((((((((sqrt(abs((((m.y - (sqrt(abs(m.x)) - sin((((((((m.x + ((((m.y - (((((((c.x + (((((((((m.x + .018174) - cos(sqrt(abs(((tan(m.x) - .689349) + m.x))))) - .420239) + m.x) + m.x) + sin(t)) + m.x) - m.x) + m.x)) - m.y)*sin(t) + sin(t)) + c.x) + .142664) - m.y) + m.x)) + c.x) + m.y)*.800054 - c.y)) - .509630) + m.y) - c.y) - sin(t))*m.x + .447933) - .237243)))) + m.x) + m.y)))*.733285 + c.x) - m.x) + m.x)*sin(t) + m.x) + .100814) + m.y) - m.x) - m.x) + sin(t)) + m.x) + .907417))) + m.y))*.388498 + sin(t)) + .016879) + c.y) + sin(t)) + .905070) - c.x) - c.x) + m.x)))) + .531642) - sin(t)) + m.y) + m.y) - .722737) + sin(t)) - c.y) - m.y) + m.x), sqrt(abs((m.x - tan(tan((sqrt(abs((((c.x - (((((((sin(sqrt(abs((sqrt(abs((((((m.y - (sin(((((sqrt(abs(((((sin(t) + (((((((((((((sin(t) - ((((((c.y*(((m.x + .127801) - (sqrt(abs((sin(t) + m.x))) + .900278)) + m.y)*m.y - m.x) + .191150) - m.x) + c.y)*sin(t) + .760660) + m.y)) + m.x) + m.y) - .470661) + .239425) + m.x) + m.y) - .085803) + m.x) - m.y) + m.x) + .304005) - .044509)) + m.x) + m.x) + c.x)*.156629)) - m.y) + m.x) - sin(t)) - m.x))*.501841 - m.x)) + m.y)*m.y + .098450) + m.x) - m.x))) + sin(t))))) - c.y) + m.y) + .005222)*m.y + m.x) + m.x) + .030531) + m.x)) + m.x) + c.x))) + m.x)))*c.x)))*m.x)
646#+end_src
647
648#+latex: \clearpage
649*Изображение:*
650#+attr_latex: :options [H]
651[[./img/10.png]]
652
653** Семантика 2
654*Вход:*
655#+begin_src bnf
656# randomart.bnf -- syntax with semantics for generating random art -*- BNF -*-
657 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | 3 <trig> | 1 "abs(" <expr> ")" | 5 "sqrt(abs(" <expr> "))"
658<value> ::= 3 <coord> | <mouse> | <time> | <const>
659<coord> ::= 4 "c.x" | 3 "c.y"
660<mouse> ::= 4 "m.x" | 3 "m.y"
661 <time> ::= "sin(t)" | "cos(t)"
662<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
663<digit> ::= 10 "0" | 9 "1" | 8 "2" | 7 "3" | 6 "4" | 5 "5" | 4 "6" | 3 "7" | 2 "8" | 1 "9"
664<binop> ::= 1 "(" <expr> " + " <expr> ")" | 30 "(" <expr> " - " <expr> ")" | 5 <expr> "*" <expr> | 7 "(" <expr> "/" <expr> ")"
665 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | 0 "tan(" <expr> ")"
666#+end_src
667
668#+latex: \clearpage
669*Выход:*
670#+attr_latex: :options linenos=false
671#+begin_src glsl
672((sqrt(abs((sqrt(abs(sqrt(abs(((c.x/sqrt(abs(sqrt(abs(((((abs(((((((((abs(sqrt(abs(sin(((( cos(((cos(sqrt(abs(sqrt(abs(((sin((sqrt(abs(((sqrt(abs(sqrt(abs((((sqrt(abs((sqrt( abs((((sqrt(abs(sqrt(abs(((((((sqrt(abs(c.x))*(sqrt(abs((sqrt(abs(sin(abs((((c.x - (abs(abs((((sqrt(abs((sqrt(abs(sqrt(abs(((sqrt(abs((sin(sin(sin(((sin((cos(((cos(abs((( sqrt(abs(cos(c.x)))*cos((c.y - c.x)) - m.y) - c.x))) - c.x)/c.x)) - c.y)) - c.y) - sin(t)))))/.024006))) - c.x) - .183139))))) - m.x))) - c.y)/sin(t)) - sin(t)))) - sin(t))) - c.x) - m.y))))) - m.x))) - c.x) - c.x) - sin(t)) - c.x) - cos(t)) - c.y)/c.x)*m.x)))) - .223574) - c.x) - cos(t)))) - c.y)))/m.x) - c.x) - m.x))))) - c.x) - cos(t)))) - m.x)) - c.x) - c.x)))))) - c.x) - c.y)) - sin(t)) - .406444) - c.y))))) - m.y)/m.x) - c.x) - c.y)/cos(t))/.262350) - sin(t)) - c.y)) - c.x) - c.x)/c.x)/m.x)))))) - cos(t)))))) - c.x))) - c.x), cos(t), sin(((((((((cos(sqrt(abs((sqrt(abs(c.y)) - c.x)))) - (sqrt(abs((sqrt(abs(m.x)) - ((cos(sqrt(abs((m.y - c.y)))) - sqrt(abs(abs((sqrt(abs((((abs((sqrt(abs(sqrt(abs(cos((m.y - ((.254220 - (sqrt(abs(sqrt(abs(((m.y - sin(sqrt(abs((cos(sqrt(abs(sqrt(abs(sin(sqrt(abs(abs(sin(((((sqrt(abs(m.x)) - c.y)*.213340*c.x*cos(t) - .877721)/m.y) - .632123))))))))))) - c.x))))) - c.x))))) - cos(t))) + c.y))))))) - sin(t))) - c.y)/c.x) - c.x))) - c.y)))))*c.x - c.y))))/.123224))/m.x) - c.y)*.273026/c.x)/c.y) - cos(t)) - m.x)/m.y)))
673#+end_src
674
675*Изображение:*
676#+attr_latex: :options [H]
677[[./img/13.png]]
678
679* ЗАКЛЮЧЕНИЕ
680:PROPERTIES:
681:UNNUMBERED: t
682:END:
683Сгенерированные шейдеры можно было бы применить в качестве реактивного
684фона рабочего стола, сайта или меню в игре, текстуры объекта,
685скайбокса или для художественной визуализации музыки в реальном
686времени.
687
688Поскольку язык основан на нотации БНФ, с малыми изменениями, он также
689относится к классу контекстно-свободных. Синтаксический анализатор
690реализован методом рекурсивного спуска в соответствии с правилами
691получившейся LL(1)-грамматики.
692
693Также было реализовано описание мажорного мода GNU Emacs для работы с
694БНФ грамматиками, его можно найти в приложений [[#A][А]].
695
696В приложений [[#B][Б]] представлена галерея различных получившихся
697изображений.
698
699*Достоинства:*
700- грамматика была приведена к LL(1);
701- автоматическое ограничение размера генерируемых функции;
702- сгенерированные шейдеры получились действительно интересными.
703
704*Недостатки:*
705- заметно, что составляющие цвета независимы;
706- синтаксический анализатор написан вручную, методом рекурсивного
707 спуска, из-за чего не получится над грамматикой провести операции в
708 автоматизированном порядке.
709
710*Масштабируемость:*
711- генерировать координаты в цветовом пространстве Oklab, возможно с одной
712 фиксированной координатой, вместо sRGB;
713- реализовать графическое описание грамматики генератора, для более
714 наглядной настройки вероятностей.
715
716* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
717:PROPERTIES:
718:UNNUMBERED: t
719:END:
720#+latex: \nocite{VOSTROV2024}
721#+print_bibliography: :heading none
722
723* ПРИЛОЖЕНИЕ А
724:PROPERTIES:
725:UNNUMBERED: t
726:CUSTOM_ID: A
727:END:
728#+include: "../lib/bnf-mode.el" src emacs-lisp
729
730* ПРИЛОЖЕНИЕ Б
731:PROPERTIES:
732:UNNUMBERED: t
733:CUSTOM_ID: B
734:END:
735[[./img/01.png]]
736
737[[./img/02.png]]
738
739[[./img/03.png]]
740
741[[./img/04.png]]
742
743[[./img/05.png]]
744
745[[./img/06.png]]
746
747[[./img/07.png]]
748
749[[./img/09.png]]
750
751[[./img/11.png]]
752
753[[./img/12.png]]
754
755[[./img/08.png]]
756
757[[./img/14.png]]
758
759# Local Variables:
760# org-confirm-babel-evaluate: nil
761# org-export-async-init-file: "ox-init.el"
762# org-export-in-background: t
763# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..d41fad7
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,32 @@
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{floatrow}
20#+latex_header: \usepackage[newfloat]{minted}
21#+latex_header: \usemintedstyle{bw}
22#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors,obeytabs}
23
24#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
25
26#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
27#+latex_header: \setmainfont{Times New Roman}
28#+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff]
29
30#+latex_header: \usepackage{tikz}
31#+latex_header: \usepackage{pgfplots}
32#+latex_header: \usepackage[rounded]{syntax}
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls
new file mode 100644
index 0000000..8274d3c
--- /dev/null
+++ b/doc/spbstu-report.cls
@@ -0,0 +1,74 @@
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
19\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
20\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}}
21\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}}
22\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}}
23\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}}
24\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
25\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
26\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
27\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
28\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}}
29\renewcommand{\maketitle}{
30 \begin{titlepage}
31 \begin{center}
32 \vspace{2cm}
33 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
34
35 \normalsize{\@university}
36
37 \vspace{0.5cm}
38 \normalsize{\@institute}
39
40 \normalsize{\@school}
41
42 \normalsize{Направление \@direction}
43
44 \vspace{2cm}
45 \LARGE{ОТЧЁТ}
46
47 \normalsize{\@reportof}
48
49 \large{\@subject}
50
51 \large{\textit{\@title}}
52 \end{center}
53
54 \vspace{3cm}
55 \small{
56 \begin{tabular}{lrrl}
57 \!\!\!Студент, & \hspace{2cm} & & \\
58 \!\!\!группы 5130201/20102 & & \underline{\hspace{3cm}} & \@author \\\\
59 \!\!\!Преподаватель, & \hspace{2cm} & \\
60 \!\!\!\@reviewertitle & & \underline{\hspace{3cm}} & \@reviewer \\\\
61 &&\hspace{5cm}
62 \end{tabular}
63 \begin{flushright}
64 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
65 \end{flushright}
66 }
67
68 \vspace*{\fill}
69 \begin{center}
70 \small{\@city, \@date}
71 \end{center}
72 \end{titlepage}
73 \setcounter{page}{2}
74}
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..8b01708
--- /dev/null
+++ b/src/bnf-lexeme.h
@@ -0,0 +1,36 @@
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 (PROBABILITY, "[0-9]+" ) \
13 X (SYMBOL_ALTERNATIVE, "\\|" ) \
14 X (SYMBOL_IS_REPLACED_BY, "::=" ) \
15 X (COMMENT, "#[^\n]*" )
16
17#define X(SYM, ...) BNF_LEXEME_KIND_##SYM,
18enum bnf_lexeme_kind {
19 BNF_LEXEME_KINDS ()
20 BNF_LEXEME_KIND_END_OF_LINE,
21 BNF_LEXEME_KIND_END_OF_FILE,
22 BNF_LEXEME_KIND_INVALID,
23 BNF_LEXEME_KIND_COUNT,
24};
25#undef X
26
27#define BNF_LEXEME_REGEX_COUNT (BNF_LEXEME_KIND_COUNT - 3)
28
29struct bnf_lexeme {
30 struct string_view sv;
31 enum bnf_lexeme_kind kind;
32};
33
34extern const char *bnf_lexeme_kind_names[BNF_LEXEME_KIND_COUNT];
35
36#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..ce14e43
--- /dev/null
+++ b/src/bnf-parser.c
@@ -0,0 +1,213 @@
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
78uint32_t
79bnf_parse_probability (struct bnf_lexer *lexer)
80{
81 const char *checkpoint = lexer->cursor;
82
83 struct bnf_lexeme lexeme = bnf_lexer_next_lexeme (lexer);
84 if (lexeme.kind == BNF_LEXEME_KIND_PROBABILITY) {
85 uint32_t probability = 0;
86 while (lexeme.sv.beg != lexeme.sv.end) {
87 probability *= 10;
88 probability += *lexeme.sv.beg++ - '0';
89 }
90 return probability;
91 }
92
93revert:
94 lexer->cursor = checkpoint;
95 return 1;
96}
97
98bool
99is_bnf_sequence_valid (struct bnf_sequence sequence)
100{
101 return sequence.term_count != 0;
102}
103
104struct bnf_sequence
105bnf_parse_sequence (struct bnf_lexer *lexer)
106{
107 struct bnf_sequence sequence = {0};
108 const char *checkpoint = lexer->cursor;
109
110 sequence.probability = bnf_parse_probability (lexer);
111
112 for (;;) {
113 struct bnf_lexeme lexeme = bnf_parse_nonterminal (lexer);
114 if (!is_bnf_lexeme_valid (lexeme))
115 lexeme = bnf_parse_terminal (lexer);
116 if (!is_bnf_lexeme_valid (lexeme))
117 break;
118
119 DYNAMIC_ARRAY_APPEND (sequence, lexeme);
120 } if (!is_bnf_sequence_valid (sequence)) goto revert;
121
122 if (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_ALTERNATIVE) ||
123 bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE))
124 return sequence;
125
126revert:
127 DYNAMIC_ARRAY_FREE (sequence);
128 lexer->cursor = checkpoint;
129 return (struct bnf_sequence) {0};
130}
131
132bool
133is_bnf_rule_valid (struct bnf_rule rule)
134{
135 return rule.is_replaced_by.sequence_count != 0;
136}
137
138struct bnf_rule
139bnf_parse_rule (struct bnf_lexer *lexer)
140{
141 struct bnf_rule rule = {0};
142 const char *checkpoint = lexer->cursor;
143
144 rule.name = bnf_parse_nonterminal (lexer);
145 if (!is_bnf_lexeme_valid (rule.name))
146 goto revert;
147
148 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_SYMBOL_IS_REPLACED_BY))
149 goto revert;
150
151 for (;;) {
152 struct bnf_sequence sequence = bnf_parse_sequence (lexer);
153 if (!is_bnf_sequence_valid (sequence)) break;
154 DYNAMIC_ARRAY_APPEND (rule.is_replaced_by, sequence);
155 } if (is_bnf_rule_valid (rule)) return rule;
156
157revert:
158 DYNAMIC_ARRAY_FREE (rule.is_replaced_by);
159 lexer->cursor = checkpoint;
160 return (struct bnf_rule) {0};
161}
162
163struct bnf_syntax
164bnf_parse_syntax (struct bnf_lexer *lexer)
165{
166 struct bnf_syntax syntax = {0};
167
168 for (;;) {
169 while (bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_LINE));
170 struct bnf_rule rule = bnf_parse_rule (lexer);
171 if (!is_bnf_rule_valid (rule)) {
172 if (!bnf_parse_lexeme (lexer, BNF_LEXEME_KIND_END_OF_FILE)) {
173 print_error (lexer, lexer->cursor, "unable to parse rule");
174 }
175 break;
176 }
177
178 DYNAMIC_ARRAY_APPEND (syntax, rule);
179 }
180
181 return syntax;
182}
183
184bool
185bnf_check_syntax (struct bnf_lexer *lexer, struct bnf_syntax syntax)
186{
187 bool no_errors = true;
188 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
189 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by) {
190 DYNAMIC_ARRAY_FOREACH (term, *sequence) {
191 if (term->kind != BNF_LEXEME_KIND_NONTERMINAL) continue;
192 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) continue;
193 if (STRING_VIEW_EQUALS (term->sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) continue;
194
195 bool rule_found = false;
196 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
197 if (!STRING_VIEW_EQUALS (rule->name.sv, term->sv)) continue;
198 rule_found = true;
199 break;
200 }
201
202 if (!rule_found) {
203 no_errors = false;
204 print_error (lexer, term->sv.beg,
205 "rule not found: %.*s",
206 (int) STRING_VIEW_LEN (term->sv), term->sv.beg);
207 }
208 }
209 }
210 }
211
212 return no_errors;
213}
diff --git a/src/bnf-parser.h b/src/bnf-parser.h
new file mode 100644
index 0000000..8887a66
--- /dev/null
+++ b/src/bnf-parser.h
@@ -0,0 +1,52 @@
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 probability;
12 uint32_t capacity;
13};
14
15struct bnf_rule {
16 struct bnf_lexeme name;
17 struct {
18 union { struct bnf_sequence *items, *sequences; };
19 union { uint32_t count, sequence_count; };
20 uint32_t capacity;
21 } is_replaced_by;
22};
23
24struct bnf_syntax {
25 union { struct bnf_rule *items, *rules; };
26 union { uint32_t count, rule_count; };
27 uint32_t capacity;
28};
29
30// struct term_table {
31// union { struct bnf_lexeme *items, *terms; };
32// union { uint32_t count, term_count; };
33// uint32_t capacity;
34// };
35
36struct bnf_parser {
37 struct bnf_lexer lexer;
38};
39
40bool is_bnf_lexeme_valid (struct bnf_lexeme);
41bool is_bnf_sequence_valid (struct bnf_sequence);
42bool is_bnf_rule_valid (struct bnf_rule);
43
44bool bnf_check_syntax (struct bnf_lexer *, struct bnf_syntax);
45bool bnf_parse_lexeme (struct bnf_lexer *, enum bnf_lexeme_kind);
46struct bnf_lexeme bnf_parse_nonterminal (struct bnf_lexer *);
47struct bnf_lexeme bnf_parse_terminal (struct bnf_lexer *);
48struct bnf_sequence bnf_parse_sequence (struct bnf_lexer *);
49struct bnf_rule bnf_parse_rule (struct bnf_lexer *);
50struct bnf_syntax bnf_parse_syntax (struct bnf_lexer *);
51
52#endif // INCLUDED_BNF_PARSER_H
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..726fcce
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,59 @@
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(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
49 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
50
51#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
52
53#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
54
55#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
56 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
57 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
58
59#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..85ca5ad
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,158 @@
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-view.h"
14
15#define I " "
16
17#define TERM_TRESHOLD (1 << 7)
18#define SPEED .25
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
44print_term (FILE *fp, struct bnf_syntax syntax, struct bnf_lexeme term);
45
46static void
47print_random_nonterminal_expansion (FILE *fp,
48 struct bnf_syntax syntax,
49 struct string_view sv)
50{
51 DYNAMIC_ARRAY_FOREACH (rule, syntax) {
52 if (!STRING_VIEW_EQUALS (rule->name.sv, sv)) continue;
53
54 uint32_t total_probability = 0;
55 DYNAMIC_ARRAY_FOREACH (sequence, rule->is_replaced_by)
56 total_probability += sequence->probability;
57 uint32_t selection = rand () % total_probability;
58 uint32_t sequence = 0;
59 for (uint32_t probability = rule->is_replaced_by.items[sequence].probability;
60 selection >= probability;
61 probability += rule->is_replaced_by.items[sequence].probability) {
62 sequence += 1;
63 }
64
65 DYNAMIC_ARRAY_FOREACH (term, rule->is_replaced_by.items[sequence])
66 print_term (fp, syntax, *term);
67
68 return;
69 }
70}
71
72static void
73print_terminal (FILE *fp, struct string_view sv)
74{
75 sv.beg += 1;
76 sv.end -= 1;
77 fprintf (fp, "%.*s", (int) STRING_VIEW_LEN (sv), sv.beg);
78}
79
80static int term_count = 0;
81static void
82print_term (FILE *fp, struct bnf_syntax syntax, struct bnf_lexeme term)
83{
84 switch (term.kind) {
85 case BNF_LEXEME_KIND_TERMINAL:
86 print_terminal (fp, term.sv);
87 break;
88 case BNF_LEXEME_KIND_NONTERMINAL:
89 if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOL>"))) {
90 fprintf (fp, "\n");
91 } else if (STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<EOF>"))) {
92 } else {
93 if (term_count > TERM_TRESHOLD &&
94 STRING_VIEW_EQUALS (term.sv, STRING_VIEW_FROM_CSTR ("<expr>"))) {
95 print_random_nonterminal_expansion (fp, syntax, STRING_VIEW_FROM_CSTR ("<value>"));
96 } else {
97 print_random_nonterminal_expansion (fp, syntax, term.sv);
98 }
99 } break;
100 default: UNREACHABLE ();
101 }
102
103 term_count += 1;
104}
105
106int
107main (int argc, char *argv[])
108{
109 const char *progname = *argv++;
110 if (argc < 2) DIE ("Usage: %s file", progname);
111
112 const char *filename = *argv++;
113 struct string_view file_contents = load_file (filename);
114
115 struct bnf_lexer lexer = bnf_lexer_from_string_view (file_contents, filename);
116 struct bnf_syntax syntax = bnf_parse_syntax (&lexer);
117 assert (bnf_check_syntax (&lexer, syntax)); // check if grammar has rules for all nonterminals
118
119 unsigned int seed = time (NULL);
120 // unsigned int seed = 1742084054;
121 srand (seed);
122
123 FILE *fp = fopen ("/home/cmmm/documents/personal/projects/raylib-shadertoy/res/shaders/glsl330/generated.fs", "w");
124 // FILE *fp = stdout;
125 fprintf (fp, "#version 330 core\n"
126 "// SEED: %u\n"
127 "// TERM_TRESHOLD: %u\n"
128 "\n"
129 "uniform float time;\n"
130 "uniform vec2 resolution;\n"
131 "uniform vec2 mouse;\n"
132 "uniform float zoom;\n"
133 "\n"
134 "out vec4 color;\n"
135 "\n"
136 "float z = zoom;\n"
137 "\n"
138 "void\n"
139 "main ()\n"
140 "{\n"
141 I"vec2 c = gl_FragCoord.xy/resolution*2*z - z;\n"
142 I"vec2 m = mouse/resolution*2*z - z;\n"
143 I"float t = time*%g;\n"
144 "\n"
145 " vec3 g = vec3 (", seed, TERM_TRESHOLD, SPEED);
146 print_random_nonterminal_expansion (fp, syntax, STRING_VIEW_FROM_CSTR ("<expr>"));
147 fprintf (fp, ", "); term_count = 0;
148 print_random_nonterminal_expansion (fp, syntax, STRING_VIEW_FROM_CSTR ("<expr>"));
149 fprintf (fp, ", "); term_count = 0;
150 print_random_nonterminal_expansion (fp, syntax, STRING_VIEW_FROM_CSTR ("<expr>"));
151 fprintf (fp, ");\n"
152 I"color = vec4 ((g + z)/2/z, 1);\n"
153 "}\n");
154 fclose (fp);
155 unload_file (file_contents);
156
157 return EXIT_SUCCESS;
158}
diff --git a/src/randomart-1.bnf b/src/randomart-1.bnf
new file mode 100644
index 0000000..b7f6fd5
--- /dev/null
+++ b/src/randomart-1.bnf
@@ -0,0 +1,10 @@
1# randomart.bnf -- syntax with semantics for generating random art -*- BNF -*-
2 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | <trig> | 0 "abs(" <expr> ")" | "sqrt(abs(" <expr> "))"
3<value> ::= <coord> | 2 <mouse> | <time> | <const>
4<coord> ::= 4 "c.x" | 3 "c.y"
5<mouse> ::= 4 "m.x" | 3 "m.y"
6 <time> ::= "sin(t)" | 0 "cos(t)"
7<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
8<digit> ::= 2 "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
9<binop> ::= 10 "(" <expr> " + " <expr> ")" | 5 "(" <expr> " - " <expr> ")" | 3 <expr> "*" <expr> | 0 "(" <expr> "/" <expr> ")"
10 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | "tan(" <expr> ")"
diff --git a/src/randomart-2.bnf b/src/randomart-2.bnf
new file mode 100644
index 0000000..42507dd
--- /dev/null
+++ b/src/randomart-2.bnf
@@ -0,0 +1,10 @@
1# randomart.bnf -- syntax with semantics for generating random art -*- BNF -*-
2 <expr> ::= <value> | 0 "-" <expr> | 10 <binop> | 3 <trig> | 1 "abs(" <expr> ")" | 5 "sqrt(abs(" <expr> "))"
3<value> ::= 3 <coord> | <mouse> | <time> | <const>
4<coord> ::= 4 "c.x" | 3 "c.y"
5<mouse> ::= 4 "m.x" | 3 "m.y"
6 <time> ::= "sin(t)" | "cos(t)"
7<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
8<digit> ::= 10 "0" | 9 "1" | 8 "2" | 7 "3" | 6 "4" | 5 "5" | 4 "6" | 3 "7" | 2 "8" | 1 "9"
9<binop> ::= 1 "(" <expr> " + " <expr> ")" | 30 "(" <expr> " - " <expr> ")" | 5 <expr> "*" <expr> | 7 "(" <expr> "/" <expr> ")"
10 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")" | 0 "tan(" <expr> ")"
diff --git a/src/randomart-3.bnf b/src/randomart-3.bnf
new file mode 100644
index 0000000..a8c075f
--- /dev/null
+++ b/src/randomart-3.bnf
@@ -0,0 +1,10 @@
1# randomart.bnf -- syntax with semantics for generating random art -*- BNF -*-
2 <expr> ::= 1 <value> | 0 "(-" <expr> ")" | 10 <binop> | 3 <trig>
3<value> ::= 1 <coord> | 2 <mouse> | <time> | <const>
4<coord> ::= "(4*abs(c.x) + abs(c.y))/2"
5<mouse> ::= "sqrt((m.x - c.x)*(m.x - c.x) + (m.y - c.y)*(m.y - c.y))"
6 <time> ::= "sin(t)" | "cos(t)"
7<const> ::= "." <digit> <digit> <digit> <digit> <digit> <digit>
8<digit> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | 3 "9"
9<binop> ::= 1 "(" <expr> " + " <expr> ")" | 0 "(" <expr> " - " <expr> ")" | 1 <expr> "*" <expr> | 0 "(" <expr> "/" <expr> ")"
10 <trig> ::= "sin(" <expr> ")" | "cos(" <expr> ")"
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..fa8b3ee
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,27 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <assert.h>
5#include <stdlib.h>
6#include <stdio.h>
7
8#define UNUSED(X) ((void) (X))
9#define UNREACHABLE() ASSERT (!"reached the unreachable...")
10#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__)
11// #define TODO(...)
12#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
13
14#define MALLOC malloc
15#define REALLOC realloc
16#define FREE free
17#define ASSERT assert
18
19#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
20
21#define DIE(FMT, ...) \
22 ({ \
23 fprintf (stderr, FMT "\n" __VA_OPT__(,) __VA_ARGS__); \
24 exit (EXIT_FAILURE); \
25 })
26
27#endif