From 8bbefe95d25fa2981add4df35bdd9903c91a8e62 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sun, 8 Nov 2026 08:13:29 +0300 Subject: publish --- .gitignore | 4 + README.org | 226 +++++++ UNLICENSE | 24 + bin/build.sh | 15 + doc/biblio.bib | 13 + doc/gost/gost-7-32-bibliography.sty | 57 ++ doc/gost/gost-7-32-captions.sty | 23 + doc/gost/gost-7-32-counters.sty | 44 ++ doc/gost/gost-7-32-headings.sty | 114 ++++ doc/gost/gost-7-32-lists.sty | 17 + doc/gost/gost-7-32-tables.sty | 29 + doc/gost/gost-7-32-toc.sty | 34 + doc/gost/gost-7-32.cls | 62 ++ doc/ox-init.el | 31 + doc/report.org | 940 +++++++++++++++++++++++++++ doc/setup.org | 31 + doc/spbstu-report.cls | 74 +++ res/01-correct-input.txt | 10 + res/02-incorrect-input.txt | 14 + res/02-input-with-invalid-lexeme.txt | 6 + res/03-input-with-long-identifier.txt | 6 + res/04-input-with-long-string-constant.txt | 6 + res/05-input-which-maybe-should-not-pass.txt | 1 + res/generated-input.txt | 2 + src/dynamic-array.h | 59 ++ src/export.c | 19 + src/lex.c | 220 +++++++ src/lexeme.c | 13 + src/lexeme.h | 74 +++ src/lexer.c | 172 +++++ src/lexer.h | 26 + src/string-builder.c | 41 ++ src/string-builder.h | 42 ++ src/string-view.h | 16 + src/utils.h | 26 + 35 files changed, 2491 insertions(+) create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 bin/build.sh create mode 100644 doc/biblio.bib create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/ox-init.el create mode 100644 doc/report.org create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 res/01-correct-input.txt create mode 100644 res/02-incorrect-input.txt create mode 100644 res/02-input-with-invalid-lexeme.txt create mode 100644 res/03-input-with-long-identifier.txt create mode 100644 res/04-input-with-long-string-constant.txt create mode 100644 res/05-input-which-maybe-should-not-pass.txt create mode 100644 res/generated-input.txt create mode 100644 src/dynamic-array.h create mode 100644 src/export.c create mode 100644 src/lex.c create mode 100644 src/lexeme.c create mode 100644 src/lexeme.h create mode 100644 src/lexer.c create mode 100644 src/lexer.h create mode 100644 src/string-builder.c create mode 100644 src/string-builder.h create mode 100644 src/string-view.h create mode 100644 src/utils.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9207dc1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.html +*.pdf +*.tex +/build diff --git a/README.org b/README.org new file mode 100644 index 0000000..805813f --- /dev/null +++ b/README.org @@ -0,0 +1,226 @@ +#+title: Lexical analysis +#+date: 2025H1 + +* Task +:PROPERTIES: +:CUSTOM_ID: task +:END: +Write a program that performs lexical analysis of the input text in +accordance with the task and generates a table of tokens with +indicating their types and values. Prepare several versions of the +program in the form of text in the input language. The program should +output messages indicating the presence of errors in the input text +that may be detected during the lexical analysis stage. The length of +identifiers and string constants is limited to 16 characters, using +only Latin letters. The program must allow for comments of unlimited +length in the input file (the format of the comments is selected +independently). Construct syntax diagrams. + +The input language contains loop statements ~for (...; ...; ...) do~, +separated by the ~|~ symbol (vertical bar). Loop statements contain +identifiers, comparison operators ~<~, ~>~, ~=~, string constants (a +sequence of characters in double quotes), and an assignment operator. +(~:=~). + +*Comment type:* +- ~// ...~ (until the end of the line) +- ~/* ... */~ (works with multiple lines and/or within a line) + +* Documentation +:PROPERTIES: +:CUSTOM_ID: documentation +:END: +The exported report can be found at [[https://git.michalec.dev/files/uni/term-06/math-logic/lab-01/report.pdf][this link]]. + +* Showcase +:PROPERTIES: +:CUSTOM_ID: showcase +:END: +#+caption: The result of an incorrect program launch +#+begin_src +$ ./build/lex +Usage: ./build/lex file +#+end_src + +#+caption: The result when specifying a non‑existent file +#+begin_src +$ ./build/lex no/such/file +error: No such file or directory: no/such/file +#+end_src + +#+caption: The result of analyzing a lexically correct text +#+begin_src +$ ./build/lex res/01-correct-input.txt +Исходный текст: +for (i :=-.1230; + i < 10; + i := 10) +do x := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do x := 10 + +| *Лексема* | *Тип лексемы* | *Значение* | +|------------------+-----------------------------+------------| +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| i | Идентификатор | I[0] | +| := | Знак присваивания | | +| -.1230 | Вещественная константа | -0.123 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[0] | +| < | Знак операции сравнения | C[1] | +| 10 | Целочиселная константа | 10 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[0] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | +| ) | Знак правой скобки | | +| do | Ключевое слово | K[1] | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| "asdf" | Строковая константа | S[0] | +| "asdf" | Строковая константа | S[0] | +| "asdf" | Строковая константа | S[0] | +| | | Символ вертикальной полосы | | +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| ; | Знак точки с запятой | | +| x | Идентификатор | I[1] | +| = | Знак операции сравнения | C[0] | +| 1 | Целочиселная константа | 1 | +| ; | Знак точки с запятой | | +| ) | Знак правой скобки | | +| "123456789ABCDE" | Строковая константа | S[1] | +| do | Ключевое слово | K[1] | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | + +| *№* | *K* | +|-----+-----| +| 0 | for | +| 1 | do | + +| *№* | *C* | +|-----+-----| +| 0 | = | +| 1 | < | +| 2 | > | + +| *№* | *S* | +|-----+----------------| +| 0 | asdf | +| 1 | 123456789ABCDE | + +| *№* | *I* | +|-----+------------------| +| 0 | i | +| 1 | x | +#+end_src + +#+caption: The result of analyzing a text with various errors +#+begin_src +$ ./build/lex res/02-incorrect-input.txt +Исходный текст: +dofor (i :=-.1230; + i != 10; + i := 10) +fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do _abcdefghijklmnop_1 := 10 + +/* + +some more text + +| *Лексема* | *Тип лексемы* | *Значение* | +|------------------+-----------------------------+------------| +| dofor | Идентификатор | I[0] | +| ( | Знак левой скобки | | +| i | Идентификатор | I[1] | +| := | Знак присваивания | | +| -.1230 | Вещественная константа | -0.123 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[1] | +| = | Знак операции сравнения | C[0] | +| 10 | Целочиселная константа | 10 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | +| ) | Знак правой скобки | | +| fordo | Идентификатор | I[2] | +| x | Идентификатор | I[3] | +| := | Знак присваивания | | +| | | Символ вертикальной полосы | | +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| x | Идентификатор | I[3] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| ; | Знак точки с запятой | | +| x | Идентификатор | I[3] | +| = | Знак операции сравнения | C[0] | +| 1 | Целочиселная константа | 1 | +| ; | Знак точки с запятой | | +| ) | Знак правой скобки | | +| "123456789ABCDE" | Строковая константа | S[0] | +| do | Ключевое слово | K[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | + +| *№* | *K* | +|-----+-----| +| 0 | for | +| 1 | do | + +| *№* | *C* | +|-----+-----| +| 0 | = | +| 1 | < | +| 2 | > | + +| *№* | *S* | +|-----+----------------| +| 0 | 123456789ABCDE | + +| *№* | *I* | +|-----+------------------| +| 0 | dofor | +| 1 | i | +| 2 | fordo | +| 3 | x | +res/02-incorrect-input.txt:2:7: error: invalid lexeme `!' + 2 | i != 10; + | ^ +res/02-incorrect-input.txt:4:11: error: invalid number constant `11ebc123' + 4 | fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" + | ^~~~~~~~ +res/02-incorrect-input.txt:4:20: error: string constant longer than 16 symbols (26) + 4 | fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" + | ^~~~~~~~~~~~~~~~~~~~~~~~~~ +res/02-incorrect-input.txt:10:3: error: identifier longer than 16 symbols (19) + 10 | do _abcdefghijklmnop_1 := 10 + | ^~~~~~~~~~~~~~~~~~~ +res/02-incorrect-input.txt:12:0: error: unterminated comment + 12 | /* + | ^~ +#+end_src + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/bin/build.sh b/bin/build.sh new file mode 100755 index 0000000..c5726e0 --- /dev/null +++ b/bin/build.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +set -xe + +mkdir -p ./build/ + +gcc -ggdb3 -Wall -Wextra -o ./build/export \ + ./src/lexeme.c \ + ./src/export.c + +gcc -ggdb3 -Wall -Wextra -o ./build/lex \ + ./src/string-builder.c \ + ./src/lexeme.c \ + ./src/lexer.c \ + ./src/lex.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 @@ +@book{WOLFRAM2002, +author = {Стивен Вольфрам}, +title = {Наука нового типа}, +publisher = {Wolfram Media}, +year = {2002}, +pages = {1197} +} +@online{VOSTROV2024, +author = {Востров А. В}, +title = {Теория алгоритмов}, +url = {https://tema.spbstu.ru/algorithm/}, +urldate = {2024-12-01} +} 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 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\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 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, justification=centering, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=above} + +\addto\captionsrussian{\renewcommand{\figurename}{Рис.}} +% \addto\captionsrussian{\renewcommand{\mintedname}{Рис.}} +\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..ee95480 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,44 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother + +% Increment figure counter when using lstlisting +% \let\oldlstlisting\lstlisting +% \renewcommand{\lstlisting}[1][]{% +% \refstepcounter{figure} +% \oldlstlisting[#1] +% } 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 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +\setcounter{secnumdepth}{5} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\centering\Large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing*{\section}{0cm}{0cm}{0.5cm} +\newcommand{\sectionbreak}{\clearpage} + +\titleformat{\subsection}[block]{\Large\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.25cm} + +\titleformat{\subsubsection}[block]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{} +\titlespacing{\subsubsection}{0cm}{0.5em}{0.25cm} + +\titleformat{\paragraph}[block]{\normalsize\bfseries}{\theparagraph}{0.5em}{} +\titlespacing*{\paragraph}{0cm}{0.5em}{0.25cm} + +\titleformat{\subparagraph}[block]{\normalsize\bfseries}{\thesubparagraph}{0.5em}{} +\titlespacing{\subparagraph}{0cm}{0.5em}{0.25cm} + +\makeatletter +\let\oldsection\section +\newcommand{\@sectionnostar}[1]{\oldsection*{#1}\addcontentsline{toc}{section}{#1}} +\newcommand{\@sectionstar}[1]{\oldsection{#1}} +\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} +\makeatother + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} 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 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} +\setlist[itemize, 3]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} +\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 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tabularx} + +% +% Center-aligned column with automatic width +% +\newcolumntype{Y}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{Z}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\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 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black, + hidelinks +]{hyperref} + +% +% Set custom font styles +% +\renewcommand{\cftsecfont}{\normalfont} +\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +\renewcommand{\cftsecpagefont}{\normalsize} +\renewcommand{\cftaftertoctitle}{\hfill\hfill} +\renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +\setlength{\cftbeforesecskip}{0cm} +\setlength{\cftbeforesubsecskip}{0cm} +\setlength{\cftbeforesubsubsecskip}{0cm} +\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 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\spacing{1.5} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..671adce --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,31 @@ +;;; ox-init.el --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +(org-babel-do-load-languages + 'org-babel-load-languages + '((latex . t) + (C . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(setq org-latex-src-block-backend 'minted) + +(require 'oc-bibtex) +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-latex-caption-above '(table src-block)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\section*{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;;; ox-init.el ends here diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..469c52b --- /dev/null +++ b/doc/report.org @@ -0,0 +1,940 @@ +#+title: Лексический анализ текста +#+author: Михалец М. +#+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №1} +#+latex_header: \subject{по дисциплине «Математическая логика и теория автоматов»} +#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} +#+latex_header: \institute{Институт компьютерных наук и кибербезопасности} +#+latex_header: \school{Высшая школа технологии искусственного интеллекта} +#+latex_header: \direction{02.03.01 Математика и компьютерные науки} +#+latex_header: \reviewertitle{}\reviewer{Востров А.В.} +#+latex_header: \city{Санкт-Петербург} +#+date: 2025 + +#+latex_header: \newcommand{\overbar}[1]{\mkern1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu} +#+macro: caption @@latex:\vspace{0em}\captionof{listing}{$2\label{$1}}\vspace{0em}@@ + +#+setupfile: setup.org +#+latex: \sloppy + +* ВВЕДЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +Данный отчёт содержит проведение лабораторной работы №1 по дисциплине +«Математическая логика и теория автоматов», в которой выполняется +лексический анализ текста. + +* Постановка задачи +Написать программу, которая выполняет лексический анализ входного +текста в соответствии с заданием и порождает таблицу лексем с +указанием их типов и значений. Подготовить несколько вариантов +программы в виде текста на входном языке. Программа должна выдавать +сообщения о наличие во входном тексте ошибок, которые могут быть +обнаружены на этапе лексического анализа. Длина идентификатора и +строковых констант ограничена 16 символами, только латиница. +Программа должна допускать наличие комментариев неограниченной длины +во входном файле (форма комментариев выбирается самостоятельно). В +отчете строим синтаксические диаграммы. + +*Вариант №11:* Входной язык содержит операторы цикла ~for (...; ...; ...) +do~, разделенные символом ~|~ (вертикальная полоса). Операторы цикла +содержат идентификаторы, знаки сравнения ~<~, ~>~, ~=~, строковые константы +(последовательность символов в двойных кавычках), знак присваивания +(~:=~). + +*Выбранный вид комментариев:* +- ~// ...~ (до конца строки) +- ~/* ... */~ (работает с несколькими строками) + +* Математическое описание +** Математическая модель программы +Лексический анализатор принимает на вход последовательность символов +$w$ и выдает последовательность лексем $L = (l_1, l_2, \dots, l_n)$. + +#+begin_export latex +\begin{displaymath} + F_{lex} : \Sigma^* \rightarrow L^*, +\end{displaymath} +#+end_export +где: +- $\Sigma^*$ --- множество всех возможных строк над алфавитом $\Sigma$; +- $L^*$ --- множество всех возможных последовательностей лексем; +- $l_i \in L$ --- лексема; + +Набор лексем для данного варианта: +- Ключевое слово: ~(for|do)~ +- Слишком длинный идентификатор: ~[A-Z_a-z][0-9A-Z_a-z]{16,}~ +- Идентификатор: ~[A-Z_a-z][0-9A-Z_a-z]{0,15}~ +- Символ вертикальной полосы: ~\|~ +- Знак присваивания: ~:=~ +- Знак сравнения: ~(<|=|>)~ +- Знак левой скобки: ~\(~ +- Знак правой скобки: ~\)~ +- Знак точки с запятой: ~;~ +- Недопустимая числовая константа: ~-?[0-9]*\.?[0-9]+[A-Z_a-z][0-9A-Z_a-z]*~ +- Целочиселная константа: ~-?[0-9]+~ +- Вещественная константа: ~-?[0-9]*\.[0-9]+~ +- Слишком длинная строковая константа: ~"[^"]{15,}"~ +- Строковая константа: ~"[^"]{0,14}"~ +- Комментарий: ~(//[^\n]*|/\*+([^*]|\*[^/])*\*+/)~ +- Незавершенный Комментарий ~/\*([^*]|]\*[^/])*~ + +#+begin_export latex +\begin{grammar} + $::=$ \[[ + \begin{stack} + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + \\ + + \end{stack} + \]] + + $::=$ \[[ + \begin{stack} + `for' \\ + `do' + \end{stack} + \]] + + $::=$ \[[ + \begin{stack} \\ `_' \end{stack} + \begin{stack} \\ + \begin{rep} + \begin{stack} + \\ \\ `_' + \end{stack} + \end{rep} + \end{stack} + \]] + + $::=$ \[[ `|' \]] + + $::=$ \[[ `:=' \]] + + $::=$ \[[ + \begin{stack} + `<' \\ + `=' \\ + `>' + \end{stack} + \]] + + $::=$ \[[ `(' \]] + + $::=$ \[[ `)' \]] + + $::=$ \[[ `;' \]] + + $::=$ \[[ + \begin{stack} \\ `-' \end{stack} + \begin{stack} \\ \begin{rep} \end{rep} \end{stack} + \begin{stack} \\ `.' \end{stack} + \begin{rep} \end{rep} + + \]] + + $::=$ \[[ + \begin{stack} \\ `-' \end{stack} + \begin{rep} \end{rep} + \]] + + $::=$ \[[ + \begin{stack} \\ `-' \end{stack} + \begin{stack} \\ \begin{rep} \end{rep} \end{stack} + `.' + \begin{rep} \end{rep} + \]] + + $::=$ \[[ + `"' + \begin{stack} \\ + \begin{rep} + \begin{stack} + \\ + \\ + `\\"' + \end{stack} + \end{rep} + \end{stack} + `"' + \]] + + $::=$ \[[ + \begin{stack} + `//' \begin{stack} \\ + \begin{rep} + \begin{stack} + \\ + + \end{stack} + \end{rep} + \end{stack} \\ + `/' \begin{rep} `*' \end{rep} + \begin{stack} \\ + \begin{rep} + \begin{stack} + \\ + \\ + `*' \\ + + \end{stack} + \end{rep} + \end{stack} + \begin{rep} `*' \end{rep} `/' + \end{stack} + \]] + + $::=$ \[[ + `/*' + \begin{stack} \\ + \begin{rep} + \begin{stack} + \\ + \\ + `*' \\ + + \end{stack} + \end{rep} + \end{stack} + \]] + + $::=$ \[[ + \begin{stack} + \\ + + \end{stack} + \]] + + $::=$ `A' | `B' | `C' | `D' | `E' | `F' | `G' | `H' | `I' | `J' | `K' | `L' | `M' | `N' | `O' | `P' | `Q' | `R' | `S' | `T' | `U' | `V' | `W' | `X' | `Y' | `Z' | `a' | `b' | `c' | `d' | `e' | `f' | `g' | `h' | `i' | `j' | `k' | `l' | `m' | `n' | `o' | `p' | `q' | `r' | `s' | `t' | `u' | `v' | `w' | `x' | `y' | `z' + + $::=$ `0' | `1' | `2' | `3' | `4' | `5' | `6' | `7' | `8' | `9' + + $::=$ ` ' | `!' | `#' | `$' | `%' | `&' | `\'' | `(' | `)' | `*' | `+' | `,' | `-' | `.' | `:' | `;' | `<' | `=' | `>' | `?' | `@' | `[' | `\\' | `]' | `^' | `_' | ``' | `{' | `|' | `}' | `~' + + $::=$ | `*' | `/' + + $::=$ | `"' | `/' + + $::=$ | `"' | `*' + + $::=$ | `"' | `*' | `/' +\end{grammar} +#+end_export + +* Программная реализация +** Лексемы +Лексемы определяются посредством X-макросов, указывая символ -- +название, строку -- описание и строку -- регулярное выражение: +#+attr_latex: :options fontsize=\scriptsize +#+begin_src c +#define LEXEME_KINDS() \ + X (KEYWORD, "Ключевое слово", "for|do" ) \ + X (IDENTIFIER_TOO_LONG, "Слишком длинный идентификатор", "[A-Z_a-z][0-9A-Z_a-z]{16,}" ) \ + X (IDENTIFIER, "Идентификатор", "[A-Z_a-z][0-9A-Z_a-z]*" ) \ + X (SYMBOL_SEPARATOR, "Символ вертикальной полосы", "\\|" ) \ + X (SYMBOL_ASSIGNMENT, "Знак присваивания", ":=" ) \ + X (SYMBOL_COMPARISON, "Знак операции сравнения", "<|=|>" ) \ + X (SYMBOL_PARENTHESIS_LEFT, "Знак левой скобки", "\\(" ) \ + X (SYMBOL_PARENTHESIS_RIGHT, "Знак правой скобки", "\\)" ) \ + X (SYMBOL_SEMICOLON, "Знак точки с запятой", ";" ) \ + X (CONSTANT_NUMBER_INVALID, "Недопустимая числовая константа", "-?[0-9]*\\.?[0-9]+[A-Z_a-z][0-9A-Z_a-z]+") \ + X (CONSTANT_INTEGER, "Целочиселная константа", "-?[0-9]+" ) \ + X (CONSTANT_REAL, "Вещественная константа", "-?[0-9]*\\.[0-9]+" ) \ + X (CONSTANT_STRING_TOO_LONG, "Слишком длинная строковая константа", "\"[^\"]{15,}\"" ) \ + X (CONSTANT_STRING, "Строковая константа", "\"[^\"]{0,14}\"" ) \ + X (COMMENT, "Комментарий", "//[^\n]*|/\\*+([^*]|\\*[^/])*\\*+/" ) \ + X (COMMENT_UNTERMINATED, "Незавершенный Комментарий", "/\\*([^*]|]\\*[^/])*" ) +#+end_src + +#+begin_src c +#define X(SYM, ...) LEXEME_KIND_##SYM, +enum lexeme_kind { + LEXEME_KIND_INVALID, + LEXEME_KINDS () + LEXEME_KIND_COUNT, + LEXEME_KIND_END_OF_FILE, +}; +#undef X + +#define X(SYM, STR, ...) [LEXEME_KIND_##SYM - 1] = (STR), +const char *lexeme_kind_names[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X + +#define X(SYM, STR, REG) [LEXEME_KIND_##SYM - 1] = "^(" REG ")", +const char *lexeme_regex_strings[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X +#+end_src + +Также, для лексем со статическими таблицами определяются их значения: +#+begin_src c +#define KEYWORDS() \ + X (FOR, "for") \ + X (DO, "do") +#define X(SYM, ...) KEYWORD_##SYM, +enum keyword { KEYWORDS () KEYWORD_COUNT }; +#undef X +#define X(SYM, STR, ...) [KEYWORD_##SYM] = (STR), +const char *keyword_names[KEYWORD_COUNT] = { KEYWORDS () }; +#undef X + +#define COMPARISONS() \ + X (EQUALS, "=") \ + X (LESS_THAN, "<") \ + X (GREATER_THAN, ">") +#define X(SYM, ...) COMPARISON_##SYM, +enum comparison { COMPARISONS () COMPARISON_COUNT }; +#undef X +#define X(SYM, STR, ...) [COMPARISON_##SYM] = (STR), +const char *comparison_names[COMPARISON_COUNT] = { COMPARISONS () }; +#undef X +#+end_src + +*** Структура лексемы +Поля: +- ~sv~ :: вид на строку в исходном буфере; +- ~kind~ :: тип лексемы; +- ~code~ :: код лексемы (одно из): + - ~keyword~ :: индекс в таблицу ключевых слов; + - ~comparison~ :: индекс в таблицу знаков сравнения; + - ~integer~ :: целочиселное значение; + - ~real~ :: вещественное значение; + - ~table_index~ :: индекс в таблицу. +#+begin_src c +struct lexeme { + struct string_view sv; + enum lexeme_kind kind; + union { + enum keyword keyword; + enum comparison comparison; + int integer; + float real; + uint32_t table_index; + } code; +}; +#+end_src + +** Лексический анализатор +*** Структура лексического анализатора +Поля: +- ~sv~ :: вид на исходный буфер; +- ~cursor~ :: положение курсора в исходном буфере; +- ~beginning_of_line~ :: положение начало строки в исходном буфере; +- ~line~ :: номер строки; +- ~constant_string_table~ :: таблица строковых констант; +- ~identifier_table~ :: таблица идентификаторов. +#+begin_src c +struct lexer { + struct string_view sv; + const char *cursor; + const char *beginning_of_line; + size_t line; + struct string_view_table constant_string_table; + struct string_view_table identifier_table; +}; +#+end_src + +*** Функция создания лексического анализатора +Инициализирует структуру лексического анализатора, для данного текста. +- Вход: :: строка и её длина. +- Выход: :: инициализированная структура лексического анализатора. +#+begin_src c +struct lexer +lexer_create (const char *string, size_t len) +{ + return (struct lexer) { + .sv = { + .beg = string, + .end = string + len, + }, + .cursor = string, + .beginning_of_line = string, + .line = 1, + }; +} + +#+end_src + +*** Функция прокрутки белых знаков +Сдвигает курсор лексического анализатора пока курсор на белом символе, +сохраняя информацию о номере и начале строки. +- Вход: :: указатель на структуру лексического анализатора. +- Выход: :: изменённая информация о расположений внутри структуры + лексического анализатора. +#+begin_src c +static void +lexer_skip_whitespace (struct lexer *lexer) +{ + while (lexer->cursor < lexer->sv.end && isspace (*lexer->cursor)) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} +#+end_src + +*** Функция прокрутки на количество символов +Сдвигает курсор лексического анализатора на определённое количество +символов, сохраняя информацию о номере и начале строки. +- Вход: :: указатель на структуру лексического анализатора и + количество символов для прокрутки. +- Выход: :: изменённая информация о расположений внутри структуры + лексического анализатора. +#+begin_src c +static void +lexer_progress_cursor_by (struct lexer *lexer, int count) +{ + const char *end = lexer->cursor + count; + ASSERT (end <= lexer->sv.end); + + while (lexer->cursor < end) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} +#+end_src + +*** Функция инициализации таблицы скомпилированных регулярных выражений +Компилирует регулярные выражения до входа в функцию ~main~ за счёт +атрибута =constructor=. +- Вход: :: глобальный массив строковых констант регулярных выражений. +- Выход: :: глобальный массив скомпилированных регулярных выражений. +#+begin_src c +static void __attribute__((constructor)) +compile_regexes (void) +{ + for (enum lexeme_kind kind = 1; i < LEXEME_KIND_COUNT; ++i) { + int errcode = regcomp (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + REG_EXTENDED); + if (errcode) { + print_regex_error (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + errcode); + exit (1); + } + } +} +#+end_src + +*** Функция распознания следующей лексемы +Пропускает белые символы, находит регулярное выражение с самым длинным +совпадением, считает данные в лексему, продвигает курсор за неё, и +возвращает её. +- Вход: :: указатель на структуру лексического анализатора. +- Выход: :: структура распознанной лексемы. +#+begin_src c +struct lexeme +lexer_next_lexeme (struct lexer *lexer) +{ + lexer_skip_whitespace (lexer); + struct lexeme lexeme = { .sv.beg = lexer->cursor }; + + if (lexer->cursor >= lexer->sv.end) { + lexeme.kind = LEXEME_KIND_END_OF_FILE; + lexeme.sv.end = lexer->cursor; + return lexeme; + } + + regmatch_t regmatch; + enum lexeme_kind longest_matching_lexeme_kind = LEXEME_KIND_INVALID; + int longest_matching_lexeme_kind_length = 0; + for (enum lexeme_kind kind = 1; kind < LEXEME_KIND_COUNT; ++kind) { + if (regexec (&lexeme_regexes[kind - 1], lexer->cursor, 1, ®match, 0)) + continue; + if (regmatch.rm_eo <= longest_matching_lexeme_kind_length) continue; + longest_matching_lexeme_kind_length = regmatch.rm_eo; + longest_matching_lexeme_kind = kind; + } + + if (longest_matching_lexeme_kind) { + lexeme.kind = longest_matching_lexeme_kind; + lexer_progress_cursor_by (lexer, longest_matching_lexeme_kind_length); + lexeme.sv.end = lexer->cursor; + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: { + for (enum keyword keyword = 0; keyword < KEYWORD_COUNT; ++keyword) { + struct string_view keyword_sv = { + .beg = keyword_names[keyword], + .end = keyword_names[keyword] + strlen (keyword_names[keyword]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, keyword_sv)) continue; + + lexeme.value.table_index = keyword; + } + } break; + case LEXEME_KIND_SYMBOL_COMPARISON: { + for (enum comparison comparison = 0; + comparison < COMPARISON_COUNT; ++comparison) { + struct string_view comparison_sv = { + .beg = comparison_names[comparison], + .end = comparison_names[comparison] + strlen (comparison_names[comparison]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, comparison_sv)) continue; + + lexeme.value.table_index = comparison; + } + } break; + case LEXEME_KIND_CONSTANT_INTEGER: { + TODO ("fix overflow"); + lexeme.value.integer = strtol (lexeme.sv.beg, NULL, 10); + } break; + case LEXEME_KIND_CONSTANT_REAL: + TODO ("fix overflow"); + lexeme.value.real = strtof (lexeme.sv.beg, NULL); + break; + case LEXEME_KIND_CONSTANT_STRING: { + struct string_view sv = { + .beg = lexeme.sv.beg + 1, + .end = lexeme.sv.end - 1, + }; + DYNAMIC_ARRAY_FOREACH (e, lexer->constant_string_table) { + if (STRING_VIEW_EQUALS (sv, *e)) { + lexeme.value.table_index = e - lexer->constant_string_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->constant_string_table.count; + DYNAMIC_ARRAY_APPEND (lexer->constant_string_table, sv); + } break; + case LEXEME_KIND_IDENTIFIER: { + DYNAMIC_ARRAY_FOREACH (e, lexer->identifier_table) { + if (STRING_VIEW_EQUALS (lexeme.sv, *e)) { + lexeme.value.table_index = e - lexer->identifier_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->identifier_table.count; + DYNAMIC_ARRAY_APPEND (lexer->identifier_table, lexeme.sv); + } break; + default: + break; + } + + return lexeme; + } + + lexeme.sv.end = ++lexer->cursor; + return lexeme; +} +#+end_src + +** Приложение ~lex~ +Алгоритм приложения: +1. Обеспечение передачи одного аргумента --- название файла для + лексического анализа. +2. Отображение данного файла в оперативную память. +3. Печать исходного текста. +4. Распознание лексемы. +5. Если лексема не распознана, переход к шагу 8. +6. Печать распознанной лексемы или сохранение информации об ошибочной + лексеме. +7. Переход к шагу 4. +8. Печать таблицы ключевых слов. +9. Печать таблицы операторов сравнения. +10. Печать таблицы распознанных идентификаторов. +11. Печать таблицы распознанных строковых констант. +12. Печать ошибок лексического анализа. +13. Выход из программы. + +*** Функция входа в программу +Выполняет работу приложения =lex=. +- Вход: :: аргументы командной строки. +- Выход: :: печать в файл стандартного вывода и код ошибки. +#+begin_src c +int +main (int argc, char *argv[]) +{ + const char *progname = *argv++; + if (argc < 2) DIE ("Usage: %s file", progname); + + file = *argv++; + int fd = open (file, O_RDONLY); + if (fd == -1) DIE ("error: %s: %s", strerror (errno), file); + + struct stat st; + fstat (fd, &st); + char *string = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + close (fd); + + puts ("Исходный текст:"); + fwrite (string, 1, st.st_size, stdout); + + struct { + struct lexing_error *items; + uint32_t count; + uint32_t capacity; + } lexing_errors = {0}; + + struct string_builder sb = {0}; + struct lexer lexer = lexer_create (string, st.st_size); + putchar ('\n'); + printf ("| *Лексема* | *Тип лексемы* | *Значение* |\n"); + printf ("|------------------+-----------------------------+------------|\n"); + for (struct lexeme lexeme = lexer_next_lexeme (&lexer); + lexeme.kind != LEXEME_KIND_END_OF_FILE; + lexeme = lexer_next_lexeme (&lexer)) { + switch (lexeme.kind) { + case LEXEME_KIND_INVALID: + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + DYNAMIC_ARRAY_APPEND ( + lexing_errors, + ((struct lexing_error) { + .lexeme = lexeme, + .beginning_of_line = lexer.beginning_of_line, + .line = lexer.line, + })); + continue; + default: break; + } + + if (lexeme.kind == LEXEME_KIND_COMMENT) + continue; + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: + string_builder_printf (&sb, "K[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_SYMBOL_COMPARISON: + string_builder_printf (&sb, "C[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_CONSTANT_INTEGER: + string_builder_printf (&sb, "%d", lexeme.value.integer); + break; + case LEXEME_KIND_CONSTANT_REAL: + string_builder_printf (&sb, "%g", lexeme.value.real); + break; + case LEXEME_KIND_CONSTANT_STRING: + string_builder_printf (&sb, "S[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_IDENTIFIER: + string_builder_printf (&sb, "I[%d]", lexeme.value.table_index); + break; + default: + STRING_BUILDER_APPEND_CSTR (sb, ""); + } + string_builder_append_ntimes (&sb, ' ', 10 - sb.count); + STRING_BUILDER_APPEND_NULL (sb); + printf ("| %-16.*s | %-*s | %s |\n", + (int) STRING_VIEW_LEN (lexeme.sv), lexeme.sv.beg, + display_to_byte_len (lexeme_kind_names[lexeme.kind - 1], 27), + lexeme_kind_names[lexeme.kind - 1], + sb.items); + STRING_BUILDER_RESET (sb); + } + + putchar ('\n'); + printf ("| *№* | *K* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < KEYWORD_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, keyword_names[i]); + + putchar ('\n'); + printf ("| *№* | *C* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < COMPARISON_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, comparison_names[i]); + + putchar ('\n'); + printf ("| *№* | *S* |\n"); + printf ("|-----+----------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.constant_string_table) { + printf ("| %3ld | %-14.*s |\n", e - lexer.constant_string_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + putchar ('\n'); + printf ("| *№* | *I* |\n"); + printf ("|-----+------------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.identifier_table) { + printf ("| %3ld | %-16.*s |\n", e - lexer.identifier_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + DYNAMIC_ARRAY_FOREACH (lexing_error, lexing_errors) { + switch (lexing_error->lexeme.kind) { + case LEXEME_KIND_INVALID: + print_lexing_error (lexing_error, "invalid lexeme `%.*s'", + (int) STRING_VIEW_LEN (lexing_error->lexeme.sv), + lexing_error->lexeme.sv.beg); + break; + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + print_lexing_error (lexing_error, + "string constant longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (lexing_error->lexeme.sv)); + break; + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + print_lexing_error (lexing_error, + "identifier longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (lexing_error->lexeme.sv)); + break; + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + print_lexing_error (lexing_error, "invalid number constant `%.*s'", + (int) STRING_VIEW_LEN (lexing_error->lexeme.sv), + lexing_error->lexeme.sv.beg); + break; + default: break; + } + } + + munmap (string, st.st_size); + + return EXIT_SUCCESS; +} +#+end_src + +* Результаты программы +Результаты программы приведены на рис. \ref{result-1}-\ref{result-4}. + +{{{caption(result-1, Результат неправильного запуска программы)}}} +#+begin_src sh +$ ./build/lex +Usage: ./build/lex file +#+end_src + +{{{caption(result-2, Результат при указаний несуществующего файла)}}} +#+begin_src sh +$ ./build/lex no/such/file +error: No such file or directory: no/such/file +#+end_src + +{{{caption(result-3, Результат анализа лексически правильного текста)}}} +#+begin_src sh +$ ./build/lex res/01-correct-input.txt +Исходный текст: +for (i :=-.1230; + i < 10; + i := 10) +do x := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do x := 10 + +| *Лексема* | *Тип лексемы* | *Значение* | +|------------------+-----------------------------+------------| +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| i | Идентификатор | I[0] | +| := | Знак присваивания | | +| -.1230 | Вещественная константа | -0.123 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[0] | +| < | Знак операции сравнения | C[1] | +| 10 | Целочиселная константа | 10 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[0] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | +| ) | Знак правой скобки | | +| do | Ключевое слово | K[1] | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| "asdf" | Строковая константа | S[0] | +| "asdf" | Строковая константа | S[0] | +| "asdf" | Строковая константа | S[0] | +| | | Символ вертикальной полосы | | +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| ; | Знак точки с запятой | | +| x | Идентификатор | I[1] | +| = | Знак операции сравнения | C[0] | +| 1 | Целочиселная константа | 1 | +| ; | Знак точки с запятой | | +| ) | Знак правой скобки | | +| "123456789ABCDE" | Строковая константа | S[1] | +| do | Ключевое слово | K[1] | +| x | Идентификатор | I[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | + +| *№* | *K* | +|-----+-----| +| 0 | for | +| 1 | do | + +| *№* | *C* | +|-----+-----| +| 0 | = | +| 1 | < | +| 2 | > | + +| *№* | *S* | +|-----+----------------| +| 0 | asdf | +| 1 | 123456789ABCDE | + +| *№* | *I* | +|-----+------------------| +| 0 | i | +| 1 | x | +#+end_src + +{{{caption(result-4, Результат анализа текста с разными ошибками)}}} +#+begin_src sh +$ ./build/lex res/02-incorrect-input.txt +Исходный текст: +dofor (i :=-.1230; + i != 10; + i := 10) +fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do _abcdefghijklmnop_1 := 10 + +/* + +some more text + +| *Лексема* | *Тип лексемы* | *Значение* | +|------------------+-----------------------------+------------| +| dofor | Идентификатор | I[0] | +| ( | Знак левой скобки | | +| i | Идентификатор | I[1] | +| := | Знак присваивания | | +| -.1230 | Вещественная константа | -0.123 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[1] | +| = | Знак операции сравнения | C[0] | +| 10 | Целочиселная константа | 10 | +| ; | Знак точки с запятой | | +| i | Идентификатор | I[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | +| ) | Знак правой скобки | | +| fordo | Идентификатор | I[2] | +| x | Идентификатор | I[3] | +| := | Знак присваивания | | +| | | Символ вертикальной полосы | | +| for | Ключевое слово | K[0] | +| ( | Знак левой скобки | | +| x | Идентификатор | I[3] | +| := | Знак присваивания | | +| 11 | Целочиселная константа | 11 | +| ; | Знак точки с запятой | | +| x | Идентификатор | I[3] | +| = | Знак операции сравнения | C[0] | +| 1 | Целочиселная константа | 1 | +| ; | Знак точки с запятой | | +| ) | Знак правой скобки | | +| "123456789ABCDE" | Строковая константа | S[0] | +| do | Ключевое слово | K[1] | +| := | Знак присваивания | | +| 10 | Целочиселная константа | 10 | + +| *№* | *K* | +|-----+-----| +| 0 | for | +| 1 | do | + +| *№* | *C* | +|-----+-----| +| 0 | = | +| 1 | < | +| 2 | > | + +| *№* | *S* | +|-----+----------------| +| 0 | 123456789ABCDE | + +| *№* | *I* | +|-----+------------------| +| 0 | dofor | +| 1 | i | +| 2 | fordo | +| 3 | x | +res/02-incorrect-input.txt:2:7: error: invalid lexeme `!' + 2 | i != 10; + | ^ +res/02-incorrect-input.txt:4:11: error: invalid number constant `11ebc123' + 4 | fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" + | ^~~~~~~~ +res/02-incorrect-input.txt:4:20: error: string constant longer than 16 symbols (26) + 4 | fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" + | ^~~~~~~~~~~~~~~~~~~~~~~~~~ +res/02-incorrect-input.txt:10:3: error: identifier longer than 16 symbols (19) + 10 | do _abcdefghijklmnop_1 := 10 + | ^~~~~~~~~~~~~~~~~~~ +res/02-incorrect-input.txt:12:0: error: unterminated comment + 12 | /* + | ^~ +#+end_src + +* ЗАКЛЮЧЕНИЕ +:PROPERTIES: +:UNNUMBERED: t +:END: +В результате работы был реализован лексический анализатор, +распознающий ключевые слова (операторы цикла), идентификаторы, знаки +сравнения, знак присваивания разделяющий символ, строковые, +целочисленные и вещественные константы. + +Данный язык является автоматным, так как отдельные лексемы -- +регулярные языки, и объединение, конкатенация и взятие звёздочки Клини +в таком случае тоже автоматные языки. Автоматные грамматики --- самые +простые из формальных грамматик. Они являются подмножеством +контекстно-свободных грамматик. + +Была выявлена потребность к следующим дополнительным лексемам: +1. неверная лексема; +2. слишком длинный идентификатор; +3. слишком длинная строковая константа; +4. неверная числовая константа; +5. незавершенный комментарий. + +Код лабораторной работы был написан в продвинутом, расширяемом, +настраиваемом и самодокументирующемся редакторе --- GNU/Emacs 29.4, на +языке программирования Си (=gnu99=). + +*Достоинства:* +- Легко определить новые лексемы, так как распознавание лексем + основано на регулярных выражения. +- Ошибки печатаются в формате как у =gcc=, что улучшает взаимодействие + программы с текстовыми редакторами как GNU/Emacs. + +*Недостатки:* +- Добавление лексем со статическими таблицами требует изменение кода в + нескольких местах. +- Регулярные выражения компилируются каждый раз при запуске программы, + а не на этапе сборки. + +*Масштабируемость:* +- Можно реализовать лексический анализ нескольких файлов или наборов текстов параллельно. + +* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ +:PROPERTIES: +:UNNUMBERED: t +:END: +#+latex: \nocite{VOSTROV2024} +#+print_bibliography: :heading none + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..bb7efdd --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,31 @@ +#+options: ':nil *:t -:t ::t <:t H:4 \n:nil ^:{} arch:headline +#+options: author:t broken-links:nil c:nil creator:nil +#+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+options: timestamp:nil title:t toc:t todo:t |:t + +#+select_tags: export +#+exclude_tags: noexport + +#+bibliography: biblio.bib +#+cite_export: biblatex + +#+latex_compiler: xelatex +#+latex_class: spbstu-report +# #+latex_class_options: [draft] + +#+latex_header: \usepackage{enumitem} + +#+latex_header: \usepackage[newfloat]{minted} +#+latex_header: \usemintedstyle{bw} +#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors} + +#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} + +#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+latex_header: \setmainfont{Times New Roman} +#+latex_header: \setmonofont{Aporetic Serif Mono}[Contextuals=AlternateOff] + +#+latex_header: \usepackage{tikz} +#+latex_header: \usepackage{pgfplots} +#+latex_header: \usepackage[rounded]{syntax} diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..763790f --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,74 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{adjustbox} +\RequirePackage{setspace} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} +\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} +\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} +\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{\@university} + + \vspace{0.5cm} + \normalsize{\@institute} + + \normalsize{\@school} + + \normalsize{Направление \@direction} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130201/20102 & \hspace{.5cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{.5cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{\@city, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/res/01-correct-input.txt b/res/01-correct-input.txt new file mode 100644 index 0000000..5141ab5 --- /dev/null +++ b/res/01-correct-input.txt @@ -0,0 +1,10 @@ +for (i :=-.1230; + i < 10; + i := 10) +do x := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do x := 10 diff --git a/res/02-incorrect-input.txt b/res/02-incorrect-input.txt new file mode 100644 index 0000000..3648c25 --- /dev/null +++ b/res/02-incorrect-input.txt @@ -0,0 +1,14 @@ +dofor (i :=-.1230; + i != 10; + i := 10) +fordo x := 11ebc123 "asdfasdfasdfasdfasdfasdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" /* +323asdf +MULTILINE COMMENT + x=2 */ +do _abcdefghijklmnop_1 := 10 + +/* + +some more text diff --git a/res/02-input-with-invalid-lexeme.txt b/res/02-input-with-invalid-lexeme.txt new file mode 100644 index 0000000..d2404ad --- /dev/null +++ b/res/02-input-with-invalid-lexeme.txt @@ -0,0 +1,6 @@ +for (i := -.1230; + i % 10; + i := 10) +do x := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDEF" do x := 10 diff --git a/res/03-input-with-long-identifier.txt b/res/03-input-with-long-identifier.txt new file mode 100644 index 0000000..05472b7 --- /dev/null +++ b/res/03-input-with-long-identifier.txt @@ -0,0 +1,6 @@ +for (i := -.1230; + i < 10; + i := 10) +do abcdef_0123456789 := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDE" do x := 10 diff --git a/res/04-input-with-long-string-constant.txt b/res/04-input-with-long-string-constant.txt new file mode 100644 index 0000000..81b14cf --- /dev/null +++ b/res/04-input-with-long-string-constant.txt @@ -0,0 +1,6 @@ +for (i := -.1230; + i < 10; + i := 10) +do x := 11 "asdf" "asdf" "asdf" +| // I don't know to work with those pipes... +for (x := 11; x = 1;) /* INLINE COMMENT */ "123456789ABCDEF" do x := 10 diff --git a/res/05-input-which-maybe-should-not-pass.txt b/res/05-input-which-maybe-should-not-pass.txt new file mode 100644 index 0000000..8a068ca --- /dev/null +++ b/res/05-input-which-maybe-should-not-pass.txt @@ -0,0 +1 @@ +dofor me 123asdf ||| )( := x y z "1alksdfhlsahdkflsd23" asdf123 // seems all good to me... diff --git a/res/generated-input.txt b/res/generated-input.txt new file mode 100644 index 0000000..3a55d29 --- /dev/null +++ b/res/generated-input.txt @@ -0,0 +1,2 @@ +// SEED: 1742551663 +for (6; 0; w := d) do 2 | for (68; 1; 1) do 77 diff --git a/src/dynamic-array.h b/src/dynamic-array.h new file mode 100644 index 0000000..6a02769 --- /dev/null +++ b/src/dynamic-array.h @@ -0,0 +1,59 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DA, COUNT) \ + ({ \ + if ((DA).count + (COUNT) > (DA).capacity) { \ + if ((DA).capacity == 0) \ + (DA).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DA).count + (COUNT) > (DA).capacity) \ + (DA).capacity *= 2; \ + (DA).items = REALLOC((DA).items, \ + (DA).capacity * \ + sizeof (*(DA).items)); \ + ASSERT((DA).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DA) \ + ({ \ + (DA).capacity = (DA).count; \ + (DA).items = REALLOC((DA).items, \ + (DA).capacity * \ + sizeof (*(DA).items)); \ + ASSERT((DA).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DA, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), 1); \ + (DA).items[(DA).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DA), (NEW_ITEMS_COUNT)); \ + memcpy ((DA).items + (DA).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \ + (DA).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DA) \ + (DA).items[(DA).count - 1] + +#define DYNAMIC_ARRAY_RESET(DA) ({ (DA).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DA) FREE((DA).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DA) for ( \ + typeof ((DA).items) ITEM = (DA).items; \ + ITEM < (DA).items + (DA).count; ++ITEM) + +#endif // INCLUDED_DYNAMIC_ARRAY_H diff --git a/src/export.c b/src/export.c new file mode 100644 index 0000000..3477ef6 --- /dev/null +++ b/src/export.c @@ -0,0 +1,19 @@ +#include +#include "utils.h" +#include "lexeme.h" +#include "lexer.c" + +int +main (int argc, char *argv[]) +{ + UNUSED (argc); + UNUSED (argv); + + for (enum lexeme_kind kind = 1; kind < LEXEME_KIND_COUNT; ++kind) { + printf ("- %s --- =%s=\n", + lexeme_kind_names[kind - 1], + lexeme_regex_strings[kind - 1]); + } + + return EXIT_SUCCESS; +} diff --git a/src/lex.c b/src/lex.c new file mode 100644 index 0000000..3b10266 --- /dev/null +++ b/src/lex.c @@ -0,0 +1,220 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utils.h" +#include "string-builder.h" +#include "lexer.h" + +const char *file; + +static void +print_lexing_error (const struct lexer *lexer, + const struct lexeme *lexeme, + const char *fmt, ...) +{ + const char *beginning_of_line = lexer->sv.beg; + size_t line = 1; + + for (const char *p = lexer->sv.beg; p < lexeme->sv.beg; ++p) { + if (*p == '\n') { + beginning_of_line = p + 1; + line += 1; + } + } + + fprintf (stderr, "%s:%d:%d: error: ", file, (int) line, + (int) (lexeme->sv.beg - beginning_of_line)); + va_list ap; + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + putc ('\n', stderr); + + const char *p = beginning_of_line; + fprintf (stderr, "%5lu | ", line); + while (*p != '\n') + putc (*p++, stderr); + putc ('\n', stderr); + + p = beginning_of_line; + fprintf (stderr, " | "); + while (p++ < lexeme->sv.beg) + putc (' ', stderr); + putc ('^', stderr); + while (p++ < lexeme->sv.end) + putc ('~', stderr); + putc ('\n', stderr); +} + +static int +display_to_byte_len (const char *str, int len) +{ + while (*str) { + if (*str++ & 0xD0) { + len += 1; + str += 1; + } + } + + return len; +} + +int +main (int argc, char *argv[]) +{ + const char *progname = *argv++; + if (argc < 2) DIE ("Usage: %s file", progname); + + file = *argv++; + int fd = open (file, O_RDONLY); + if (fd == -1) DIE ("error: %s: %s", strerror (errno), file); + + struct stat st; + fstat (fd, &st); + char *string = mmap (NULL, st.st_size + 1, PROT_READ, MAP_PRIVATE, fd, 0); + close (fd); + + puts ("Исходный текст:"); + fwrite (string, 1, st.st_size, stdout); + + FILE *dump = fopen ("./build/dump.txt", "w"); + + struct { + struct lexeme *items; + uint32_t count; + uint32_t capacity; + } invalid_lexemes = {0}; + + struct string_builder sb = {0}; + struct lexer lexer = lexer_create (string, st.st_size); + putchar ('\n'); + printf ("| *Лексема* | *Тип лексемы* | *Значение* |\n"); + printf ("|------------------+-----------------------------+------------|\n"); + for (struct lexeme lexeme = lexer_next_lexeme (&lexer); + lexeme.kind != LEXEME_KIND_END_OF_FILE; + lexeme = lexer_next_lexeme (&lexer)) { + switch (lexeme.kind) { + case LEXEME_KIND_INVALID: + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + case LEXEME_KIND_COMMENT_UNTERMINATED: + DYNAMIC_ARRAY_APPEND (invalid_lexemes, lexeme); + continue; + default: break; + } + + if (lexeme.kind == LEXEME_KIND_COMMENT) + continue; + + fwrite (lexeme.sv.beg, STRING_VIEW_LEN (lexeme.sv), 1, dump); + putc (' ', dump); + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: + string_builder_printf (&sb, "K[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_SYMBOL_COMPARISON: + string_builder_printf (&sb, "C[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_CONSTANT_INTEGER: + string_builder_printf (&sb, "%d", lexeme.value.integer); + break; + case LEXEME_KIND_CONSTANT_REAL: + string_builder_printf (&sb, "%g", lexeme.value.real); + break; + case LEXEME_KIND_CONSTANT_STRING: + string_builder_printf (&sb, "S[%d]", lexeme.value.table_index); + break; + case LEXEME_KIND_IDENTIFIER: + string_builder_printf (&sb, "I[%d]", lexeme.value.table_index); + break; + default: + STRING_BUILDER_APPEND_CSTR (sb, ""); + } + string_builder_append_ntimes (&sb, ' ', 10 - sb.count); + STRING_BUILDER_APPEND_NULL (sb); + printf ("| %-16.*s | %-*s | %s |\n", + (int) STRING_VIEW_LEN (lexeme.sv), lexeme.sv.beg, + display_to_byte_len (lexeme_kind_names[lexeme.kind - 1], 27), + lexeme_kind_names[lexeme.kind - 1], + sb.items); + STRING_BUILDER_RESET (sb); + } + + fclose (dump); + + putchar ('\n'); + printf ("| *№* | *K* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < KEYWORD_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, keyword_names[i]); + + putchar ('\n'); + printf ("| *№* | *C* |\n"); + printf ("|-----+-----|\n"); + for (int32_t i = 0; i < COMPARISON_COUNT; ++i) + printf ("| %3d | %-3s |\n", i, comparison_names[i]); + + putchar ('\n'); + printf ("| *№* | *S* |\n"); + printf ("|-----+----------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.constant_string_table) { + printf ("| %3ld | %-14.*s |\n", e - lexer.constant_string_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + putchar ('\n'); + printf ("| *№* | *I* |\n"); + printf ("|-----+------------------|\n"); + DYNAMIC_ARRAY_FOREACH (e, lexer.identifier_table) { + printf ("| %3ld | %-16.*s |\n", e - lexer.identifier_table.items, + (int) STRING_VIEW_LEN (*e), e->beg); + } + + DYNAMIC_ARRAY_FOREACH (invalid_lexeme, invalid_lexemes) { + switch (invalid_lexeme->kind) { + case LEXEME_KIND_INVALID: + print_lexing_error (&lexer, invalid_lexeme, "invalid lexeme `%.*s'", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + case LEXEME_KIND_CONSTANT_STRING_TOO_LONG: + print_lexing_error (&lexer, invalid_lexeme, + "string constant longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (invalid_lexeme->sv)); + break; + case LEXEME_KIND_IDENTIFIER_TOO_LONG: + print_lexing_error (&lexer, invalid_lexeme, + "identifier longer than 16 symbols (%d)", + (int) STRING_VIEW_LEN (invalid_lexeme->sv)); + break; + case LEXEME_KIND_CONSTANT_NUMBER_INVALID: + print_lexing_error (&lexer, invalid_lexeme, "invalid number constant `%.*s'", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + case LEXEME_KIND_COMMENT_UNTERMINATED: + invalid_lexeme->sv.end = invalid_lexeme->sv.beg + 2; + print_lexing_error (&lexer, invalid_lexeme, "unterminated comment", + (int) STRING_VIEW_LEN (invalid_lexeme->sv), + invalid_lexeme->sv.beg); + break; + default: break; + } + } + + munmap (string, st.st_size); + + return EXIT_SUCCESS; +} diff --git a/src/lexeme.c b/src/lexeme.c new file mode 100644 index 0000000..41ae8c8 --- /dev/null +++ b/src/lexeme.c @@ -0,0 +1,13 @@ +#include "lexeme.h" + +#define X(SYM, STR, ...) [LEXEME_KIND_##SYM - 1] = (STR), +const char *lexeme_kind_names[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X + +#define X(SYM, STR, ...) [KEYWORD_##SYM] = (STR), +const char *keyword_names[KEYWORD_COUNT] = { KEYWORDS () }; +#undef X + +#define X(SYM, STR, ...) [COMPARISON_##SYM] = (STR), +const char *comparison_names[COMPARISON_COUNT] = { COMPARISONS () }; +#undef X diff --git a/src/lexeme.h b/src/lexeme.h new file mode 100644 index 0000000..ebb8958 --- /dev/null +++ b/src/lexeme.h @@ -0,0 +1,74 @@ +#ifndef INCLUDED_LEXEME_H +#define INCLUDED_LEXEME_H + +#include +#include +#include "utils.h" +#include "string-view.h" + +// Входной язык содержит операторы цикла for (...; ...; ...) do, +// разделенные символом | (вертикальная полоса). Операторы цикла +// содержат идентификаторы, знаки сравнения <, >, =, строковые +// константы (последовательность символов в двойных кавычках), знак +// присваивания (:=). +#define LEXEME_KINDS() \ + X (KEYWORD, "Ключевое слово", "for|do" ) \ + X (IDENTIFIER_TOO_LONG, "Слишком длинный идентификатор", "[A-Z_a-z][0-9A-Z_a-z]{16,}" ) \ + X (IDENTIFIER, "Идентификатор", "[A-Z_a-z][0-9A-Z_a-z]*" ) \ + X (SYMBOL_SEPARATOR, "Символ вертикальной полосы", "\\|" ) \ + X (SYMBOL_ASSIGNMENT, "Знак присваивания", ":=" ) \ + X (SYMBOL_COMPARISON, "Знак операции сравнения", "<|=|>" ) \ + X (SYMBOL_PARENTHESIS_LEFT, "Знак левой скобки", "\\(" ) \ + X (SYMBOL_PARENTHESIS_RIGHT, "Знак правой скобки", "\\)" ) \ + X (SYMBOL_SEMICOLON, "Знак точки с запятой", ";" ) \ + X (CONSTANT_NUMBER_INVALID, "Недопустимая числовая константа", "-?[0-9]*\\.?[0-9]+[A-Z_a-z][0-9A-Z_a-z]+") \ + X (CONSTANT_INTEGER, "Целочиселная константа", "-?[0-9]+" ) \ + X (CONSTANT_REAL, "Вещественная константа", "-?[0-9]*\\.[0-9]+" ) \ + X (CONSTANT_STRING_TOO_LONG, "Слишком длинная строковая константа", "\"[^\"]{15,}\"" ) \ + X (CONSTANT_STRING, "Строковая константа", "\"[^\"]{0,14}\"" ) \ + X (COMMENT, "Комментарий", "//[^\n]*|/\\*+([^*]|\\*[^/])*\\*+/" ) \ + X (COMMENT_UNTERMINATED, "Незавершенный Комментарий", "/\\*([^*]|]\\*[^/])*" ) + +#define X(SYM, ...) LEXEME_KIND_##SYM, +enum lexeme_kind { + LEXEME_KIND_INVALID, + LEXEME_KINDS () + LEXEME_KIND_COUNT, + LEXEME_KIND_END_OF_FILE, +}; +#undef X + +#define KEYWORDS() \ + X (FOR, "for") \ + X (DO, "do") + +#define COMPARISONS() \ + X (EQUALS, "=") \ + X (LESS_THAN, "<") \ + X (GREATER_THAN, ">") + +#define X(SYM, ...) KEYWORD_##SYM, +enum keyword { KEYWORDS () KEYWORD_COUNT }; +#undef X + +#define X(SYM, ...) COMPARISON_##SYM, +enum comparison { COMPARISONS () COMPARISON_COUNT }; +#undef X + +struct lexeme { + struct string_view sv; + enum lexeme_kind kind; + union { + enum keyword keyword; + enum comparison comparison; + int integer; + float real; + uint32_t table_index; + } value; +}; + +extern const char *lexeme_kind_names[LEXEME_KIND_COUNT - 1]; +extern const char *keyword_names[KEYWORD_COUNT]; +extern const char *comparison_names[COMPARISON_COUNT]; + +#endif diff --git a/src/lexer.c b/src/lexer.c new file mode 100644 index 0000000..a219c91 --- /dev/null +++ b/src/lexer.c @@ -0,0 +1,172 @@ +#include "lexer.h" +#include +#include +#include +#include +#include +#include "dynamic-array.h" + +#define X(SYM, STR, REG) [LEXEME_KIND_##SYM - 1] = "^(" REG ")", +static const char *lexeme_regex_strings[LEXEME_KIND_COUNT - 1] = { LEXEME_KINDS () }; +#undef X + +static regex_t lexeme_regexes[LEXEME_KIND_COUNT - 1]; + +static void +print_regex_error (const regex_t *comp, const char *regex, int errcode) +{ + size_t length = regerror (errcode, comp, NULL, 0); + char *buffer = malloc (length); + regerror (errcode, comp, buffer, length); + fprintf (stderr, "error: regcomp (\"%s\"): %s\n", + regex, buffer); + free (buffer); +} + +static void __attribute__((constructor)) +compile_regexes (void) +{ + for (enum lexeme_kind kind = 1; kind < LEXEME_KIND_COUNT; ++kind) { + int errcode = regcomp (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + REG_EXTENDED); + if (errcode) { + print_regex_error (&lexeme_regexes[kind - 1], + lexeme_regex_strings[kind - 1], + errcode); + exit (1); + } + } +} + +struct lexer +lexer_create (const char *string, size_t len) +{ + return (struct lexer) { + .sv = { + .beg = string, + .end = string + len, + }, + .cursor = string, + .beginning_of_line = string, + .line = 0, + }; +} + +static void +lexer_skip_whitespace (struct lexer *lexer) +{ + while (lexer->cursor < lexer->sv.end && isspace (*lexer->cursor)) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} + +static void +lexer_progress_cursor_by (struct lexer *lexer, int count) +{ + const char *end = lexer->cursor + count; + ASSERT (end <= lexer->sv.end); + + while (lexer->cursor < end) { + if (*lexer->cursor == '\n') { + lexer->line += 1; + lexer->beginning_of_line = lexer->cursor + 1; + } + lexer->cursor += 1; + } +} + +struct lexeme +lexer_next_lexeme (struct lexer *lexer) +{ + lexer_skip_whitespace (lexer); + struct lexeme lexeme = { .sv.beg = lexer->cursor }; + + if (lexer->cursor >= lexer->sv.end) { + lexeme.kind = LEXEME_KIND_END_OF_FILE; + lexeme.sv.end = lexer->cursor; + return lexeme; + } + + regmatch_t regmatch; + enum lexeme_kind longest_matching_lexeme_kind = LEXEME_KIND_INVALID; + int longest_matching_lexeme_kind_length = 0; + for (enum lexeme_kind lexeme_kind = 1; lexeme_kind < LEXEME_KIND_COUNT; ++lexeme_kind) { + if (regexec (&lexeme_regexes[lexeme_kind - 1], lexer->cursor, 1, ®match, 0)) continue; + if (regmatch.rm_eo <= longest_matching_lexeme_kind_length) continue; + longest_matching_lexeme_kind_length = regmatch.rm_eo; + longest_matching_lexeme_kind = lexeme_kind; + } + + if (longest_matching_lexeme_kind) { + lexeme.kind = longest_matching_lexeme_kind; + lexer_progress_cursor_by (lexer, longest_matching_lexeme_kind_length); + lexeme.sv.end = lexer->cursor; + + switch (lexeme.kind) { + case LEXEME_KIND_KEYWORD: { + for (enum keyword keyword = 0; keyword < KEYWORD_COUNT; ++keyword) { + struct string_view keyword_sv = { + .beg = keyword_names[keyword], + .end = keyword_names[keyword] + strlen (keyword_names[keyword]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, keyword_sv)) continue; + + lexeme.value.table_index = keyword; + } + } break; + case LEXEME_KIND_SYMBOL_COMPARISON: { + for (enum comparison comparison = 0; comparison < COMPARISON_COUNT; ++comparison) { + struct string_view comparison_sv = { + .beg = comparison_names[comparison], + .end = comparison_names[comparison] + strlen (comparison_names[comparison]), + }; if (!STRING_VIEW_EQUALS (lexeme.sv, comparison_sv)) continue; + + lexeme.value.table_index = comparison; + } + } break; + case LEXEME_KIND_CONSTANT_INTEGER: { + TODO ("fix overflow"); + lexeme.value.integer = strtol (lexeme.sv.beg, NULL, 10); + } break; + case LEXEME_KIND_CONSTANT_REAL: + TODO ("fix overflow"); + lexeme.value.real = strtof (lexeme.sv.beg, NULL); + break; + case LEXEME_KIND_CONSTANT_STRING: { + struct string_view sv = { + .beg = lexeme.sv.beg + 1, + .end = lexeme.sv.end - 1, + }; + DYNAMIC_ARRAY_FOREACH (e, lexer->constant_string_table) { + if (STRING_VIEW_EQUALS (sv, *e)) { + lexeme.value.table_index = e - lexer->constant_string_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->constant_string_table.count; + DYNAMIC_ARRAY_APPEND (lexer->constant_string_table, sv); + } break; + case LEXEME_KIND_IDENTIFIER: { + DYNAMIC_ARRAY_FOREACH (e, lexer->identifier_table) { + if (STRING_VIEW_EQUALS (lexeme.sv, *e)) { + lexeme.value.table_index = e - lexer->identifier_table.items; + return lexeme; + } + } + lexeme.value.table_index = lexer->identifier_table.count; + DYNAMIC_ARRAY_APPEND (lexer->identifier_table, lexeme.sv); + } break; + default: + break; + } + + return lexeme; + } + + lexeme.sv.end = ++lexer->cursor; + return lexeme; +} diff --git a/src/lexer.h b/src/lexer.h new file mode 100644 index 0000000..563dc60 --- /dev/null +++ b/src/lexer.h @@ -0,0 +1,26 @@ +#ifndef INCLUDED_LEXER_H +#define INCLUDED_LEXER_H + +#include +#include "utils.h" +#include "lexeme.h" + +struct string_view_table { + struct string_view *items; + uint32_t count; + uint32_t capacity; +}; + +struct lexer { + struct string_view sv; + const char *cursor; + const char *beginning_of_line; + size_t line; + struct string_view_table constant_string_table; + struct string_view_table identifier_table; +}; + +extern struct lexer lexer_create (const char *string, size_t len); +extern struct lexeme lexer_next_lexeme (struct lexer *); + +#endif diff --git a/src/string-builder.c b/src/string-builder.c new file mode 100644 index 0000000..5880da8 --- /dev/null +++ b/src/string-builder.c @@ -0,0 +1,41 @@ +#include "string-builder.h" +#include +#include + +void +string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n) +{ + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n); + memset (sb->items + sb->count, c, n); + sb->count += n; +} + +void +string_builder_append_cstrs (STRING_BUILDER sb, ...) +{ + va_list args; + + va_start (args, sb); + const char *arg = va_arg (args, const char *); + while (arg) { + STRING_BUILDER_APPEND_CSTR(*sb, arg); + arg = va_arg (args, const char *); + } va_end (args); +} + +void +string_builder_printf (STRING_BUILDER sb, const char *format, ...) +{ + va_list args; + + va_start (args, format); + int size = vsnprintf (NULL, 0, format, args); + va_end (args); + ASSERT (size >= 0); + + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1); + va_start (args, format); + vsnprintf (&sb->items[sb->count], size + 1, format, args); + va_end (args); + sb->count += size; +} diff --git a/src/string-builder.h b/src/string-builder.h new file mode 100644 index 0000000..6834eed --- /dev/null +++ b/src/string-builder.h @@ -0,0 +1,42 @@ +#ifndef INCLUDED_STRING_BUILDER_H +#define INCLUDED_STRING_BUILDER_H + +#include +#include +#include "utils.h" +#include "dynamic-array.h" + +struct string_builder { + char *items; + size_t count; + size_t capacity; +}; +#define STRING_BUILDER struct string_builder * + +#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \ + DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE) + +#define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \ + ({ \ + const char *s = (CSTR); \ + size_t n = strlen (s); \ + DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \ + }) + +#define STRING_BUILDER_APPEND_CSTRS(SB, ...) \ + string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL) + +#define STRING_BUILDER_APPEND_NULL(SB) \ + DYNAMIC_ARRAY_APPEND (SB, '\0') + +#define STRING_BUILDER_RESET(SB) \ + DYNAMIC_ARRAY_RESET (SB) + +#define STRING_BUILDER_FREE(SB) \ + DYNAMIC_ARRAY_FREE(SB) + +extern void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n); +extern void string_builder_append_cstrs (STRING_BUILDER, ...); +extern void string_builder_printf (STRING_BUILDER, const char *format, ...); + +#endif diff --git a/src/string-view.h b/src/string-view.h new file mode 100644 index 0000000..c745d12 --- /dev/null +++ b/src/string-view.h @@ -0,0 +1,16 @@ +#ifndef INCLUDED_STRING_VIEW_H +#define INCLUDED_STRING_VIEW_H + +#include + +struct string_view { + const char *beg; + const char *end; +}; + +#define STRING_VIEW_LEN(SV) ((SV).end - (SV).beg) +#define STRING_VIEW_EQUALS(A, B) \ + (STRING_VIEW_LEN (A) == STRING_VIEW_LEN (B) && \ + !memcmp ((A).beg, (B).beg, STRING_VIEW_LEN (A))) + +#endif // INCLUDED_STRING_VIEW_H diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..68bb2b5 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,26 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include + +#define UNUSED(X) ((void) (X)) +#define UNREACHABLE() ASSERT (!"reached the unreachable...") +// #define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__) +#define TODO(...) + +#define ASSERT assert +#define REALLOC realloc +#define FREE free + +#define DIE(FMT, ...) \ + ({ \ + fprintf (stderr, FMT "\n" __VA_OPT__(,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + }) + +#define ARRAY_LEN(array) (sizeof (array)/sizeof (*array)) +#define ARRAY_GET(array, index) \ + (ASSERT(index >= 0), ASSERT(index < ARRAY_LEN(array)), array[index]) + +#endif -- cgit v1.3.1