diff --git a/lab4/.gitignore b/lab4/.gitignore new file mode 100644 index 0000000..f7ea855 --- /dev/null +++ b/lab4/.gitignore @@ -0,0 +1,4 @@ +*.zip +*.cmil +cmilan/src/cmilan.exe +!cmilan/doc/cmilan.pdf diff --git a/lab4/cmilan/doc/Makefile b/lab4/cmilan/doc/Makefile new file mode 100644 index 0000000..a4b4448 --- /dev/null +++ b/lab4/cmilan/doc/Makefile @@ -0,0 +1,10 @@ +cmilan.pdf: cmilan.tex + pdflatex cmilan.tex + pdflatex cmilan.tex + pdflatex cmilan.tex + +clean: + rm -f cmilan.aux + rm -f cmilan.toc + rm -f cmilan.log + diff --git a/lab4/cmilan/doc/cmilan.pdf b/lab4/cmilan/doc/cmilan.pdf new file mode 100644 index 0000000..172d61b Binary files /dev/null and b/lab4/cmilan/doc/cmilan.pdf differ diff --git a/lab4/cmilan/doc/cmilan.tex b/lab4/cmilan/doc/cmilan.tex new file mode 100644 index 0000000..2a23eea --- /dev/null +++ b/lab4/cmilan/doc/cmilan.tex @@ -0,0 +1,956 @@ +\documentclass[a4paper,12pt]{article} +\usepackage{ucs} +\usepackage{cmap} +\usepackage[utf8x]{inputenc} +\usepackage[T2A]{fontenc} +\usepackage[english,russian]{babel} +\usepackage[hmargin=2cm,vmargin=2cm]{geometry} +\usepackage{indentfirst} +\usepackage{listings} +\usepackage{syntax} +\usepackage[section]{placeins} + +\setlength{\grammarparsep}{10pt plus 1pt minus 1pt} +\setlength{\grammarindent}{9em} + +\lstset{ + frame=TB, + morekeywords={begin,end,if,then,else,fi,while,do,od,write,read} +} + +\title{Компилятор \textsc{CMilan}} +\author{Э. Ф. Аллахвердиев, Д. А. Тимофеев} + +\begin{document} +\maketitle +\tableofcontents + +\section{Обзор языка Милан} + +Язык Милан --- учебный язык программирования, описанный в +учебнике~\cite{karpov05}. + +Программа на Милане представляет собой последовательность операторов, +заключенных между ключевыми словами \texttt{begin} и \texttt{end}. Операторы +отделяются друг от друга точкой с запятой. После последнего оператора в блоке +точка с запятой не ставится. Компилятор \textsc{CMilan} не учитывает регистр +символов в именах переменных и ключевых словах. + +В базовую версию языка Милан входят следующие конструкции: константы, +идентификаторы, арифметические операции над целыми числами, операторы чтения +чисел со стандартного ввода и печати чисел на стандартный вывод, оператор +присваивания, условный оператор, оператор цикла с предусловием. + +Программа может содержать комментарии, которые могут быть многострочными. +Комментарий начинается символами `\texttt{/*}' и заканчивается символами +`\texttt{*/}'. Вложенные комментарии не допускаются. + +Грамматика языка Милан в расширенной форме Бэкуса-Наура приведена на +рисунке~\ref{milan-grammar}. + +\begin{figure} +\begin{grammar} + + ::= `begin' `end' + + ::= `;' + \alt $\epsilon$ + + ::= `:=' + \alt `if' `then' [`else' ] `fi' + \alt `while' `do' `od' + \alt `write' `(' `)' + + ::= \{ \} + + ::= \{ \} + + ::= | | `(' `)' + + ::= + + ::= `+' | `-' + + ::= `*' | `/' + + ::= `=' | `!=' | `<' | `<=' | `>' | `>=' + + ::= \{ | \} + + ::= `a' | `b' | `c' | \ldots | `z' | `A' | `B' | `C' | \ldots | `Z' + + ::= `0' | `1' | `2' | `3' | `4' | `5' | `6' | `7' | `8' | `9' + +\end{grammar} +\label{milan-grammar} +\caption{Грамматика языка Милан} +\end{figure} + +\subsection{Константы} + +В языке реализована поддержка знаковых целочисленных констант. Синтаксически +константы представляют собой последовательность цифр, перед которой может +находиться знак `-'. Примеры констант: \texttt{0}, \texttt{9}, \texttt{1234}, +\texttt{-19}, \texttt{-0}. + +\subsection{Идентификаторы} + +Идентификаторы представляют собой последовательность букв латинского алфавита и +цифр. Первым символом идентификатора должна быть буква. Максимальная длина +идентификатора ограничена 63 символами. Регистр символов не учитывается. +Идентификаторы не должны совпадать с ключевыми словами \texttt{begin}, +\texttt{end}, \texttt{if}, \texttt{then}, \texttt{else}, \texttt{fi}, +\texttt{do}, \texttt{od}, \texttt{while}, \texttt{read}, \texttt{write}. + +Примеры идентификаторов: \texttt{a}, \texttt{X}, \texttt{GCD}, \texttt{Milan23}. +Цепочки символов, недопустимые в качестве идентификаторов: \texttt{12a} (первый +символ не является буквой), \texttt{Begin} (цепочка символов совпадает с +ключевым словом), \texttt{a\_1} (цепочка содержит символ подчеркивания). + +\subsection{Арифметические выражения} + +\begin{grammar} + ::= \{ \} + + ::= \{ \} + + ::= | | `(' `)' +\end{grammar} + +Арифметические выражения строятся по традиционным для языков программирования +правилам. Элементами арифметических выражений могут быть константы, +идентификаторы, знаки арифметических операций `\texttt{+}' (сложение), +`\texttt{-}' (вычитание), `\texttt{*}' (умножение), `\texttt{/}' +(деление), скобки и ключевое слово \texttt{read}, которое обозначает операцию +чтения числа со стандартного ввода. + +Примеры правильных выражений: \texttt{12 + 4}, \texttt{i}, \texttt{(x+1)*y}, +\texttt{2*x+1}, \texttt{read}, \texttt{read * (x - read)}. + +Операции `\texttt{*}' и `\texttt{/}' имеют более высокий приоритет, чем +операции `\texttt{+}' и `\texttt{-}'. Все эти операции левоассоциативны. + +Значения арифметических выражений вычисляются слева направо с учетом приоритета +операций. Порядок вычисления важен из-за присутствия операции \texttt{read}, +благодаря которой вычисление значения выражения имеет побочный эффект. + +\subsection{Печать чисел на стандартный вывод} + +\begin{grammar} + ::= `write' `(' `)' +\end{grammar} + +Печать чисел осуществляется с помощью оператора \texttt{write}, аргументом +которого является произвольное арифметическое выражение. Примеры использования +оператора \texttt{write}: \texttt{write(5)}, +\texttt{write(n+7)}, \texttt{write((2+read)*3)}, \texttt{write(read)}. + +\subsection{Оператор присваивания} + +\begin{grammar} + ::= `:=' +\end{grammar} + +При выполнении оператора присваивания сначала вычисляется значение выражения, +записанного в его правой части. Затем результат записывается в ячейку памяти, +соответствующую переменной в левой части оператора присваивания. + +Последовательность символов `\texttt{:=}' является неделимой и не может +содержать пробелов между символами `\texttt{:}' и `\texttt{=}'. + +Примеры корректных операторов присваивания: \texttt{a := b + 1}, \texttt{c := +read}. + +\subsection{Условный оператор} + +\begin{grammar} + ::= `if' `then' [`else' ] `fi' + + ::= + + ::= `=' | `!=' | `<' | `<=' | `>' | `>=' +\end{grammar} + +Условный оператор включает: +\begin{enumerate} +\item условие, которое представляет собой проверку на равенство или неравенство +двух арифметических выражений, +\item последовательность операторов, которая должна быть выполнена, если условие +истинно (блок \texttt{then}), +\item необязательную последовательность операторов, которая должна быть +выполнена, если условие ложно (блок \texttt{else}). +\end{enumerate} + +Проверка условия $a ? b$, где $a$ и $b$ --- арифметические выражения, а <<$?$>> +--- один из операторов сравнения, производится следующим образом: +\begin{enumerate} +\item вычисляется значение выражения $a$; +\item вычисляется значение выражения $b$; +\item проверяется выполнение условия. +\end{enumerate} + +Поддерживаются следующие отношения: `\texttt{=}' (<<равно>>), `\texttt{!=}' +(<<не равно>>), `\texttt{<}' (<<меньше>>), `\texttt{<=}' (<<меньше или равно>>), +`\texttt{>}' (<<больше>>), `\texttt{>=}' (<<больше или равно>>). + +Условный оператор завершается ключевым словом \texttt{fi}. Оно используется, +чтобы избежать известной проблемы <<висячего else>>, которая встречается, в +частности, в языках C, C++ и Java. Наличие <<закрывающей скобки>> \texttt{fi} +позволяет однозначно интерпретировать вложенные условные операторы. + +Примеры использования условного оператора приведены на рисунках~\ref{ifthen} и +\ref{ifthenelse}. Обе эти программы считывают со стандартного ввода два числа. +Программа на рисунке~\ref{ifthen} печатает наибольшее из двух чисел. Программа +на рисунке~\ref{ifthenelse} печатает числа в порядке возрастания. + +\begin{figure} +\begin{lstlisting} +begin + x := read; + y := read; + max := x; + if y > max then + max := y + fi; + write (max) +end +\end{lstlisting} +\label{ifthen} +\caption{Пример условного оператора \texttt{if..then..fi}} +\end{figure} + +\begin{figure} +\begin{lstlisting} +begin + x := read; + y := read; + if x <= y then + write (x); + write (y) + else + write (y); + write (x) + fi +end +\end{lstlisting} +\label{ifthenelse} +\caption{Пример условного оператора \texttt{if..then..else..fi}} +\end{figure} + +\subsection{Цикл с предусловием} + +\begin{grammar} + ::= `while' `do' `od' + + ::= + + ::= `=' | `!=' | `<' | `<=' | `>' | `>=' +\end{grammar} + +При выполнении цикла с предусловием сначала проверяется, истинно ли условие. +Если оно истинно, последовательно выполняются операторы, составляющие тело +цикла. После того, как последний оператор будет выполнен, управление снова +возвращается к проверке условия. Если условие оказывается ложным, выполнение +цикла завершается. Вычисление выражений, необходимых для проверки условия, +производится так же, как и при выполнении условного оператора. + +Пример программы, использующей цикл, приведен на рисунке~\ref{while}. Эта +программа считывает со стандартного ввода число и печатает его факториал. + +\begin{figure} +\begin{lstlisting} +begin + n := read; + factorial := 1; + x := 1; + while x <= n do + factorial := factorial * x; + x := x + 1 + od; + write (factorial) +end +\end{lstlisting} +\label{while} +\caption{Пример цикла с предусловием} +\end{figure} + +\section{Использование компилятора} + +Компилятор \textsc{CMilan} преобразует программы на языке Милан в +последовательность команд виртуальной машины Милана. Общее описание виртуальной +машины можно найти в учебнике~\cite{karpov05}, а более детальное +описание --- или в документации, прилагаемой к исходным текстам виртуальной +машины. + +Исполняемый файл компилятора называется \texttt{cmilan} (в операционных системах +семейства Unix) или \texttt{cmilan.exe} (в Windows). Компилятор имеет интерфейс +командной строки. Чтобы скомпилировать программу, записанную в файле +<>, нужно выполнить команду <<\texttt{cmilan program.mil}>>. +Результатом работы компилятора является либо последовательность команд для +виртуальной машины Милана, которая печатается на стандарный вывод, либо набор +сообщений о синтаксических ошибках, которые выводятся в стандартный поток +ошибок. + +При вызове программы \texttt{cmilan} без параметров компилятор печатает краткую +информацию о порядке его вызова. + +Чтобы сохранить генерируемую компилятором программу для виртуальной машины в +файл, достаточно перенаправить в этот файл стандартный поток вывода. + +На рисунке~\ref{cmilan-usage} приведен пример сеанса работы с компилятором. + +\begin{figure} +\begin{verbatim} +bash$ cat factorial.mil +BEGIN + n := READ; + factorial := 1; + i := 1; + WHILE i <= n DO + factorial := factorial * i; + i := i + 1 + OD; + WRITE(factorial) +END +bash$ cmilan factorial.mil > factorial.out +bash$ milanvm factorial.out +Reading input from factorial.out +> 5 +120 +\end{verbatim} +\label{cmilan-usage} +\caption{Пример использования компилятора \textsc{CMilan}} +\end{figure} + +\subsection{Сборка компилятора в Unix} + +Для сборки компилятора в операционных системах семейства Unix (в частности, +GNU/Linux и FreeBSD) необходим компилятор C++, в качестве которого рекомендуется +использовать GCC, и GNU Make. Для сборки компилятора достаточно перейти в +каталог \texttt{src}, в котором расположены исходные тексты компилятора +\textsc{CMilan}, и выполнить команду \texttt{make}. + +\subsection{Сборка компилятора в Windows} + +Для сборки компилятора \textsc{CMilan} в Windows можно использовать компилятор +GCC или Microsoft Visual Studio. При использовании GCC (Cygwin, MinGW) сборка +производится так же, как и в Unix. Для сборки компилятора с помощью Visual +Studio 2010 в дистрибутив компилятора включены файлы проекта (каталог +\texttt{src\\cmilan\_vs2011}). Если необходимо использовать другие версии Visual +Studio, достаточно создать пустой проект консольного приложения Win32 и добавить +в проект существующие исходные тексты из каталога \texttt{src}. + +\section{Устройство компилятора} + +\subsection{Архитектура компилятора} +Компилятор \textsc{CMilan} включает три компонента: +\begin{enumerate} +\item лексический анализатор; +\item синтаксический анализатор; +\item генератор команд виртуальной машины Милана. +\end{enumerate} + +Лексический анализатор посимвольно читает из входного потока текст программы и преобразует +группы символов в лексемы (терминальные символы грамматики языка Милан). При +этом он отслеживает номер текущей строки, который используется синтаксическим +анализатором при формировании сообщений об ошибках. Также лексический анализатор +удаляет пробельные символы и комментарии. При формировании лексем анализатор +идентифицирует ключевые слова и последовательности символов (например, оператор +присваивания), а также определяет значения числовых констант и имена переменных. +Эти значения становятся значениями атрибутов, связанных с лексемами. + +Синтаксический анализатор читает сформированную лексическим анализатором +последовательность лексем и проверяет ее соответствие грамматике языка Милан. +Для этого используется метод рекурсивного спуска. Если в процессе +синтаксического анализа обнаруживается ошибка, анализатор формирует сообщение об +ошибке, включающее сведения об ошибке и номер строки, в которой она возникла. +В процессе анализа программы синтаксический анализатор генерирует набор машинных +команд, соответствующие каждой конструкции языка. + +Генератор кода представляет собой служебный компонент, ответственный за +формирование внешнего представления генерируемого кода. Генератор поддерживает +буфер команд и предоставляет синтаксическому анализатору набор функций, +позволяющий записать указанную команду по определенному адресу. После того, как +синтаксический анализатор заканчивает формирование программы, генератор кода +используется для печати на стандартный вывод отсортированной по возрастанию +адресов последовательности инструкций. Использование генератора кода несколько +упрощает устройство компилятора, поскольку синтаксический анализатор может +генерировать команды не в порядке их следования в программе, а по мере получения +всей необходимой информации для их формирования. Это особенно важно при +трансляции таких инструкций, как условные операторы или циклы. + +Все три компонента объединяются <<драйвером>> --- управляющей программой +компилятора. Драйвер анализирует аргументы командной строки, инициализирует +синтаксический анализатор и вызывает его метод \texttt{parse()}, запуская +процесс трансляции. + +\textsc{CMilan} является примером простейшего однопроходного компилятора, +в котором синтаксический анализ и генерация кода выполняются совместно. При этом +компилятор никак не оптимизирует код. Реальные компиляторы +обычно выполняют трансляцию и оптимизацию кода в несколько проходов, используя +несколько видов внутреннего представления программы. Сведения об архитектуре +таких компиляторов можно найти, в частности, в классической <<книге +дракона>>~\cite{dragonbook11}. В случае \textsc{CMilan}, тем не менее, +предпочтение было отдано не качеству генерируемого кода, а простоте реализации и +легкости расширения. + +\subsection{Генератор кода} + +Основной задачей генератора кода является хранение и заполнение буфера +инструкций последовательностью команд для виртуальной машины Милана. Генератор +кода не отвечает за правильность этой последовательности и не выполняет никаких +семантических преобразований. Тем не менее, генератор кода вполне мог бы быть +расширен для того, чтобы выполнять простые оптимизации на уровне машинных +команд. + +Генератор кода описан в файлах \texttt{codegen.h} и \texttt{codegen.cpp}. Его +реализация состоит из двух классов. Класс \texttt{Command} описывает машинные +инструкций и отвечает за их вывод. В классе Codegen реализованы функции добавления +инструкций в буфер, получения текущего адреса в буфере, резервирования ячейки +для инструкции, которая должна быть добавлена в код позднее, и печати +последовательности инструкций из буфера на стандартный вывод. + +Приведем краткое описание методов генератора кода. +\begin{itemize} +\item \texttt{void Command::print(int address, ostream\& os)} + + Печать инструкции с указанием адреса \texttt{address} в поток вывода \texttt{os}. + +\item \texttt{void CodeGen::emit(Instruction instruction)} + + Добавление инструкции \texttt{instruction} без аргументов в конец буфера. + +\item \texttt{void CodeGen::emit(Instruction instruction, int arg)} + + Добавление инструкции \texttt{instruction} с аргументом \texttt{arg} в конец буфера. + +\item \texttt{void CodeGen::emitAt(int address, Instruction instruction)} + + Запись инструкции \texttt{instruction} без аргументов в буфер со смещением + \texttt{address}. + +\item \texttt{void CodeGen::emitAt(int address, Instruction instruction, int +arg)} + + Запись инструкции \texttt{instruction} с аргументом \texttt{arg} в буфер + со смещением \texttt{address} + +\item \texttt{int CodeGen::getCurrentAddress()} + + Возврат адреса, по которому будет записана очередная инструкция. + +\item \texttt{int CodeGen::reserve()} + + Резервирование ячейки памяти для инструкции. Метод добавляет в конец + буфера инструкцию \texttt{NOP} и возвращает ее адрес. + +\item \texttt{void CodeGen::flush()} + + Вывод последовательности инструкций в выходной поток. +\end{itemize} + +\subsection{Лексический анализатор} + +Лексический анализатор преобразует считываемые из входного потока символы в +лексемы языка Милан. Например, последовательность символов `\texttt{B}', +`\texttt{E}', `\texttt{G}', `\texttt{I}', `\texttt{N}' соответствует ключевому +слову `\texttt{begin}'. Каждой лексеме соответствует отдельный элемент +перечислимого типа \texttt{Token}. В частности, ключевому слову `\texttt{begin}' +соответствует константа \texttt{T\_BEGIN}. С некоторыми лексемами связана +дополнительная информация --- значение атрибута. Так, с лексемой +\texttt{T\_NUMBER} (целочисленная константа) связано число, равное значению этой +константы, а с лексемой \texttt{T\_IDENTIFIER} (идентификатор) --- строка, +содержащая имя переменной. + +В таблице~\ref{lexemes} приведен полный список лексем и значений связанных с ними +атрибутов. + +\begin{table} +\begin{center} +\begin{tabular}{|l|l|p{6cm}|} +\hline +\hline +Имя лексемы & Значение & Атрибут \\ +\hline +\hline +\texttt{T\_EOF} & Конец текстового потока & \\ +\hline +\texttt{T\_ILLEGAL} & Недопустимый символ & \\ +\hline +\texttt{T\_IDENTIFIER}& Идентификатор & Имя переменной \\ +\hline +\texttt{T\_NUMBER} & Константа & Значение константы \\ +\hline +\texttt{T\_BEGIN} & Ключевое слово `\texttt{begin}' & \\ +\hline +\texttt{T\_END} & Ключевое слово `\texttt{end}' & \\ +\hline +\texttt{T\_IF} & Ключевое слово `\texttt{if}' & \\ +\hline +\texttt{T\_THEN} & Ключевое слово `\texttt{then}' & \\ +\hline +\texttt{T\_ELSE} & Ключевое слово `\texttt{else}' & \\ +\hline +\texttt{T\_FI} & Ключевое слово `\texttt{fi}' & \\ +\hline +\texttt{T\_WHILE} & Ключевое слово `\texttt{while}' & \\ +\hline +\texttt{T\_DO} & Ключевое слово `\texttt{do}' & \\ +\hline +\texttt{T\_OD} & Ключевое слово `\texttt{od}' & \\ +\hline +\texttt{T\_WRITE} & Ключевое слово `\texttt{write}' & \\ +\hline +\texttt{T\_READ} & Ключевое слово `\texttt{read}' & \\ +\hline +\texttt{T\_ASSIGN} & Оператор `\texttt{:=}' & \\ +\hline +\texttt{T\_ADDOP} & Операция типа сложения & +\texttt{A\_PLUS}~(`\texttt{+}'), \texttt{A\_MINUS}~(`\texttt{-}') \\ +\hline +\texttt{T\_MULOP} & Операция типа умножения & +\texttt{A\_MULTIPLY}~(`\texttt{*}'), \texttt{A\_DIVIDE}~(`\texttt{/}') \\ +\hline +\texttt{T\_CMP} & Оператор отношения & +\texttt{C\_EQ}~(`\texttt{=}'), \texttt{C\_NE}~(`\texttt{!=}'), +\texttt{C\_LT}~(`\texttt{<}'), \texttt{C\_LE}~(`\texttt{<=}'), +\texttt{C\_GT}~(`\texttt{>}'), \texttt{C\_GE}~(`\texttt{=}') \\ +\hline +\texttt{T\_LPAREN} & Открывающая скобка & \\ +\hline +\texttt{T\_RPAREN} & Закрывающая скобка & \\ +\hline +\texttt{T\_SEMICOLON} & `\texttt{;}' & \\ +\hline +\hline +\end{tabular} +\end{center} +\caption{Лексемы языка Милан} +\label{lexemes} +\end{table} + +Все ключевые слова перечислены в ассоциативном массиве \texttt{keywords\_}. При +этом ключом является строка, соответствующая ключевому слову в нижнем регистре, +а значением --- соответствующая лексема. С помощью массива \texttt{tokenNames\_} +каждой лексеме сопоставлено ее строковое внешнее представление, которое +используется при формировании сообщений об ошибках. Последовательность +символов, не соответствующая ни одной из лексем, считается ошибочной. В этом +случае лексический анализатор возвращает значение \texttt{T\_ILLEGAL}. + +Исходный текст лексического анализатора находится в файлах \texttt{scanner.h} и +\texttt{scanner.cpp}. Алгоритм лексического анализа реализован в классе +\texttt{Scanner}. Он содержит следующие открытые методы: + +\begin{itemize} +\item \texttt{Token token()} + + Получение текущей лексемы. Одна и та же лексема может быть прочитана + многократно. + +\item \texttt{void nextToken()} + + Переход к следующей лексеме. + +\item \texttt{int getIntValue()} + + Получение целочисленного атрибута текущей лексемы. В базовой версии Милана + этот метод используется только для получения значений целочисленных + констант. + +\item \texttt{string getStringValue()} + + Получение строкового атрибута текущей лексемы. В базовой версии Милана + этот метод используется для получения имен идентификаторов. + +\item \texttt{Cmp getCmpValue()} + + Получение кода операции сравнения текущей лексемы (используется только + вместе с лексемой \texttt{T\_CMP}). + +\item \texttt{Arithmetic getArithmeticValue()} + + Получение кода арифметической операции (используется вместе с лексемами + \texttt{T\_ADDOP} и \texttt{T\_MULOP}). + +\item \texttt{const int getLineNumber()} + + Получение номера текущей строки в исходном файле (используется при + формировании сообщений об ошибках). +\end{itemize} + +Поля класса описывают состояние лексического анализатора: +\begin{itemize} +\item \texttt{const string fileName\_} + + Имя входного файла. + +\item \texttt{int lineNumber\_} + + Номер текущей строки в анализируемой программе. + +\item \texttt{Token token\_} + + Текущая лексема. + +\item \texttt{int intValue\_} + + Целочисленный атрибут лексемы. + +\item \texttt{string stringValue\_} + + Строковый атрибут лексемы. + +\item \texttt{Cmp cmpValue\_} + + Код оператора сравнения. + +\item \texttt{Arithmetic arithmeticValue\_} + + Код арифметической операции. + +\item \texttt{map keywords\_} + + Ассоциативный массив, описывающий ключевые слова языка Милан. Используется + при обнаружении цепочки символов, которая может быть как идентификатором, + так и ключевым словом. + +\item \texttt{ifstream input\_} + + Входной поток для чтения из файла. + +\item \texttt{char ch\_} + + Очередной символ программы. +\end{itemize} + +Закрытые методы класса (служебные функции): +\begin{itemize} +\item \texttt{bool isIdentifierStart(char c)} + + Метод возвращает значение \texttt{true}, если символ \texttt{c} может быть + первым символом идентификатора (в базовой версии языка Милан это означает, + что символ является буквой латинского алфавита). + +\item \texttt{bool isIdentifierBody(char c)} + + Метод возвращает значение \texttt{true}, если символ \texttt{c} может + быть частью идентификатора. В базовой версии языка Милан эт означает, что + символ является буквой латинского алфавита или цифрой. + +\item \texttt{void skipSpace()} + + Пропуск всех пробельных символов (символов пробела, табуляции, перевода + строки). При чтении символа перевода строки увеличивается номер текущей + строки \texttt{lineNumber\_}. + +\item \texttt{void nextChar()} + + Переход к следующему символу программы. +\end{itemize} + +Основная часть алгоритма лексического анализа реализована в методе +\texttt{nextToken}. Для того, чтобы перейти к следующей лексеме, выполняется +следующая последовательность действий, + +Прежде всего необходимо удалить пробелы и комментарии. Признаком начала +комментария является последовательность символов `\texttt{/*}'. При обнаружении +символа `\texttt{/}' необходимо проверить следующий за ним символ. Если он не +совпадает с `\texttt{*}', значит, был найден оператор деления. В этом случае +переменной \texttt{token\_} присваивается значение \texttt{T\_MULOP}, а атрибуту +\texttt{arithmeticValue\_} --- значение \texttt{A\_DIVIDE}. Если за символом +`\texttt{/}' непосредственно следует `\texttt{*}', лексический анализатор +пропускает все символы, пока не встретит закрывающую комментарий +последовательность `\texttt{*/}' или конец файла. После того, как был найден +признак конца комментария, еще раз вызывается функция \texttt{skipSpace}. +Операция удаления комментариев повторяется многократно, пока очередной +непробельный символ не окажется отличным от символа `\texttt{/}'. Если в +процессе удаления пробелов или комментариев был встречен конец файла, очередной +лексемой считается \texttt{T\_EOF}. + +После удаления пробелов и комментариев происходит анализ очередного символа. Он +выполняется по следующим правилам. +\begin{enumerate} +\item Если символ является цифрой, то очередная лексема --- целочисленная константа +(\texttt{T\_NUMBER}). Лексический анализатор считывает из входного потока эту +и все следующие за ней цифры, преобразуя полученную последовательность в целое +число. Это число становится значением атрибута \texttt{intValue\_}. + +\item Если символ может быть началом идентификатора, из потока считываются все +последующие символы, которые могут быть частью идентификатора. Полученная +последовательность проверяется на совпадение с ключевым словом. В случае +совпадения очередной лексемой считается лексема, соответствующая этому ключевому +слову. Если цепочка символов не совпала ни с одним ключевым словом, очередная +лексема считается идентификатором (\texttt{T\_IDENTIFIER}), а сама цепочка +становится значением строкового атрибута \texttt{stringValue\_}. + +\item Если символ равен `\texttt{:}', лексический анализатор считывает следующий +символ и проверяет, что он равен `\texttt{=}'. В этом случае возвращается +лексема \texttt{T\_ASSIGN}. Если следом за `\texttt{:}' идет любой другой +символ, лексема считается ошибочной (\texttt{T\_ILLEGAL}). + +\item Если символ равен `\texttt{!}', производится аналогичная проверка на +равенство следующего символа `\texttt{=}'. В случае успеха текущей лексемой +становится лексема \texttt{T\_CMP}, а атрибут \texttt{cmpValue\_} принимает +значение \texttt{T\_NE}. + +\item Если символ равен `\texttt{<}', `\texttt{>}' или `\texttt{=}', текущей +лексемой становится \texttt{T\_CMP}. Чтобы определить значение атрибута +\texttt{cmpValue\_}, лексический анализатор может прочитать еще один символ для +того, чтобы отличить оператор `\texttt{<}' от оператора `\texttt{>}', а оператор +`\texttt{>}' от оператора `\texttt{>=}'. + +\item Если символ равен `\texttt{+}' или `\texttt{-}', переменная +\texttt{token\_} принимает значение \texttt{T\_ADDOP}, при этом соответствующим +образом устанавливается значение атрибута \texttt{arithmeticValue\_}. Аналогично +обрабатываются символ `\texttt{*}' (лексема \texttt{T\_MULOP}). Оператор деления +обрабатывать таким же образом не нужно, поскольку он обнаруживается в ходе +удаления комментариев. + +\item Если символ совпадает с `\texttt{;}', `\texttt{(}', `\texttt{)}', +очередная лексема устанавливается в соответствующее символу значение. +\end{enumerate} + +\subsection{Синтаксический анализатор} + +Задачами синтаксического анализатора является проверка соответствия программы +грамматике языка Милан (рисунок~\ref{milan-grammar}) и формирование кода для +виртуальной машины Милана в соответствии со структурой программы. Синтаксический +анализ выполняется методом рекурсивного спуска. Каждому нетерминальному символу +грамматики сопоставлен метод, выполняющий проверку соответствия +последовательности лексем одному из тех правил грамматики, в левой части которых +стоит данный нетерминальный символ. Семантические действия (генерация кода) +встроены в код метода. + +Исходный текст синтаксического анализатора находится в файлах \texttt{parser.h} +и \texttt{parser.cpp}. Алгоритм синтаксического анализа реализован в классе +\texttt{Parser}. Конструктор класса в качестве аргумента принимает имя файла, в +котором находится анализируемый текст, и создает экземпляры лексического +анализатора и генератора кода. + +Синтаксический анализатор предоставляет один открытый метод \texttt{void parse()}, +который используется для того, чтобы начать процесс анализа. + +Состояние анализатора описывается следующими полями: +\begin{itemize} +\item \texttt{Scanner* scanner\_} + + Экземпляр лексического анализатора. + +\item \texttt{CodeGen* codegen\_} + + Экземпляр генератора кода. + +\item \texttt{std::ostream\& output\_} + + Выходной поток, в который должны быть выведены инструкции программы. + Базовая версия компилятора Милан использует в качестве выходного потока + стандартный вывод (\texttt{std::cout}). + +\item \texttt{bool error\_} + + Признак ошибки в тексте программы. Если \texttt{error\_} принимает + значение <<истина>>, генерируемый машинный код не выводится. + +\item \texttt{map variables\_} + + Таблица имен, найденных в программе. Она сопоставляет каждой переменной ее + адрес в памяти виртуальной машины. Поскольку базовая версия языка Милан не + содержит вложенных блоков, процедур или функций, таблица имен представляет + собой простой ассоциативный массив. + +\item \texttt{int lastVar\_} + + Адрес последней найденной переменной. +\end{itemize} + +Синтаксический анализатор включает ряд вспомогательных функций (закрытые методы +класса). + +\begin{itemize} +\item \texttt{bool see(Token t)} + + Сравнение текущей лексемы с образцом. Текущая позиция в потоке лексем не + изменяется. + +\item \texttt{bool match(Token t)} + + Проверка совпадения текущей лексемы с образцом. Если лексема и образец + совпадают, лексема изымается из потока. + +\item \texttt{void mustBe(Token t)} + + Проверка совпадения текущей лексемы с образцом. Если лексема и образец + совпадают, лексема изымается из потока. В противном случае формируется + сообщение об ошибке, а программа считается некорректной. + +\item \texttt{void next()} + + Переход к следующей лексеме. + +\item \texttt{void reportError(const string\& message)} + + Формирование сообщения об ошибке. Каждое сообщение включает текст + \texttt{message} и номер строки, в которой обнаружена ошибка. + +\item \texttt{void recover(Token t)} + + Восстановление после ошибки. Используется примитивный алгоритм: если + очередная лексема не совпадает с ожидаемой, анализатор пропускает все + последующие лексемы, пока не встретит ожидаемую лексему или + конец файла. Хотя такой метод восстановления не отличается точностью, он, + тем не менее, позволяет продолжить анализ и, возможно, найти ошибки в + оставшейся части программы. + +\item \texttt{int findOrAddVariable(const string\&)} + + Поиск имени переменной в таблице имен. Если имя найдено, метод возвращает + адрес переменной, в противном случае имя добавляется в таблицу имен, и для + соответствующей переменной резервируется новый адрес. +\end{itemize} + +Кроме служебных методов, класс \texttt{Parser} содержит закрытые методы +\texttt{void program()}, \texttt{void statementList()}, \texttt{void +statement()}, \texttt{void expression()}, \texttt{void term()}, \texttt{void +factor()}, \texttt{void relation()}, которые соответствуют нетерминальным +символам грамматики. Эти методы не возвращают значений и не принимают +аргументов, поскольку с нетерминальными символами не связаны явные атрибуты: все +семантические действия, которые производятся во время анализа программы, +модифицируют буфер общего для всех методов генератора кода. + +\subsubsection{Распознавание операторов} + +Продемонстрируем алгоритм работы синтаксического анализатора на примере анализа +операторов (метод \texttt{statement}). + +В соответствии с грамматикой языка Милан, в качестве оператора может выступать +оператор присваивания, условный оператор \texttt{if}, оператор цикла +\texttt{while} или оператор печати \texttt{write}. Для выбора нужной +альтернативы достаточно прочитать первую лексему оператора. + +Если очередная лексема равна \texttt{T\_IDENTIFIER}, синтаксический анализатор +имеет дело с оператором присваивания. Он считывает имя переменной, стоящей в +левой части присваивания, и определяет ее адрес. Затем анализатор проверяет, что +следующая лексема совпадает с \texttt{T\_ASSIGN}. После знака `\texttt{:=}' в +программе должно следовать арифметическое выражение, поэтому анализатор вызывает +метод \texttt{expression()}. Этот метод проверяет правильность арифметического +выражения и генерирует последовательность команд для его вычисления. В +результате выполнены этой последовательности на вершине стека будет находиться +значение выражения. Чтобы выполнить присваивание, достаточно записать значение с +вершины стека в память по адресу переменной в левой части оператора +присваивания. Для этого после вызова \texttt{expression()} нужно добавить в +буфер команд инструкцию \texttt{STORE}, аргументом которой будет запомненный +ранее адрес переменной. + +Если очередная лексема равна \texttt{T\_IF}, анализатор должен начать разбор +условного оператора. Сначала он вызывает метод \texttt{relation()}, проверяя, +что после лексемы \texttt{T\_IF} следует правильное сравнение двух выражений. +Метод \texttt{relation()} генерирует код, вычисляющий и сравнивающий два +выражения. При выполнении этого кода на вершине стека останется значение $1$, +если условие выполнено, и $0$ в противном случае. Если условие не выполнено, +должен произойти переход к списку операторов блока \texttt{else} или, если этого +блока нет, по адресу следующей за условным оператором инструкции. Однако этот +адрес еще не известен синтаксическому анализатору. Чтобы решить эту проблему, +применяется так называемый <<метод обратных поправок>>~\cite{dragonbook11}. +Анализатор резервирует место для условного перехода \texttt{JUMP\_NO} и +запоминает адрес этой инструкции в переменной \texttt{jumpNoAddress}, после чего +переходит к дальнейшему анализу условного оператора. + +Следом за условием в тексте программы должна находиться лексема +\texttt{T\_THEN}. Если она обнаружена, анализатор переходит к следующей лексеме +и вызывает метод \texttt{statementList()}, который анализирует список операторов +и генерирует для них исполняемый код. Дальнейшие действия зависят от того, +присутствует ли в условном операторе ветвь \texttt{else}. Если следующая лексема +равна \texttt{T\_ELSE}, синтаксический анализатор должен сгенерировать +инструкцию \texttt{JUMP} для выхода из условного оператора, после чего +приступить к анализу блока \texttt{else}. Если условный оператор не содержит +блока \texttt{else}, инструкция безусловного перехода в конце блока +\texttt{then} не нужна. + +Генерация безусловного перехода также требует знания адреса, следующего за +последней инструкцией условного оператора, поэтому анализатор снова должен +зарезервировать ячейку памяти для команды перехода. Следующий за этой ячейкой +адрес содержит первую команду блока \texttt{else}. Это именно тот адрес, по +которому необходимо было выполнить переход в случае, если условие не было +выполнено. Поскольку теперь этот адрес известен, синтаксический анализатор +генерирует инструкцию безусловного перехода и помещает ее в буфер команд по +адресу, который записан в переменной \texttt{jumpNoAddress}. В случае отсутствия +блока \texttt{else} поправка происходит таким же образом, но в качестве адреса +перехода просто используется следующий за последней инструкцией блока +\texttt{then} адрес. После вызова функции \texttt{statementList}, которая +разбирает список операторов блока \texttt{else}, аналогично исправляется +зарезервированная инструкция безусловного перехода. + +Структура кода, соответствующая условному оператору, приведена на +рисунке~\ref{ifthenelse-code}. + +\begin{figure} +\begin{verbatim} + Вычисление выражений + ... + COMPARE operator + JUMP_NO elseLabel + Операторы блока THEN + ... + JUMP endLabel +elseLabel: Операторы блока ELSE + ... + endLabel: +\end{verbatim} +\caption{Структура исполняемого кода условного оператора} +\label{ifthenelse-code} +\end{figure} + +Если очередная лексема равна \texttt{T\_WHILE}, синтаксическому анализатору +предстоит разобрать оператор цикла. Анализатор должен запомнить текущий адрес +команды, поскольку после каждой итерации цикла по этому адресу нужно будет +возвращаться. Затем анализатор вызывает метод \texttt{relation()}, чтобы +сгенерировать код проверки условия. Если условие окажется ложным, нужно будет +выполнить переход на следующий за циклом оператор. Для этого синтаксический +анализатор резервирует ячейку памяти для команды \texttt{JUMP\_NO}. После этого +он проверяет наличие лексемы \texttt{T\_DO} и вызывает метод +\texttt{statementList()} для обработки тела цикла. Затем анализатор генерирует +инструкцию безусловного перехода назад, к началу проверки условия, и записывает +в зарезервированную ячейку инструкцию условного перехода по известному теперь +адресу конца цикла. Для завершения анализа инструкции достаточно убедиться, что +очередная лексема равна ожидаемому значению \texttt{T\_OD}. Структура +исполняемого кода для цикла приведена на рисунке~\ref{while-code}. + +\begin{figure} +\begin{verbatim} +whileLabel: Вычисление выражений + ... + COMPARE operator + JUMP_NO endLabel + ... + Операторы тела цикла + ... + JUMP whileLabel + endLabel: +\end{verbatim} +\caption{Структура исполняемого кода цикла с предусловием} +\label{while-code} +\end{figure} + +Если очередная лексема равна \texttt{T\_WRITE}, необходимо проверить, что +следующая лексема равна \texttt{T\_LPAREN}, затем вызвать метод +\texttt{expression()} и проверить, что за выражением в потоке следует лексема +\texttt{T\_RPAREN}. Поскольку код, вычисляющий значение выражения, оставляет его +значение на вершине стека, для выполнения печати достаточно после вызова +\texttt{expression()} сгенерировать инструкцию \texttt{PRINT}. + +\begin{thebibliography}{9} +\addcontentsline{toc}{section}{Список литературы} + +\bibitem{dragonbook11} + А. Ахо, М. Лам, Р. Сети, Дж. Ульман, + \emph{Компиляторы: принципы, технологии и инструментарий}, 2-е изд. + М.: Вильямс, 2011. + +\bibitem{karpov05} + Ю.Г. Карпов, + \emph{Теория и технология программирования. Основы построения трансляторов}. + СПб.: БХВ-Петербург, 2005. +\end{thebibliography} + +\end{document} + diff --git a/lab4/cmilan/src/Makefile b/lab4/cmilan/src/Makefile new file mode 100644 index 0000000..fe098cf --- /dev/null +++ b/lab4/cmilan/src/Makefile @@ -0,0 +1,23 @@ +CFLAGS = -Wall -W -Werror -O2 +LDFLAGS = + +HEADERS = scanner.h \ + parser.h \ + codegen.h + +OBJS = main.o \ + codegen.o \ + scanner.o \ + parser.o \ + +EXE = cmilan + +$(EXE): $(OBJS) $(HEADERS) + $(CXX) $(LDFLAGS) -o $@ $(OBJS) + +.cpp.o: + $(CXX) $(CFLAGS) -c $< -o $@ + +clean: + -@rm -f $(EXE) $(OBJS) + diff --git a/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.sln b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.sln new file mode 100644 index 0000000..78d63b7 --- /dev/null +++ b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cmilan_vs2011", "cmilan_vs2011.vcxproj", "{1D542465-2019-4442-864E-DC785FA067A8}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1D542465-2019-4442-864E-DC785FA067A8}.Debug|Win32.ActiveCfg = Debug|Win32 + {1D542465-2019-4442-864E-DC785FA067A8}.Debug|Win32.Build.0 = Debug|Win32 + {1D542465-2019-4442-864E-DC785FA067A8}.Release|Win32.ActiveCfg = Release|Win32 + {1D542465-2019-4442-864E-DC785FA067A8}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj new file mode 100644 index 0000000..6654c34 --- /dev/null +++ b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj @@ -0,0 +1,92 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {1D542465-2019-4442-864E-DC785FA067A8} + Win32Proj + cmilan_vs2011 + + + + Application + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + true + cmilan + + + false + cmilan + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.filters b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.filters new file mode 100644 index 0000000..f1b7248 --- /dev/null +++ b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.user b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.user new file mode 100644 index 0000000..ace9a86 --- /dev/null +++ b/lab4/cmilan/src/cmilan_vs2011/cmilan_vs2011.vcxproj.user @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/lab4/cmilan/src/codegen.cpp b/lab4/cmilan/src/codegen.cpp new file mode 100644 index 0000000..24462e3 --- /dev/null +++ b/lab4/cmilan/src/codegen.cpp @@ -0,0 +1,129 @@ +#include "codegen.h" + +void Command::print(int address, ostream& os) +{ + os << address << ":\t"; + switch(instruction_) { + case NOP: + os << "NOP"; + break; + + case STOP: + os << "STOP"; + break; + + case LOAD: + os << "LOAD\t" << arg_; + break; + + case STORE: + os << "STORE\t" << arg_; + break; + + case BLOAD: + os << "BLOAD\t" << arg_; + break; + + case BSTORE: + os << "BSTORE\t" << arg_; + break; + + case PUSH: + os << "PUSH\t" << arg_; + break; + + case POP: + os << "POP"; + break; + + case DUP: + os << "DUP"; + break; + + case ADD: + os << "ADD"; + break; + + case SUB: + os << "SUB"; + break; + + case MULT: + os << "MULT"; + break; + + case DIV: + os << "DIV"; + break; + + case INVERT: + os << "INVERT"; + break; + + case COMPARE: + os << "COMPARE\t" << arg_; + break; + + case JUMP: + os << "JUMP\t" << arg_; + break; + + case JUMP_YES: + os << "JUMP_YES\t" << arg_; + break; + + case JUMP_NO: + os << "JUMP_NO\t" << arg_; + break; + + case INPUT: + os << "INPUT"; + break; + + case PRINT: + os << "PRINT"; + break; + } + + os << endl; +} + +void CodeGen::emit(Instruction instruction) +{ + commandBuffer_.push_back(Command(instruction)); +} + +void CodeGen::emit(Instruction instruction, int arg) +{ + commandBuffer_.push_back(Command(instruction, arg)); +} + +void CodeGen::emitAt(int address, Instruction instruction) +{ + commandBuffer_[address] = Command(instruction); +} + +void CodeGen::emitAt(int address, Instruction instruction, int arg) +{ + commandBuffer_[address] = Command(instruction, arg); +} + +int CodeGen::getCurrentAddress() +{ + return commandBuffer_.size(); +} + +int CodeGen::reserve() +{ + emit(NOP); + return commandBuffer_.size() - 1; +} + +void CodeGen::flush() +{ + int count = commandBuffer_.size(); + for(int address = 0; address < count; ++address) { + commandBuffer_[address].print(address, output_); + } + output_.flush(); +} diff --git a/lab4/cmilan/src/codegen.h b/lab4/cmilan/src/codegen.h new file mode 100644 index 0000000..9cba4c0 --- /dev/null +++ b/lab4/cmilan/src/codegen.h @@ -0,0 +1,100 @@ +#ifndef CMILAN_CODEGEN_H +#define CMILAN_CODEGEN_H + +#include +#include + +using namespace std; + +// Инструкции виртуальной машины Милана + +enum Instruction +{ + NOP, // отсутствие операции + STOP, // остановка машины, завершение работы программы + LOAD, // LOAD addr - загрузка слова данных в стек из памяти по адресу addr + STORE, // STORE addr - запись слова данных с вершины стека в память по адресу addr + BLOAD, // BLOAD addr - загрузка слова данных в стек из памяти по адресу addr + значение на вершине стека + BSTORE, // BSTORE addr - запись слова данных по адресу addr + значение на вершине стека + PUSH, // PUSH n - загрузка в стек константы n + POP, // удаление слова с вершины стека + DUP, // копирование слова на вершине стека + ADD, // сложение двух слов на вершине стека и запись результата вместо них + SUB, // вычитание двух слов на вершине стека и запись результата вместо них + MULT, // умножение двух слов на вершине стека и запись результата вместо них + DIV, // деление двух слов на вершине стека и запись результата вместо них + INVERT, // изменение знака слова на вершине стека + COMPARE, // COMPARE cmp - сравнение двух слов на вершине стека с помощью операции сравнения с кодом cmp + JUMP, // JUMP addr - безусловный переход по адресу addr + JUMP_YES, // JUMP_YES addr - переход по адресу addr, если на вершине стека значение 1 + JUMP_NO, // JUMP_NO addr - переход по адресу addr, если на вершине стека значение 0 + INPUT, // чтение целого числа со стандартного ввода и загрузка его в стек + PRINT // печать на стандартный вывод числа с вершины стека +}; + +// Класс Command представляет машинные инструкции. + +class Command +{ +public: + // Конструктор для инструкций без аргументов + Command(Instruction instruction) + : instruction_(instruction), arg_(0) + {} + + // Конструктор для инструкций с одним аргументом + Command(Instruction instruction, int arg) + : instruction_(instruction), arg_(arg) + {} + + // Печать инструкции + // int address - адрес инструкции + // ostream& os - поток вывода, куда будет напечатана инструкция + void print(int address, ostream& os); + +private: + Instruction instruction_; // Код инструкции + int arg_; // Аргумент инструкции +}; + +// Кодогенератор. +// Назначение кодогенератора: +// - Формировать программу для виртуальной машины Милана +// - Отслеживать адрес последней инструкции +// - Буферизовать программу и печатать ее в указанный поток вывода + +class CodeGen +{ +public: + explicit CodeGen(ostream& output) + : output_(output) + { + } + + // Добавление инструкции без аргументов в конец программы + void emit(Instruction instruction); + + // Добавление инструкции с одним аргументом в конец программы + void emit(Instruction instruction, int arg); + + // Запись инструкции без аргументов по указанному адресу + void emitAt(int address, Instruction instruction); + + // Запись инструкции с одним аргументом по указанному адресу + void emitAt(int address, Instruction instruction, int arg); + + // Получение адреса, непосредственно следующего за последней инструкцией в программе + int getCurrentAddress(); + + // Формирование "пустой" инструкции (NOP) и возврат ее адреса + int reserve(); + + // Запись последовательности инструкций в выходной поток + void flush(); + +private: + ostream& output_; // Выходной поток + vector commandBuffer_; // Буфер инструкций +}; + +#endif diff --git a/lab4/cmilan/src/codegen.o b/lab4/cmilan/src/codegen.o new file mode 100644 index 0000000..06e9e6c Binary files /dev/null and b/lab4/cmilan/src/codegen.o differ diff --git a/lab4/cmilan/src/main.cpp b/lab4/cmilan/src/main.cpp new file mode 100644 index 0000000..ceb66d4 --- /dev/null +++ b/lab4/cmilan/src/main.cpp @@ -0,0 +1,32 @@ +#include "parser.h" +#include +#include + +using namespace std; + +void printHelp() +{ + cout << "Usage: cmilan input_file" << endl; +} + +int main(int argc, char** argv) +{ + if(argc < 2) { + printHelp(); + return EXIT_FAILURE; + } + + ifstream input; + input.open(argv[1]); + + if(input) { + Parser p(argv[1], input); + p.parse(); + return EXIT_SUCCESS; + } + else { + cerr << "File '" << argv[1] << "' not found" << endl; + return EXIT_FAILURE; + } +} + diff --git a/lab4/cmilan/src/main.o b/lab4/cmilan/src/main.o new file mode 100644 index 0000000..66fbf99 Binary files /dev/null and b/lab4/cmilan/src/main.o differ diff --git a/lab4/cmilan/src/parser.cpp b/lab4/cmilan/src/parser.cpp new file mode 100644 index 0000000..c67b27c --- /dev/null +++ b/lab4/cmilan/src/parser.cpp @@ -0,0 +1,270 @@ +#include "parser.h" +#include + +//Выполняем синтаксический разбор блока program. Если во время разбора не обнаруживаем +//никаких ошибок, то выводим последовательность команд стек-машины +void Parser::parse() +{ + program(); + if(!error_) { + codegen_->flush(); + } +} + +void Parser::program() +{ + mustBe(T_BEGIN); + statementList(); + mustBe(T_END); + codegen_->emit(STOP); +} + +void Parser::statementList() +{ + // Если список операторов пуст, очередной лексемой будет одна из возможных "закрывающих скобок": END, OD, ELSE, FI. + // В этом случае результатом разбора будет пустой блок (его список операторов равен null). + // Если очередная лексема не входит в этот список, то ее мы считаем началом оператора и вызываем метод statement. + // Признаком последнего оператора является отсутствие после оператора точки с запятой. + if(see(T_END) || see(T_OD) || see(T_ELSE) || see(T_FI)) { + return; + } + else { + bool more = true; + while(more) { + statement(); + more = match(T_SEMICOLON); + } + } +} + +void Parser::statement() +{ + // Если встречаем переменную, то запоминаем ее адрес или добавляем новую если не встретили. + // Следующей лексемой должно быть присваивание. Затем идет блок expression, который возвращает значение на вершину стека. + // Записываем это значение по адресу нашей переменной + if(see(T_IDENTIFIER)) { + int varAddress = findOrAddVariable(scanner_->getStringValue()); + next(); + mustBe(T_ASSIGN); + expression(); + codegen_->emit(STORE, varAddress); + } + // Если встретили IF, то затем должно следовать условие. На вершине стека лежит 1 или 0 в зависимости от выполнения условия. + // Затем зарезервируем место для условного перехода JUMP_NO к блоку ELSE (переход в случае ложного условия). Адрес перехода + // станет известным только после того, как будет сгенерирован код для блока THEN. + else if(match(T_IF)) { + relation(); + + int jumpNoAddress = codegen_->reserve(); + + mustBe(T_THEN); + statementList(); + if(match(T_ELSE)) { + //Если есть блок ELSE, то чтобы не выполнять его в случае выполнения THEN, + //зарезервируем место для команды JUMP в конец этого блока + int jumpAddress = codegen_->reserve(); + //Заполним зарезервированное место после проверки условия инструкцией перехода в начало блока ELSE. + codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress()); + statementList(); + //Заполним второй адрес инструкцией перехода в конец условного блока ELSE. + codegen_->emitAt(jumpAddress, JUMP, codegen_->getCurrentAddress()); + } + else { + //Если блок ELSE отсутствует, то в зарезервированный адрес после проверки условия будет записана + //инструкция условного перехода в конец оператора IF...THEN + codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress()); + } + + mustBe(T_FI); + } + + else if(match(T_WHILE)) { + //запоминаем адрес начала проверки условия. + int conditionAddress = codegen_->getCurrentAddress(); + relation(); + //резервируем место под инструкцию условного перехода для выхода из цикла. + int jumpNoAddress = codegen_->reserve(); + mustBe(T_DO); + statementList(); + mustBe(T_OD); + //переходим по адресу проверки условия + codegen_->emit(JUMP, conditionAddress); + //заполняем зарезервированный адрес инструкцией условного перехода на следующий за циклом оператор. + codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress()); + } + else if(match(T_WRITE)) { + mustBe(T_LPAREN); + expression(); + mustBe(T_RPAREN); + codegen_->emit(PRINT); + } + else { + reportError("statement expected."); + } +} + +void Parser::expression() +{ + + /* + Арифметическое выражение описывается следующими правилами: -> | + | - + При разборе сначала смотрим первый терм, затем анализируем очередной символ. Если это '+' или '-', + удаляем его из потока и разбираем очередное слагаемое (вычитаемое). Повторяем проверку и разбор очередного + терма, пока не встретим за термом символ, отличный от '+' и '-' + */ + + term(); + while(see(T_ADDOP)) { + Arithmetic op = scanner_->getArithmeticValue(); + next(); + term(); + + if(op == A_PLUS) { + codegen_->emit(ADD); + } + else { + codegen_->emit(SUB); + } + } +} + +void Parser::term() +{ + /* + Терм описывается следующими правилами: -> | + | - + При разборе сначала смотрим первый множитель, затем анализируем очередной символ. Если это '*' или '/', + удаляем его из потока и разбираем очередное слагаемое (вычитаемое). Повторяем проверку и разбор очередного + множителя, пока не встретим за ним символ, отличный от '*' и '/' + */ + factor(); + while(see(T_MULOP)) { + Arithmetic op = scanner_->getArithmeticValue(); + next(); + factor(); + + if(op == A_MULTIPLY) { + codegen_->emit(MULT); + } + else { + codegen_->emit(DIV); + } + } +} + +void Parser::factor() +{ + /* + Множитель описывается следующими правилами: + -> number | identifier | - | () | READ + */ + if(see(T_NUMBER)) { + int value = scanner_->getIntValue(); + next(); + codegen_->emit(PUSH, value); + //Если встретили число, то преобразуем его в целое и записываем на вершину стека + } + else if(see(T_IDENTIFIER)) { + int varAddress = findOrAddVariable(scanner_->getStringValue()); + next(); + codegen_->emit(LOAD, varAddress); + //Если встретили переменную, то выгружаем значение, лежащее по ее адресу, на вершину стека + } + else if(see(T_ADDOP) && scanner_->getArithmeticValue() == A_MINUS) { + next(); + factor(); + codegen_->emit(INVERT); + //Если встретили знак "-", и за ним то инвертируем значение, лежащее на вершине стека + } + else if(match(T_LPAREN)) { + expression(); + mustBe(T_RPAREN); + //Если встретили открывающую скобку, тогда следом может идти любое арифметическое выражение и обязательно + //закрывающая скобка. + } + else if(match(T_READ)) { + codegen_->emit(INPUT); + //Если встретили зарезервированное слово READ, то записываем на вершину стека идет запись со стандартного ввода + } + else { + reportError("expression expected."); + } +} + +void Parser::relation() +{ + //Условие сравнивает два выражения по какому-либо из знаков. Каждый знак имеет свой номер. В зависимости от + //результата сравнения на вершине стека окажется 0 или 1. + expression(); + if(see(T_CMP)) { + Cmp cmp = scanner_->getCmpValue(); + next(); + expression(); + switch(cmp) { + //для знака "=" - номер 0 + case C_EQ: + codegen_->emit(COMPARE, 0); + break; + //для знака "!=" - номер 1 + case C_NE: + codegen_->emit(COMPARE, 1); + break; + //для знака "<" - номер 2 + case C_LT: + codegen_->emit(COMPARE, 2); + break; + //для знака ">" - номер 3 + case C_GT: + codegen_->emit(COMPARE, 3); + break; + //для знака "<=" - номер 4 + case C_LE: + codegen_->emit(COMPARE, 4); + break; + //для знака ">=" - номер 5 + case C_GE: + codegen_->emit(COMPARE, 5); + break; + }; + } + else { + reportError("comparison operator expected."); + } +} + +int Parser::findOrAddVariable(const string& var) +{ + VarTable::iterator it = variables_.find(var); + if(it == variables_.end()) { + variables_[var] = lastVar_; + return lastVar_++; + } + else { + return it->second; + } +} + +void Parser::mustBe(Token t) +{ + if(!match(t)) { + error_ = true; + + // Подготовим сообщение об ошибке + std::ostringstream msg; + msg << tokenToString(scanner_->token()) << " found while " << tokenToString(t) << " expected."; + reportError(msg.str()); + + // Попытка восстановления после ошибки. + recover(t); + } +} + +void Parser::recover(Token t) +{ + while(!see(t) && !see(T_EOF)) { + next(); + } + + if(see(t)) { + next(); + } +} diff --git a/lab4/cmilan/src/parser.h b/lab4/cmilan/src/parser.h new file mode 100644 index 0000000..073ab7b --- /dev/null +++ b/lab4/cmilan/src/parser.h @@ -0,0 +1,119 @@ +#ifndef CMILAN_PARSER_H +#define CMILAN_PARSER_H + +#include "scanner.h" +#include "codegen.h" +#include +#include +#include +#include + +using namespace std; + +/* Синтаксический анализатор. + * + * Задачи: + * - проверка корректности программы, + * - генерация кода для виртуальной машины в процессе анализа, + * - простейшее восстановление после ошибок. + * + * Синтаксический анализатор языка Милан. + * + * Парсер с помощью переданного ему при инициализации лексического анализатора + * читает по одной лексеме и на основе грамматики Милана генерирует код для + * стековой виртуальной машины. Синтаксический анализ выполняется методом + * рекурсивного спуска. + * + * При обнаружении ошибки парсер печатает сообщение и продолжает анализ со + * следующего оператора, чтобы в процессе разбора найти как можно больше ошибок. + * Поскольку стратегия восстановления после ошибки очень проста, возможна печать + * сообщений о несуществующих ("наведенных") ошибках или пропуск некоторых + * ошибок без печати сообщений. Если в процессе разбора была найдена хотя бы + * одна ошибка, код для виртуальной машины не печатается.*/ + +class Parser +{ +public: + // Конструктор + // const string& fileName - имя файла с программой для анализа + // + // Конструктор создает экземпляры лексического анализатора и генератора. + + Parser(const string& fileName, istream& input) + : output_(cout), error_(false), recovered_(true), lastVar_(0) + { + scanner_ = new Scanner(fileName, input); + codegen_ = new CodeGen(output_); + next(); + } + + ~Parser() + { + delete codegen_; + delete scanner_; + } + + void parse(); //проводим синтаксический разбор + +private: + typedef map VarTable; + //описание блоков. + void program(); //Разбор программы. BEGIN statementList END + void statementList(); // Разбор списка операторов. + void statement(); //разбор оператора. + void expression(); //разбор арифметического выражения. + void term(); //разбор слагаемого. + void factor(); //разбор множителя. + void relation(); //разбор условия. + + // Сравнение текущей лексемы с образцом. Текущая позиция в потоке лексем не изменяется. + bool see(Token t) + { + return scanner_->token() == t; + } + + // Проверка совпадения текущей лексемы с образцом. Если лексема и образец совпадают, + // лексема изымается из потока. + + bool match(Token t) + { + if(scanner_->token() == t) { + scanner_->nextToken(); + return true; + } + else { + return false; + } + } + + // Переход к следующей лексеме. + + void next() + { + scanner_->nextToken(); + } + + // Обработчик ошибок. + void reportError(const string& message) + { + cerr << "Line " << scanner_->getLineNumber() << ": " << message << endl; + error_ = true; + } + + void mustBe(Token t); //проверяем, совпадает ли данная лексема с образцом. Если да, то лексема изымается из потока. + //Иначе создаем сообщение об ошибке и пробуем восстановиться + void recover(Token t); //восстановление после ошибки: идем по коду до тех пор, + //пока не встретим эту лексему или лексему конца файла. + int findOrAddVariable(const string&); //функция пробегает по variables_. + //Если находит нужную переменную - возвращает ее номер, иначе добавляет ее в массив, увеличивает lastVar и возвращает его. + + Scanner* scanner_; //лексический анализатор для конструктора + CodeGen* codegen_; //указатель на виртуальную машину + ostream& output_; //выходной поток (в данном случае используем cout) + bool error_; //флаг ошибки. Используется чтобы определить, выводим ли список команд после разбора или нет + bool recovered_; //не используется + VarTable variables_; //массив переменных, найденных в программе + int lastVar_; //номер последней записанной переменной +}; + +#endif diff --git a/lab4/cmilan/src/parser.o b/lab4/cmilan/src/parser.o new file mode 100644 index 0000000..9ed6d50 Binary files /dev/null and b/lab4/cmilan/src/parser.o differ diff --git a/lab4/cmilan/src/scanner.cpp b/lab4/cmilan/src/scanner.cpp new file mode 100644 index 0000000..29f5474 --- /dev/null +++ b/lab4/cmilan/src/scanner.cpp @@ -0,0 +1,233 @@ +#include "scanner.h" +#include +#include +#include + +using namespace std; + +static const char * tokenNames_[] = { + "end of file", + "illegal token", + "identifier", + "number", + "'BEGIN'", + "'END'", + "'IF'", + "'THEN'", + "'ELSE'", + "'FI'", + "'WHILE'", + "'DO'", + "'OD'", + "'WRITE'", + "'READ'", + "':='", + "'+' or '-'", + "'*' or '/'", + "comparison operator", + "'('", + "')'", + "';'", +}; + +void Scanner::nextToken() +{ + skipSpace(); + + // Пропускаем комментарии + // Если встречаем "/", то за ним должна идти "*". Если "*" не встречена, считаем, что встретили операцию деления + // и лексему - операция типа умножения. Дальше смотрим все символы, пока не находим звездочку или символ конца файла. + // Если нашли * - проверяем на наличие "/" после нее. Если "/" не найден - ищем следующую "*". + while(ch_ == '/') { + nextChar(); + if(ch_ == '*') { + nextChar(); + bool inside = true; + while(inside) { + while(ch_ != '*' && !input_.eof()) { + nextChar(); + } + + if(input_.eof()) { + token_ = T_EOF; + return; + } + + nextChar(); + if(ch_ == '/') { + inside = false; + nextChar(); + } + } + } + else { + token_ = T_MULOP; + arithmeticValue_ = A_DIVIDE; + return; + } + + skipSpace(); + } + + //Если встречен конец файла, считаем за лексему конца файла. + if(input_.eof()) { + token_ = T_EOF; + return; + } + //Если встретили цифру, то до тех пока дальше идут цифры - считаем как продолжение числа. + //Запоминаем полученное целое, а за лексему считаем целочисленный литерал + + if(isdigit(ch_)) { + int value = 0; + while(isdigit(ch_)) { + value = value * 10 + (ch_ - '0'); //поразрядное считывание, преобразуем символьное значение к числу. + nextChar(); + } + token_ = T_NUMBER; + intValue_ = value; + } + //Если же следующий символ - буква ЛА - тогда считываем до тех пор, пока дальше буквы ЛА или цифры. + //Как только считали имя переменной, сравниваем ее со списком зарезервированных слов. Если не совпадает ни с одним из них, + //считаем, что получили переменную, имя которой запоминаем, а за текущую лексему считаем лексему идентификатора. + //Если совпадает с каким-либо словом из списка - считаем что получили лексему, соответствующую этому слову. + else if(isIdentifierStart(ch_)) { + string buffer; + while(isIdentifierBody(ch_)) { + buffer += ch_; + nextChar(); + } + + transform(buffer.begin(), buffer.end(), buffer.begin(), ::tolower); + + map::iterator kwd = keywords_.find(buffer); + if(kwd == keywords_.end()) { + token_ = T_IDENTIFIER; + stringValue_ = buffer; + } + else { + token_ = kwd->second; + } + } + //Символ не является буквой, цифрой, "/" или признаком конца файла + else { + switch(ch_) { + //Признак лексемы открывающей скобки - встретили "(" + case '(': + token_ = T_LPAREN; + nextChar(); + break; + //Признак лексемы закрывающей скобки - встретили ")" + case ')': + token_ = T_RPAREN; + nextChar(); + break; + //Признак лексемы ";" - встретили ";" + case ';': + token_ = T_SEMICOLON; + nextChar(); + break; + //Если встречаем ":", то дальше смотрим наличие символа "=". Если находим, то считаем что нашли лексему присваивания + //Иначе - лексема ошибки. + case ':': + nextChar(); + if(ch_ == '=') { + token_ = T_ASSIGN; + nextChar(); + + } + else { + token_ = T_ILLEGAL; + } + break; + //Если встретили символ "<", то либо следующий символ "=", тогда лексема нестрогого сравнения. Иначе - строгого. + case '<': + token_ = T_CMP; + nextChar(); + if(ch_ == '=') { + cmpValue_ = C_LE; + nextChar(); + } + else { + cmpValue_ = C_LT; + } + break; + //Аналогично предыдущему случаю + case '>': + token_ = T_CMP; + nextChar(); + if(ch_ == '=') { + cmpValue_ = C_GE; + nextChar(); + } + else { + cmpValue_ = C_GT; + } + break; + //Если встретим "!", то дальше должно быть "=", тогда считаем, что получили лексему сравнения + //и знак "!=" иначе считаем, что у нас лексема ошибки + case '!': + nextChar(); + if(ch_ == '=') { + nextChar(); + token_ = T_CMP; + cmpValue_ = C_NE; + } + else { + token_ = T_ILLEGAL; + } + break; + //Если встретим "=" - лексема сравнения и знак "=" + case '=': + token_ = T_CMP; + cmpValue_ = C_EQ; + nextChar(); + break; + //Знаки операций. Для "+"/"-" получим лексему операции типа сложнения, и соответствующую операцию. + //для "*" - лексему операции типа умножения + case '+': + token_ = T_ADDOP; + arithmeticValue_ = A_PLUS; + nextChar(); + break; + + case '-': + token_ = T_ADDOP; + arithmeticValue_ = A_MINUS; + nextChar(); + break; + + case '*': + token_ = T_MULOP; + arithmeticValue_ = A_MULTIPLY; + nextChar(); + break; + //Иначе лексема ошибки. + default: + token_ = T_ILLEGAL; + nextChar(); + break; + } + } +} + +void Scanner::skipSpace() +{ + while(isspace(ch_)) { + if(ch_ == '\n') { + ++lineNumber_; + } + + nextChar(); + } +} + +void Scanner::nextChar() +{ + ch_ = input_.get(); +} + +const char * tokenToString(Token t) +{ + return tokenNames_[t]; +} + diff --git a/lab4/cmilan/src/scanner.h b/lab4/cmilan/src/scanner.h new file mode 100644 index 0000000..15d1523 --- /dev/null +++ b/lab4/cmilan/src/scanner.h @@ -0,0 +1,164 @@ +#ifndef CMILAN_SCANNER_H +#define CMILAN_SCANNER_H + +#include +#include +#include + +using namespace std; + +enum Token { + T_EOF, // Конец текстового потока + T_ILLEGAL, // Признак недопустимого символа + T_IDENTIFIER, // Идентификатор + T_NUMBER, // Целочисленный литерал + T_BEGIN, // Ключевое слово "begin" + T_END, // Ключевое слово "end" + T_IF, // Ключевое слово "if" + T_THEN, // Ключевое слово "then" + T_ELSE, // Ключевое слово "else" + T_FI, // Ключевое слово "fi" + T_WHILE, // Ключевое слово "while" + T_DO, // Ключевое слово "do" + T_OD, // Ключевое слово "od" + T_WRITE, // Ключевое слово "write" + T_READ, // Ключевое слово "read" + T_ASSIGN, // Оператор ":=" + T_ADDOP, // Сводная лексема для "+" и "-" (операция типа сложения) + T_MULOP, // Сводная лексема для "*" и "/" (операция типа умножения) + T_CMP, // Сводная лексема для операторов отношения + T_LPAREN, // Открывающая скобка + T_RPAREN, // Закрывающая скобка + T_SEMICOLON // ";" +}; + +// Функция tokenToString возвращает описание лексемы. +// Используется при печати сообщения об ошибке. +const char * tokenToString(Token t); + +// Виды операций сравнения +enum Cmp { + C_EQ, // Операция сравнения "=" + C_NE, // Операция сравнения "!=" + C_LT, // Операция сравнения "<" + C_LE, // Операция сравнения "<=" + C_GT, // Операция сравнения ">" + C_GE // Операция сравнения ">=" +}; + +// Виды арифметических операций +enum Arithmetic { + A_PLUS, //операция "+" + A_MINUS, //операция "-" + A_MULTIPLY, //операция "*" + A_DIVIDE //операция "/" +}; + +// Лексический анализатор + +class Scanner +{ +public: + // Конструктор. В качестве аргумента принимает имя файла и поток, + // из которого будут читаться символы транслируемой программы. + + explicit Scanner(const string& fileName, istream& input) + : fileName_(fileName), lineNumber_(1), input_(input) + { + keywords_["begin"] = T_BEGIN; + keywords_["end"] = T_END; + keywords_["if"] = T_IF; + keywords_["then"] = T_THEN; + keywords_["else"] = T_ELSE; + keywords_["fi"] = T_FI; + keywords_["while"] = T_WHILE; + keywords_["do"] = T_DO; + keywords_["od"] = T_OD; + keywords_["write"] = T_WRITE; + keywords_["read"] = T_READ; + + nextChar(); + } + + // Деструктор + virtual ~Scanner() + {} + + //getters всех private переменных + const string& getFileName() const //не используется + { + return fileName_; + } + + int getLineNumber() const + { + return lineNumber_; + } + + Token token() const + { + return token_; + } + + int getIntValue() const + { + return intValue_; + } + + string getStringValue() const + { + return stringValue_; + } + + Cmp getCmpValue() const + { + return cmpValue_; + } + + Arithmetic getArithmeticValue() const + { + return arithmeticValue_; + } + + // Переход к следующей лексеме. + // Текущая лексема записывается в token_ и изымается из потока. + void nextToken(); +private: + + // Пропуск всех пробельные символы. + // Если встречается символ перевода строки, номер текущей строки + // (lineNumber) увеличивается на единицу. + void skipSpace(); + + + void nextChar(); //переходит к следующему символу + //проверка переменной на первый символ (должен быть буквой латинского алфавита) + bool isIdentifierStart(char c) + { + return ((c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z')); + } + //проверка на остальные символы переменной (буква или цифра) + bool isIdentifierBody(char c) + { + return isIdentifierStart(c) || isdigit(c); + } + + + const string fileName_; //входной файл + int lineNumber_; //номер текущей строки кода + + Token token_; //текущая лексема + int intValue_; //значение текущего целого + string stringValue_; //имя переменной + Cmp cmpValue_; //значение оператора сравнения (>, <, =, !=, >=, <=) + Arithmetic arithmeticValue_; //значение знака (+,-,*,/) + + map keywords_; //ассоциативный массив с лексемами и + //соответствующими им зарезервированными словами в качестве индексов + + istream& input_; //входной поток для чтения из файла. + char ch_; //текущий символ +}; + +#endif diff --git a/lab4/cmilan/src/scanner.o b/lab4/cmilan/src/scanner.o new file mode 100644 index 0000000..f5783eb Binary files /dev/null and b/lab4/cmilan/src/scanner.o differ diff --git a/lab4/cmilan/test/add.mil b/lab4/cmilan/test/add.mil new file mode 100644 index 0000000..c206c9a --- /dev/null +++ b/lab4/cmilan/test/add.mil @@ -0,0 +1,7 @@ +BEGIN + i := 1; + j := 2; + k := i + j; + WRITE(k) +END + diff --git a/lab4/cmilan/test/comment.mil b/lab4/cmilan/test/comment.mil new file mode 100644 index 0000000..4909fdf --- /dev/null +++ b/lab4/cmilan/test/comment.mil @@ -0,0 +1,14 @@ +/* это комментарий */ +/* это продолжение комментария */ + +/***************************** + * эта программа печатает 42 * + ****************************/ + +begin /* комментарий в конце строки */ +/* комментарий в начале строки */ write(42) +/* многострочный + комментарий */ +end + +/* комментарий в конце файла */ diff --git a/lab4/cmilan/test/factorial.mil b/lab4/cmilan/test/factorial.mil new file mode 100644 index 0000000..bb280e7 --- /dev/null +++ b/lab4/cmilan/test/factorial.mil @@ -0,0 +1,10 @@ +BEGIN + n := READ; + factorial := 1; + i := 1; + WHILE i <= n DO + factorial := factorial * i; + i := i + 1 + OD; + WRITE(factorial) +END diff --git a/lab4/cmilan/test/fib.mil b/lab4/cmilan/test/fib.mil new file mode 100644 index 0000000..97bee76 --- /dev/null +++ b/lab4/cmilan/test/fib.mil @@ -0,0 +1,17 @@ +/* N- */ + +BEGIN + a := 1; + b := 1; + n := READ; + + WHILE n > 1 DO + t := a; + a := b; + b := b + t; + n := n - 1 + OD; + + WRITE(a) +END + diff --git a/lab4/cmilan/test/gcd.mil b/lab4/cmilan/test/gcd.mil new file mode 100644 index 0000000..b669e9a --- /dev/null +++ b/lab4/cmilan/test/gcd.mil @@ -0,0 +1,17 @@ +/* Greatest common divisor */ + +BEGIN + a := READ; + b := READ; + + WHILE a != b DO + IF a < b THEN + b := b - a + ELSE + a := a - b + FI + OD; + + WRITE(a) +END + diff --git a/lab4/cmilan/test/if.mil b/lab4/cmilan/test/if.mil new file mode 100644 index 0000000..e81aa1d --- /dev/null +++ b/lab4/cmilan/test/if.mil @@ -0,0 +1,8 @@ +BEGIN + i := 1; + j := 2; + + IF i < j THEN WRITE(i) FI; + IF i < j THEN WRITE(i) ELSE WRITE(j) FI +END + diff --git a/lab4/cmilan/test/invalid.mil b/lab4/cmilan/test/invalid.mil new file mode 100644 index 0000000..a8db7e7 --- /dev/null +++ b/lab4/cmilan/test/invalid.mil @@ -0,0 +1,5 @@ +BEGIN + IF 1 2 THEN WRITE(n) ELSE WRITE(2) FI; + X := Y + 1; + WRITE (X +) +END diff --git a/lab4/cmilan/test/invert.mil b/lab4/cmilan/test/invert.mil new file mode 100644 index 0000000..21321a5 --- /dev/null +++ b/lab4/cmilan/test/invert.mil @@ -0,0 +1,14 @@ +BEGIN + x := READ; + x := -x; + + WRITE(-x); + + IF -x > 0 THEN x := 1 FI; + + x := x + -1; + x := x - -x; + + x := x -1 +END + diff --git a/lab4/cmilan/test/loop.mil b/lab4/cmilan/test/loop.mil new file mode 100644 index 0000000..b57e777 --- /dev/null +++ b/lab4/cmilan/test/loop.mil @@ -0,0 +1,17 @@ +BEGIN + /* Read a number */ + + i := READ; + + /* Count from 0 to this number */ + + IF i > 0 THEN step := 1 ELSE step := -1 FI; + k := 0; + WHILE k != i DO + WRITE(k); + k := k + step + OD; + + WRITE(i) +END + diff --git a/lab4/cmilan/test/power.mil b/lab4/cmilan/test/power.mil new file mode 100644 index 0000000..7661a84 --- /dev/null +++ b/lab4/cmilan/test/power.mil @@ -0,0 +1,14 @@ +BEGIN + N := READ; + P := READ; + + S := 1; + + WHILE P > 0 DO + S := S * N; + P := P - 1 + OD; + + WRITE(S) +END + diff --git a/lab4/cmilan/test/read2.mil b/lab4/cmilan/test/read2.mil new file mode 100644 index 0000000..3b4ed25 --- /dev/null +++ b/lab4/cmilan/test/read2.mil @@ -0,0 +1,8 @@ +BEGIN + IF READ < READ + THEN + WRITE(1) + ELSE + WRITE(2) + FI +END diff --git a/lab4/cmilan/test/sum.mil b/lab4/cmilan/test/sum.mil new file mode 100644 index 0000000..507ca7c --- /dev/null +++ b/lab4/cmilan/test/sum.mil @@ -0,0 +1,9 @@ +BEGIN + i := 8; + j := 2; + + WHILE i != j DO + IF i < j THEN j := j - i ELSE i := i - j FI + OD; + WRITE(i) +END diff --git a/lab4/vm/bin/milanvm.exe b/lab4/vm/bin/milanvm.exe new file mode 100644 index 0000000..0add2db Binary files /dev/null and b/lab4/vm/bin/milanvm.exe differ diff --git a/lab4/vm/doc/changelog.txt b/lab4/vm/doc/changelog.txt new file mode 100644 index 0000000..7f6f6ea --- /dev/null +++ b/lab4/vm/doc/changelog.txt @@ -0,0 +1,10 @@ + : +================== + + 1.2: + * ymilan + . + * NOP ( ). + + 1.1: + * ymilan 1.1. diff --git a/lab4/vm/doc/vm.txt b/lab4/vm/doc/vm.txt new file mode 100644 index 0000000..760ea66 --- /dev/null +++ b/lab4/vm/doc/vm.txt @@ -0,0 +1,224 @@ +== == + + , . + . + . : + . + + . + +NOP + + ; . + +STOP + + ; + . + +LOAD <> + + , <>. + +STORE <> + + <>. + , + . + + +BLOAD <> + + , : + < > = <> + < >. + . + + BLOAD , , + , + . + +BSTORE <> + + : + < > = <> + < >, + . + < >. + + BSTORE + , + . + + : [10, 20, ...]. BSTORE 5 + 15 20. + +PUSH <> + + <> . + +POP + + . + +DUP + + , . + +ADD + + + . + +MULT + + + . + +SUB + + , + - . + + : + + PUSH 10 + PUSH 8 + SUB + + 2. + +DIV + + , + / . + . = 0, + . + +INVERT + + . + +COMPARE <> + + , , + . + + <>: + + <> + + 0 = + 1 != + 2 < + 3 > + 4 <= + 5 >= + + 1, + , 0 . + + : + + PUSH 5 + PUSH 7 + COMPARE 2 + + 1 ( 5 < 7). + +JUMP <> + + <>, + <>. + <> , + , . + + +JUMP_YES <> + + <>, + ; . + +JUMP_NO <> + + <>, + 0; . + <> , + , . + +INPUT + + + . - + . + +PRINT + + + . . + + . + + , + . . + + . ';' , +, , . + + , , . + , ':'. + 0. + + , +: STOP. , . + + : + +------------------------------------------------------------ +0: INPUT +1: STORE 42 ; n := READ +2: LOAD 14 +3: PUSH 4 +4: LOAD 42 +5: COMPARE 2 +6: JUMP_NO 9 +7: PUSH 10 +8: STORE 42 +9: LOAD 42 +10: PRINT +11: STOP +------------------------------------------------------------- + + + SET: + + SET <> <> + + SET <> + <>. + + SET . + . + SET +. + + SET <> <> + + PUSH <> + STORE <> + + . + + SET . SET: + +------------------------------------ +SET 0 15 +SET 1 40 + +0: LOAD 0 +1: LOAD 1 +2: ADD +3: PRINT +4: STOP +------------------------------------ + + 55. + diff --git a/lab4/vm/vm/Makefile b/lab4/vm/vm/Makefile new file mode 100644 index 0000000..53415a7 --- /dev/null +++ b/lab4/vm/vm/Makefile @@ -0,0 +1,15 @@ +mvm: vm.c lex.yy.c vmparse.tab.h main.c + gcc -o mvm main.c vm.c lex.yy.c vmparse.tab.c + +lex.yy.c: vmlex.l + flex vmlex.l + +vmparse.tab.h: vmparse.y + bison -d vmparse.y + +clean: + rm lex.yy.c vmparse.tab.h vmparse.tab.c + +distclean: + rm mvm lex.yy.c vmparse.tab.h vmparse.tab.c + diff --git a/lab4/vm/vm/lex.yy.c b/lab4/vm/vm/lex.yy.c new file mode 100644 index 0000000..ddc430f --- /dev/null +++ b/lab4/vm/vm/lex.yy.c @@ -0,0 +1,1690 @@ +/* A lexical scanner generated by flex */ + +/* Scanner skeleton version: + * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ + */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 5 + +#include + + +/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ +#ifdef c_plusplus +#ifndef __cplusplus +#define __cplusplus +#endif +#endif + + +#ifdef __cplusplus + +#include +#include + +/* Use prototypes in function declarations. */ +#define YY_USE_PROTOS + +/* The "const" storage-class-modifier is valid. */ +#define YY_USE_CONST + +#else /* ! __cplusplus */ + +#if __STDC__ + +#define YY_USE_PROTOS +#define YY_USE_CONST + +#endif /* __STDC__ */ +#endif /* ! __cplusplus */ + +#ifdef __TURBOC__ + #pragma warn -rch + #pragma warn -use +#include +#include +#define YY_USE_CONST +#define YY_USE_PROTOS +#endif + +#ifdef YY_USE_CONST +#define yyconst const +#else +#define yyconst +#endif + + +#ifdef YY_USE_PROTOS +#define YY_PROTO(proto) proto +#else +#define YY_PROTO(proto) () +#endif + +/* Returned upon end-of-file. */ +#define YY_NULL 0 + +/* Promotes a possibly negative, possibly signed char to an unsigned + * integer for use as an array index. If the signed char is negative, + * we want to instead treat it as an 8-bit unsigned char, hence the + * double cast. + */ +#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN yy_start = 1 + 2 * + +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START ((yy_start - 1) / 2) +#define YYSTATE YY_START + +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) + +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE yyrestart( yyin ) + +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#define YY_BUF_SIZE 16384 + +typedef struct yy_buffer_state *YY_BUFFER_STATE; + +extern int yyleng; +extern FILE *yyin, *yyout; + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + +/* The funky do-while in the following #define is used to turn the definition + * int a single C statement (which needs a semi-colon terminator). This + * avoids problems with code like: + * + * if ( condition_holds ) + * yyless( 5 ); + * else + * do_something_else(); + * + * Prior to using the do-while the compiler would get upset at the + * "else" because it interpreted the "if" statement as being all + * done when it reached the ';' after the yyless() call. + */ + +/* Return all but the first 'n' matched characters back to the input stream. */ + +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + *yy_cp = yy_hold_char; \ + YY_RESTORE_YY_MORE_OFFSET \ + yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) + +#define unput(c) yyunput( c, yytext_ptr ) + +/* The following is because we cannot portably get our hands on size_t + * (without autoconf's help, which isn't available because we want + * flex-generated scanners to compile on their own). + */ +typedef unsigned int yy_size_t; + + +struct yy_buffer_state + { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + yy_size_t yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + }; + +static YY_BUFFER_STATE yy_current_buffer = 0; + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + */ +#define YY_CURRENT_BUFFER yy_current_buffer + + +/* yy_hold_char holds the character lost when yytext is formed. */ +static char yy_hold_char; + +static int yy_n_chars; /* number of characters read into yy_ch_buf */ + + +int yyleng; + +/* Points to current character in buffer. */ +static char *yy_c_buf_p = (char *) 0; +static int yy_init = 1; /* whether we need to initialize */ +static int yy_start = 0; /* start state number */ + +/* Flag which is used to allow yywrap()'s to do buffer switches + * instead of setting up a fresh yyin. A bit of a hack ... + */ +static int yy_did_buffer_switch_on_eof; + +void yyrestart YY_PROTO(( FILE *input_file )); + +void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); +void yy_load_buffer_state YY_PROTO(( void )); +YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); +void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); +void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); +void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); +#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) + +YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); +YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); +YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); + +static void *yy_flex_alloc YY_PROTO(( yy_size_t )); +static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); +static void yy_flex_free YY_PROTO(( void * )); + +#define yy_new_buffer yy_create_buffer + +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! yy_current_buffer ) \ + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ + yy_current_buffer->yy_is_interactive = is_interactive; \ + } + +#define yy_set_bol(at_bol) \ + { \ + if ( ! yy_current_buffer ) \ + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ + yy_current_buffer->yy_at_bol = at_bol; \ + } + +#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) + + +#define yywrap() 1 +#define YY_SKIP_YYWRAP +typedef unsigned char YY_CHAR; +FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; +typedef int yy_state_type; +extern char *yytext; +#define yytext_ptr yytext + +static yy_state_type yy_get_previous_state YY_PROTO(( void )); +static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); +static int yy_get_next_buffer YY_PROTO(( void )); +static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + yytext_ptr = yy_bp; \ + yyleng = (int) (yy_cp - yy_bp); \ + yy_hold_char = *yy_cp; \ + *yy_cp = '\0'; \ + yy_c_buf_p = yy_cp; + +#define YY_NUM_RULES 27 +#define YY_END_OF_BUFFER 28 +static yyconst short int yy_accept[91] = + { 0, + 0, 0, 28, 27, 3, 1, 27, 4, 5, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 3, 4, 0, 2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 16, 0, 0, 0, 19, 14, 0, 0, + 0, 0, 0, 26, 13, 0, 0, 6, 0, 17, + 0, 0, 0, 0, 0, 21, 8, 18, 0, 12, + 7, 0, 10, 0, 0, 24, 0, 0, 25, 9, + 11, 0, 15, 0, 0, 20, 23, 0, 22, 0 + } ; + +static yyconst int yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 4, 1, 1, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, 7, 1, + 1, 1, 1, 1, 8, 9, 10, 11, 12, 1, + 1, 13, 14, 15, 1, 16, 17, 18, 19, 20, + 1, 21, 22, 23, 24, 25, 1, 1, 26, 1, + 1, 1, 1, 1, 27, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static yyconst int yy_meta[28] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1 + } ; + +static yyconst short int yy_base[92] = + { 0, + 0, 0, 100, 101, 97, 101, 93, 92, 101, 93, + 84, 12, 75, 15, 75, 68, 72, 66, 70, 11, + 19, 86, 82, 83, 101, 74, 65, 60, 65, 56, + 60, 13, 62, 70, 61, 56, 55, 60, 51, 49, + 52, 61, 101, 61, 49, 47, 101, 101, 42, 53, + 44, 52, 39, 101, 101, 43, 47, 101, 16, 101, + 48, 37, 49, 33, 34, 27, 101, 101, 30, 101, + 101, 40, 101, 39, 29, 101, 26, 22, 101, 101, + 101, 35, 101, 27, 33, 101, 101, 22, 101, 101, + 40 + + } ; + +static yyconst short int yy_def[92] = + { 0, + 90, 1, 90, 90, 90, 90, 90, 90, 90, 91, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 91, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 0, + 90 + + } ; + +static yyconst short int yy_nxt[129] = + { 0, + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 4, 4, 15, 16, 17, 18, 19, 4, 20, + 4, 21, 4, 4, 4, 4, 4, 27, 30, 37, + 40, 38, 49, 28, 39, 71, 72, 50, 31, 84, + 24, 41, 42, 89, 88, 87, 86, 85, 83, 82, + 81, 80, 79, 78, 77, 76, 75, 74, 73, 70, + 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, + 59, 58, 57, 56, 55, 54, 53, 52, 51, 48, + 47, 46, 45, 44, 43, 25, 23, 22, 36, 35, + 34, 33, 32, 29, 26, 25, 23, 23, 22, 90, + + 3, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90 + } ; + +static yyconst short int yy_chk[129] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 12, 14, 20, + 21, 20, 32, 12, 20, 59, 59, 32, 14, 78, + 91, 21, 21, 88, 85, 84, 82, 78, 77, 75, + 74, 72, 69, 66, 65, 64, 63, 62, 61, 57, + 56, 53, 52, 51, 50, 49, 46, 45, 44, 42, + 41, 40, 39, 38, 37, 36, 35, 34, 33, 31, + 30, 29, 28, 27, 26, 24, 23, 22, 19, 18, + 17, 16, 15, 13, 11, 10, 8, 7, 5, 3, + + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, + 90, 90, 90, 90, 90, 90, 90, 90 + } ; + +static yy_state_type yy_last_accepting_state; +static char *yy_last_accepting_cpos; + +/* The intent behind this definition is that it'll catch + * any uses of REJECT which flex missed. + */ +#define REJECT reject_used_but_not_detected +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +char *yytext; +#line 1 "vmlex.l" +#define INITIAL 0 +#line 2 "vmlex.l" +#include "vmparse.tab.h" +#include + +#ifndef __GNUC__ +#define YY_NO_UNISTD_H +#endif +#line 429 "lex.yy.c" + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int yywrap YY_PROTO(( void )); +#else +extern int yywrap YY_PROTO(( void )); +#endif +#endif + +#ifndef YY_NO_UNPUT +static void yyunput YY_PROTO(( int c, char *buf_ptr )); +#endif + +#ifndef yytext_ptr +static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen YY_PROTO(( yyconst char * )); +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus +static int yyinput YY_PROTO(( void )); +#else +static int input YY_PROTO(( void )); +#endif +#endif + +#if YY_STACK_USED +static int yy_start_stack_ptr = 0; +static int yy_start_stack_depth = 0; +static int *yy_start_stack = 0; +#ifndef YY_NO_PUSH_STATE +static void yy_push_state YY_PROTO(( int new_state )); +#endif +#ifndef YY_NO_POP_STATE +static void yy_pop_state YY_PROTO(( void )); +#endif +#ifndef YY_NO_TOP_STATE +static int yy_top_state YY_PROTO(( void )); +#endif + +#else +#define YY_NO_PUSH_STATE 1 +#define YY_NO_POP_STATE 1 +#define YY_NO_TOP_STATE 1 +#endif + +#ifdef YY_MALLOC_DECL +YY_MALLOC_DECL +#else +#if __STDC__ +#ifndef __cplusplus +#include +#endif +#else +/* Just try to get by without declaring the routines. This will fail + * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) + * or sizeof(void*) != sizeof(int). + */ +#endif +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#define YY_READ_BUF_SIZE 8192 +#endif + +/* Copy whatever the last rule matched to the standard output. */ + +#ifndef ECHO +/* This used to be an fputs(), but since the string might contain NUL's, + * we now use fwrite(). + */ +#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ + if ( yy_current_buffer->yy_is_interactive ) \ + { \ + int c = '*', n; \ + for ( n = 0; n < max_size && \ + (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ + buf[n] = (char) c; \ + if ( c == '\n' ) \ + buf[n++] = (char) c; \ + if ( c == EOF && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + result = n; \ + } \ + else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \ + && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) +#endif + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL int yylex YY_PROTO(( void )) +#endif + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK break; +#endif + +#define YY_RULE_SETUP \ + YY_USER_ACTION + +YY_DECL + { + register yy_state_type yy_current_state; + register char *yy_cp, *yy_bp; + register int yy_act; + +#line 17 "vmlex.l" + + +#line 583 "lex.yy.c" + + if ( yy_init ) + { + yy_init = 0; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! yy_start ) + yy_start = 1; /* first start state */ + + if ( ! yyin ) + yyin = stdin; + + if ( ! yyout ) + yyout = stdout; + + if ( ! yy_current_buffer ) + yy_current_buffer = + yy_create_buffer( yyin, YY_BUF_SIZE ); + + yy_load_buffer_state(); + } + + while ( 1 ) /* loops until end-of-file is reached */ + { + yy_cp = yy_c_buf_p; + + /* Support of yytext. */ + *yy_cp = yy_hold_char; + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + + yy_current_state = yy_start; +yy_match: + do + { + register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; + if ( yy_accept[yy_current_state] ) + { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 91 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + ++yy_cp; + } + while ( yy_base[yy_current_state] != 101 ); + +yy_find_action: + yy_act = yy_accept[yy_current_state]; + if ( yy_act == 0 ) + { /* have to back up */ + yy_cp = yy_last_accepting_cpos; + yy_current_state = yy_last_accepting_state; + yy_act = yy_accept[yy_current_state]; + } + + YY_DO_BEFORE_ACTION; + + +do_action: /* This label is used only to access EOF actions. */ + + + switch ( yy_act ) + { /* beginning of action switch */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = yy_hold_char; + yy_cp = yy_last_accepting_cpos; + yy_current_state = yy_last_accepting_state; + goto yy_find_action; + +case 1: +YY_RULE_SETUP +#line 19 "vmlex.l" + + YY_BREAK +case 2: +YY_RULE_SETUP +#line 20 "vmlex.l" + + YY_BREAK +case 3: +YY_RULE_SETUP +#line 21 "vmlex.l" + + YY_BREAK +case 4: +YY_RULE_SETUP +#line 22 "vmlex.l" +{ yylval = atoi(yytext); return T_INT; } + YY_BREAK +case 5: +YY_RULE_SETUP +#line 24 "vmlex.l" +{ return T_COLON; } + YY_BREAK +case 6: +YY_RULE_SETUP +#line 26 "vmlex.l" +{ return T_SET; } + YY_BREAK +case 7: +YY_RULE_SETUP +#line 27 "vmlex.l" +{ return T_STOP; } + YY_BREAK +case 8: +YY_RULE_SETUP +#line 28 "vmlex.l" +{ return T_LOAD; } + YY_BREAK +case 9: +YY_RULE_SETUP +#line 29 "vmlex.l" +{ return T_STORE; } + YY_BREAK +case 10: +YY_RULE_SETUP +#line 30 "vmlex.l" +{ return T_BLOAD; } + YY_BREAK +case 11: +YY_RULE_SETUP +#line 31 "vmlex.l" +{ return T_BSTORE; } + YY_BREAK +case 12: +YY_RULE_SETUP +#line 32 "vmlex.l" +{ return T_PUSH; } + YY_BREAK +case 13: +YY_RULE_SETUP +#line 33 "vmlex.l" +{ return T_POP; } + YY_BREAK +case 14: +YY_RULE_SETUP +#line 34 "vmlex.l" +{ return T_DUP; } + YY_BREAK +case 15: +YY_RULE_SETUP +#line 35 "vmlex.l" +{ return T_INVERT; } + YY_BREAK +case 16: +YY_RULE_SETUP +#line 36 "vmlex.l" +{ return T_ADD; } + YY_BREAK +case 17: +YY_RULE_SETUP +#line 37 "vmlex.l" +{ return T_SUB; } + YY_BREAK +case 18: +YY_RULE_SETUP +#line 38 "vmlex.l" +{ return T_MULT; } + YY_BREAK +case 19: +YY_RULE_SETUP +#line 39 "vmlex.l" +{ return T_DIV; } + YY_BREAK +case 20: +YY_RULE_SETUP +#line 40 "vmlex.l" +{ return T_COMPARE; } + YY_BREAK +case 21: +YY_RULE_SETUP +#line 41 "vmlex.l" +{ return T_JUMP; } + YY_BREAK +case 22: +YY_RULE_SETUP +#line 42 "vmlex.l" +{ return T_JUMP_YES; } + YY_BREAK +case 23: +YY_RULE_SETUP +#line 43 "vmlex.l" +{ return T_JUMP_NO; } + YY_BREAK +case 24: +YY_RULE_SETUP +#line 44 "vmlex.l" +{ return T_INPUT; } + YY_BREAK +case 25: +YY_RULE_SETUP +#line 45 "vmlex.l" +{ return T_PRINT; } + YY_BREAK +case 26: +YY_RULE_SETUP +#line 46 "vmlex.l" +{ return T_NOP; } + YY_BREAK +case YY_STATE_EOF(INITIAL): +#line 48 "vmlex.l" +{ yyterminate(); } + YY_BREAK +case 27: +YY_RULE_SETUP +#line 50 "vmlex.l" +ECHO; + YY_BREAK +#line 805 "lex.yy.c" + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = yy_hold_char; + YY_RESTORE_YY_MORE_OFFSET + + if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between yy_current_buffer and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + yy_n_chars = yy_current_buffer->yy_n_chars; + yy_current_buffer->yy_input_file = yyin; + yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state ); + + yy_bp = yytext_ptr + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++yy_c_buf_p; + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { + yy_cp = yy_c_buf_p; + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer() ) + { + case EOB_ACT_END_OF_FILE: + { + yy_did_buffer_switch_on_eof = 0; + + if ( yywrap() ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = + yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + yy_c_buf_p = + &yy_current_buffer->yy_ch_buf[yy_n_chars]; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of yylex */ + + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ + +static int yy_get_next_buffer() + { + register char *dest = yy_current_buffer->yy_ch_buf; + register char *source = yytext_ptr; + register int number_to_move, i; + int ret_val; + + if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( yy_current_buffer->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + yy_current_buffer->yy_n_chars = yy_n_chars = 0; + + else + { + int num_to_read = + yy_current_buffer->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ +#ifdef YY_USES_REJECT + YY_FATAL_ERROR( +"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); +#else + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = yy_current_buffer; + + int yy_c_buf_p_offset = + (int) (yy_c_buf_p - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + int new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yy_flex_realloc( (void *) b->yy_ch_buf, + b->yy_buf_size + 2 ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = 0; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = yy_current_buffer->yy_buf_size - + number_to_move - 1; +#endif + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), + yy_n_chars, num_to_read ); + + yy_current_buffer->yy_n_chars = yy_n_chars; + } + + if ( yy_n_chars == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart( yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + yy_current_buffer->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + yy_n_chars += number_to_move; + yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; + yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; + + yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; + + return ret_val; + } + + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + +static yy_state_type yy_get_previous_state() + { + register yy_state_type yy_current_state; + register char *yy_cp; + + yy_current_state = yy_start; + + for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) + { + register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if ( yy_accept[yy_current_state] ) + { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 91 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + } + + return yy_current_state; + } + + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ + +#ifdef YY_USE_PROTOS +static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) +#else +static yy_state_type yy_try_NUL_trans( yy_current_state ) +yy_state_type yy_current_state; +#endif + { + register int yy_is_jam; + register char *yy_cp = yy_c_buf_p; + + register YY_CHAR yy_c = 1; + if ( yy_accept[yy_current_state] ) + { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 91 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_is_jam = (yy_current_state == 90); + + return yy_is_jam ? 0 : yy_current_state; + } + + +#ifndef YY_NO_UNPUT +#ifdef YY_USE_PROTOS +static void yyunput( int c, register char *yy_bp ) +#else +static void yyunput( c, yy_bp ) +int c; +register char *yy_bp; +#endif + { + register char *yy_cp = yy_c_buf_p; + + /* undo effects of setting up yytext */ + *yy_cp = yy_hold_char; + + if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + register int number_to_move = yy_n_chars + 2; + register char *dest = &yy_current_buffer->yy_ch_buf[ + yy_current_buffer->yy_buf_size + 2]; + register char *source = + &yy_current_buffer->yy_ch_buf[number_to_move]; + + while ( source > yy_current_buffer->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + yy_current_buffer->yy_n_chars = + yy_n_chars = yy_current_buffer->yy_buf_size; + + if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + + + yytext_ptr = yy_bp; + yy_hold_char = *yy_cp; + yy_c_buf_p = yy_cp; + } +#endif /* ifndef YY_NO_UNPUT */ + + +#ifdef __cplusplus +static int yyinput() +#else +static int input() +#endif + { + int c; + + *yy_c_buf_p = yy_hold_char; + + if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) + /* This was really a NUL. */ + *yy_c_buf_p = '\0'; + + else + { /* need more input */ + int offset = yy_c_buf_p - yytext_ptr; + ++yy_c_buf_p; + + switch ( yy_get_next_buffer() ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart( yyin ); + + /* fall through */ + + case EOB_ACT_END_OF_FILE: + { + if ( yywrap() ) + return EOF; + + if ( ! yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = yytext_ptr + offset; + break; + } + } + } + + c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ + *yy_c_buf_p = '\0'; /* preserve yytext */ + yy_hold_char = *++yy_c_buf_p; + + + return c; + } + + +#ifdef YY_USE_PROTOS +void yyrestart( FILE *input_file ) +#else +void yyrestart( input_file ) +FILE *input_file; +#endif + { + if ( ! yy_current_buffer ) + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); + + yy_init_buffer( yy_current_buffer, input_file ); + yy_load_buffer_state(); + } + + +#ifdef YY_USE_PROTOS +void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +#else +void yy_switch_to_buffer( new_buffer ) +YY_BUFFER_STATE new_buffer; +#endif + { + if ( yy_current_buffer == new_buffer ) + return; + + if ( yy_current_buffer ) + { + /* Flush out information for old buffer. */ + *yy_c_buf_p = yy_hold_char; + yy_current_buffer->yy_buf_pos = yy_c_buf_p; + yy_current_buffer->yy_n_chars = yy_n_chars; + } + + yy_current_buffer = new_buffer; + yy_load_buffer_state(); + + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + yy_did_buffer_switch_on_eof = 1; + } + + +#ifdef YY_USE_PROTOS +void yy_load_buffer_state( void ) +#else +void yy_load_buffer_state() +#endif + { + yy_n_chars = yy_current_buffer->yy_n_chars; + yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; + yyin = yy_current_buffer->yy_input_file; + yy_hold_char = *yy_c_buf_p; + } + + +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) +#else +YY_BUFFER_STATE yy_create_buffer( file, size ) +FILE *file; +int size; +#endif + { + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_buf_size = size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + yy_init_buffer( b, file ); + + return b; + } + + +#ifdef YY_USE_PROTOS +void yy_delete_buffer( YY_BUFFER_STATE b ) +#else +void yy_delete_buffer( b ) +YY_BUFFER_STATE b; +#endif + { + if ( ! b ) + return; + + if ( b == yy_current_buffer ) + yy_current_buffer = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + yy_flex_free( (void *) b->yy_ch_buf ); + + yy_flex_free( (void *) b ); + } + + +#ifndef YY_ALWAYS_INTERACTIVE +#ifndef YY_NEVER_INTERACTIVE +extern int isatty YY_PROTO(( int )); +#endif +#endif + +#ifdef YY_USE_PROTOS +void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) +#else +void yy_init_buffer( b, file ) +YY_BUFFER_STATE b; +FILE *file; +#endif + + + { + yy_flush_buffer( b ); + + b->yy_input_file = file; + b->yy_fill_buffer = 1; + +#if YY_ALWAYS_INTERACTIVE + b->yy_is_interactive = 1; +#else +#if YY_NEVER_INTERACTIVE + b->yy_is_interactive = 0; +#else + b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; +#endif +#endif + } + + +#ifdef YY_USE_PROTOS +void yy_flush_buffer( YY_BUFFER_STATE b ) +#else +void yy_flush_buffer( b ) +YY_BUFFER_STATE b; +#endif + + { + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == yy_current_buffer ) + yy_load_buffer_state(); + } + + +#ifndef YY_NO_SCAN_BUFFER +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) +#else +YY_BUFFER_STATE yy_scan_buffer( base, size ) +char *base; +yy_size_t size; +#endif + { + YY_BUFFER_STATE b; + + if ( size < 2 || + base[size-2] != YY_END_OF_BUFFER_CHAR || + base[size-1] != YY_END_OF_BUFFER_CHAR ) + /* They forgot to leave room for the EOB's. */ + return 0; + + b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); + + b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_pos = b->yy_ch_buf = base; + b->yy_is_our_buffer = 0; + b->yy_input_file = 0; + b->yy_n_chars = b->yy_buf_size; + b->yy_is_interactive = 0; + b->yy_at_bol = 1; + b->yy_fill_buffer = 0; + b->yy_buffer_status = YY_BUFFER_NEW; + + yy_switch_to_buffer( b ); + + return b; + } +#endif + + +#ifndef YY_NO_SCAN_STRING +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) +#else +YY_BUFFER_STATE yy_scan_string( yy_str ) +yyconst char *yy_str; +#endif + { + int len; + for ( len = 0; yy_str[len]; ++len ) + ; + + return yy_scan_bytes( yy_str, len ); + } +#endif + + +#ifndef YY_NO_SCAN_BYTES +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) +#else +YY_BUFFER_STATE yy_scan_bytes( bytes, len ) +yyconst char *bytes; +int len; +#endif + { + YY_BUFFER_STATE b; + char *buf; + yy_size_t n; + int i; + + /* Get memory for full buffer, including space for trailing EOB's. */ + n = len + 2; + buf = (char *) yy_flex_alloc( n ); + if ( ! buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); + + for ( i = 0; i < len; ++i ) + buf[i] = bytes[i]; + + buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; + + b = yy_scan_buffer( buf, n ); + if ( ! b ) + YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); + + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->yy_is_our_buffer = 1; + + return b; + } +#endif + + +#ifndef YY_NO_PUSH_STATE +#ifdef YY_USE_PROTOS +static void yy_push_state( int new_state ) +#else +static void yy_push_state( new_state ) +int new_state; +#endif + { + if ( yy_start_stack_ptr >= yy_start_stack_depth ) + { + yy_size_t new_size; + + yy_start_stack_depth += YY_START_STACK_INCR; + new_size = yy_start_stack_depth * sizeof( int ); + + if ( ! yy_start_stack ) + yy_start_stack = (int *) yy_flex_alloc( new_size ); + + else + yy_start_stack = (int *) yy_flex_realloc( + (void *) yy_start_stack, new_size ); + + if ( ! yy_start_stack ) + YY_FATAL_ERROR( + "out of memory expanding start-condition stack" ); + } + + yy_start_stack[yy_start_stack_ptr++] = YY_START; + + BEGIN(new_state); + } +#endif + + +#ifndef YY_NO_POP_STATE +static void yy_pop_state() + { + if ( --yy_start_stack_ptr < 0 ) + YY_FATAL_ERROR( "start-condition stack underflow" ); + + BEGIN(yy_start_stack[yy_start_stack_ptr]); + } +#endif + + +#ifndef YY_NO_TOP_STATE +static int yy_top_state() + { + return yy_start_stack[yy_start_stack_ptr - 1]; + } +#endif + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +#ifdef YY_USE_PROTOS +static void yy_fatal_error( yyconst char msg[] ) +#else +static void yy_fatal_error( msg ) +char msg[]; +#endif + { + (void) fprintf( stderr, "%s\n", msg ); + exit( YY_EXIT_FAILURE ); + } + + + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + yytext[yyleng] = yy_hold_char; \ + yy_c_buf_p = yytext + n; \ + yy_hold_char = *yy_c_buf_p; \ + *yy_c_buf_p = '\0'; \ + yyleng = n; \ + } \ + while ( 0 ) + + +/* Internal utility routines. */ + +#ifndef yytext_ptr +#ifdef YY_USE_PROTOS +static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) +#else +static void yy_flex_strncpy( s1, s2, n ) +char *s1; +yyconst char *s2; +int n; +#endif + { + register int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; + } +#endif + +#ifdef YY_NEED_STRLEN +#ifdef YY_USE_PROTOS +static int yy_flex_strlen( yyconst char *s ) +#else +static int yy_flex_strlen( s ) +yyconst char *s; +#endif + { + register int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; + } +#endif + + +#ifdef YY_USE_PROTOS +static void *yy_flex_alloc( yy_size_t size ) +#else +static void *yy_flex_alloc( size ) +yy_size_t size; +#endif + { + return (void *) malloc( size ); + } + +#ifdef YY_USE_PROTOS +static void *yy_flex_realloc( void *ptr, yy_size_t size ) +#else +static void *yy_flex_realloc( ptr, size ) +void *ptr; +yy_size_t size; +#endif + { + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return (void *) realloc( (char *) ptr, size ); + } + +#ifdef YY_USE_PROTOS +static void yy_flex_free( void *ptr ) +#else +static void yy_flex_free( ptr ) +void *ptr; +#endif + { + free( ptr ); + } + +#if YY_MAIN +int main() + { + yylex(); + return 0; + } +#endif +#line 50 "vmlex.l" + + diff --git a/lab4/vm/vm/main.c b/lab4/vm/vm/main.c new file mode 100644 index 0000000..31698c7 --- /dev/null +++ b/lab4/vm/vm/main.c @@ -0,0 +1,46 @@ +#include "vm.h" +#include "vmparse.tab.h" +#include +#include + +extern FILE *yyin; +int need_close = 0; + +int yyparse(); + +void milan_error(char const * msg) +{ + if(need_close) + fclose(yyin); + + fprintf(stderr, msg); + exit(1); +} + +int main(int argc, char **argv) +{ + if(argc < 2) { + yyin = stdin; + printf("Reading input from stdin\n"); + } + else { + yyin = fopen(argv[1], "rt"); + if(!yyin) { + printf("Unable to read %s\n", argv[1]); + return 1; + } + + need_close = 1; + printf("Reading input from %s\n", argv[1]); + } + + if(0 == yyparse()) { + run(); + } + + if(need_close) { + fclose(yyin); + } + + return 0; +} diff --git a/lab4/vm/vm/test/bop1.ms b/lab4/vm/vm/test/bop1.ms new file mode 100644 index 0000000..296b955 --- /dev/null +++ b/lab4/vm/vm/test/bop1.ms @@ -0,0 +1,6 @@ +4: STOP +1: PUSH 20 +2: ADD +3: PRINT +0: PUSH 10 +2: MULT diff --git a/lab4/vm/vm/test/bop2.ms b/lab4/vm/vm/test/bop2.ms new file mode 100644 index 0000000..0ae0d54 --- /dev/null +++ b/lab4/vm/vm/test/bop2.ms @@ -0,0 +1,8 @@ +0: PUSH 10 +1: PUSH -1 +2: BSTORE 2 +3: PUSH 0 +4: BLOAD 1 +5: PRINT +6: STOP + diff --git a/lab4/vm/vm/test/fib.ms b/lab4/vm/vm/test/fib.ms new file mode 100644 index 0000000..654666a --- /dev/null +++ b/lab4/vm/vm/test/fib.ms @@ -0,0 +1,37 @@ +; N- + +SET 0 0 ; 0 +SET 1 1 ; 1 + +SET 1000 0 ; n +SET 1001 1 ; a +SET 1002 1 ; b + +; + + 0: INPUT + 1: STORE 1000 ; n := READ + + 2: LOAD 1000 + 3: LOAD 1 + 4: COMPARE 3 ; IF n > 1 + 5: JUMP_NO 17 + + 6: LOAD 1002 ; STACK <- b + 7: LOAD 1001 ; STACK <- a + 8: LOAD 1002 + 9: STORE 1001 ; a := b +10: ADD +11: STORE 1002 ; b := __a + b + +12: LOAD 1000 +13: LOAD 1 +14: SUB +15: STORE 1000 ; n := n - 1 +16: JUMP 2 + +17: LOAD 1001 ; WRITE(a) +18: PRINT + +19: STOP + diff --git a/lab4/vm/vm/test/fib2.ms b/lab4/vm/vm/test/fib2.ms new file mode 100644 index 0000000..fd01c89 --- /dev/null +++ b/lab4/vm/vm/test/fib2.ms @@ -0,0 +1,21 @@ +SET 0 1 +SET 1 1 + + 0: INPUT + 1: DUP + 2: PUSH 1 + 3: COMPARE 3 + 4: JUMP_NO 14 + 5: LOAD 1 + 6: LOAD 0 + 7: LOAD 1 + 8: STORE 0 + 9: ADD +10: STORE 1 +11: PUSH 1 +12: SUB +13: JUMP 1 +14: LOAD 0 +15: PRINT +16: STOP + \ No newline at end of file diff --git a/lab4/vm/vm/vm.c b/lab4/vm/vm/vm.c new file mode 100644 index 0000000..5738940 --- /dev/null +++ b/lab4/vm/vm/vm.c @@ -0,0 +1,371 @@ +#include +#include +#include "vm.h" + +void milan_error(); + +command vm_program[MAX_PROGRAM_SIZE]; + +int vm_memory[MAX_MEMORY_SIZE]; +int vm_stack[MAX_STACK_SIZE]; + +unsigned int vm_stack_pointer = 0; +unsigned int vm_command_pointer = 0; + +opcode_info opcodes_table[] = { + {"NOP", 0}, + {"STOP", 0}, + {"LOAD", 1}, + {"STORE", 1}, + {"BLOAD", 1}, + {"BSTORE", 1}, + {"PUSH", 1}, + {"POP", 0}, + {"DUP", 0}, + {"INVERT", 0}, + {"ADD", 0}, + {"SUB", 0}, + {"MULT", 0}, + {"DIV", 0}, + {"COMPARE", 1}, + {"JUMP", 1}, + {"JUMP_YES", 1}, + {"JUMP_NO", 1}, + {"INPUT", 0}, + {"PRINT", 0} +}; + +int opcodes_table_size = sizeof(opcodes_table) / sizeof(opcode_info); + +typedef enum { + BAD_DATA_ADDRESS, + BAD_CODE_ADDRESS, + BAD_RELATION, + STACK_OVERFLOW, + STACK_EMPTY, + DIVISION_BY_ZERO, + BAD_INPUT, + UNKNOWN_COMMAND +} runtime_error; + +void vm_init() +{ + vm_stack_pointer = 0; + vm_command_pointer = 0; +} + +void vm_error(runtime_error error) +{ + opcode_info* info; + + switch(error) { + case BAD_DATA_ADDRESS: + fprintf(stderr, "Error: illegal data address\n"); + break; + + case BAD_CODE_ADDRESS: + fprintf(stderr, "Error: illegal address in JUMP* instruction\n"); + break; + + case BAD_RELATION: + fprintf(stderr, "Error: illegal comparison operator\n"); + break; + + case STACK_OVERFLOW: + fprintf(stderr, "Error: stack overflow\n"); + break; + + case STACK_EMPTY: + fprintf(stderr, "Error: stack is empty (no arguments are available)\n"); + break; + + case DIVISION_BY_ZERO: + fprintf(stderr, "Error: division by zero\n"); + break; + + case BAD_INPUT: + fprintf(stderr, "Error: illegal input\n"); + break; + + case UNKNOWN_COMMAND: + fprintf(stderr, "Error: unknown command, unable to execute\n"); + break; + + default: + fprintf(stderr, "Error: runtime error %d\n", error); + } + + fprintf(stderr, "Code:\n\n"); + + info = operation_info(vm_program[vm_command_pointer].operation); + if(NULL == info) { + fprintf(stderr, "%d\t(%d)\t\t%d\n", vm_command_pointer, + vm_program[vm_command_pointer].operation, + vm_program[vm_command_pointer].arg); + } + else { + if(info->need_arg) { + fprintf(stderr, "\t%d\t%s\t\t%d\n", vm_command_pointer, info->name, + vm_program[vm_command_pointer].arg); + } + else { + fprintf(stderr, "\t%d\t%s\n", vm_command_pointer, info->name); + } + } + + milan_error("VM error"); +} + +int vm_load(unsigned int address) +{ + if(address < MAX_MEMORY_SIZE) { + return vm_memory[address]; + } + else { + vm_error(BAD_DATA_ADDRESS); + return 0; + } +} + +void vm_store(unsigned int address, int word) +{ + if(address < MAX_MEMORY_SIZE) { + vm_memory[address] = word; + } + else { + vm_error(BAD_DATA_ADDRESS); + } +} + +int vm_read() +{ + int n; + + fprintf(stderr, "> "); fflush(stdout); + if(scanf("%d", &n)) { + return n; + } + else { + vm_error(BAD_INPUT); + return 0; + } +} + +void vm_write(int n) +{ + fprintf(stderr, "%d\n", n); +} + +int vm_pop() +{ + if(vm_stack_pointer > 0) { + return vm_stack[--vm_stack_pointer]; + } + else { + vm_error(STACK_EMPTY); + return 0; + } +} + +void vm_push(int word) +{ + if(vm_stack_pointer < MAX_STACK_SIZE) { + vm_stack[vm_stack_pointer++] = word; + } + else { + vm_error(STACK_OVERFLOW); + } +} + +int vm_run_command() +{ + unsigned int index = vm_command_pointer; + + operation op = vm_program[index].operation; + unsigned int arg = vm_program[index].arg; + int data; + + switch(op) { + case NOP: + /* */ + break; + + case STOP: + return 0; + break; + + case LOAD: + vm_push(vm_load(arg)); + break; + + case STORE: + vm_store(arg, vm_pop()); + break; + + case BLOAD: + vm_push(vm_load(arg + vm_pop())); + break; + + case BSTORE: + data = vm_pop(); + vm_store(arg + data, vm_pop()); + break; + + case PUSH: + vm_push(arg); + break; + + case POP: + vm_pop(); + break; + + case DUP: + data = vm_pop(); + vm_push(data); + vm_push(data); + break; + + case INVERT: + vm_push(-vm_pop()); + break; + + case ADD: + data = vm_pop(); + vm_push(vm_pop() + data); + break; + + case SUB: + data = vm_pop(); + vm_push(vm_pop() - data); + break; + + case MULT: + data = vm_pop(); + vm_push(vm_pop() * data); + break; + + case DIV: + data = vm_pop(); + if(0 == data) { + vm_error(DIVISION_BY_ZERO); + } + else { + vm_push(vm_pop() / data); + } + break; + + case COMPARE: + data = vm_pop(); + switch(arg) { + case EQ: + vm_push((vm_pop() == data) ? 1 : 0); + break; + + case NE: + vm_push((vm_pop() != data) ? 1 : 0); + break; + + case LT: + vm_push((vm_pop() < data) ? 1 : 0); + break; + + case GT: + vm_push((vm_pop() > data) ? 1 : 0); + break; + + case LE: + vm_push((vm_pop() <= data) ? 1 : 0); + break; + + case GE: + vm_push((vm_pop() >= data) ? 1 : 0); + break; + + default: + vm_error(BAD_RELATION); + } + break; + + case JUMP: + if(arg < MAX_PROGRAM_SIZE) { + vm_command_pointer = arg; + return 1; + } + else { + vm_error(BAD_CODE_ADDRESS); + } + + break; + + case JUMP_YES: + if(arg < MAX_PROGRAM_SIZE) { + data = vm_pop(); + if(data) { + vm_command_pointer = arg; + return 1; + } + } + else { + vm_error(BAD_CODE_ADDRESS); + } + break; + + case JUMP_NO: + if(arg < MAX_PROGRAM_SIZE) { + data = vm_pop(); + if(!data) { + vm_command_pointer = arg; + return 1; + } + } + else { + vm_error(BAD_CODE_ADDRESS); + } + break; + + case INPUT: + vm_push(vm_read()); + break; + + case PRINT: + vm_write(vm_pop()); + break; + + default: + vm_error(UNKNOWN_COMMAND); + } + + ++vm_command_pointer; + return 1; +} + +void run() +{ + vm_command_pointer = 0; + while(vm_command_pointer < MAX_PROGRAM_SIZE) { + if(!vm_run_command()) + break; + } +} + +opcode_info* operation_info(operation op) +{ + return (op < opcodes_table_size) ? &opcodes_table[op] : NULL; +} + +void put_command(unsigned int address, operation op, int arg) +{ + if(address < MAX_PROGRAM_SIZE) { + vm_program[address].operation = op; + vm_program[address].arg = arg; + } + else { + milan_error("Illegal address in put_command()"); + } +} + +void set_mem(unsigned int address, int value) +{ + vm_memory[address] = value; +} + diff --git a/lab4/vm/vm/vm.h b/lab4/vm/vm/vm.h new file mode 100644 index 0000000..9f444a1 --- /dev/null +++ b/lab4/vm/vm/vm.h @@ -0,0 +1,88 @@ +#ifndef _MILAN_VM_H +#define _MILAN_VM_H + +#include + +/* */ + +/* */ +#define MAX_PROGRAM_SIZE 65536 + +/* */ +#define MAX_MEMORY_SIZE 65536 + +/* */ +#define MAX_STACK_SIZE 8192 + +/* */ +typedef enum { + NOP = 0, /* */ + STOP, /* */ + LOAD, /* */ + STORE, /* */ + BLOAD, /* */ + BSTORE, /* */ + PUSH, /* */ + POP, /* */ + DUP, /* */ + INVERT, /* */ + ADD, /* */ + SUB, /* */ + MULT, /* */ + DIV, /* */ + COMPARE, /* */ + JUMP, /* */ + JUMP_YES, /* , 0 */ + JUMP_NO, /* , 0 */ + INPUT, /* */ + PRINT /* */ +} operation; + +/* */ +typedef enum { + EQ, /* = */ + NE, /* !- */ + LT, /* < */ + GT, /* > */ + LE, /* <= */ + GE /* >= */ +} compare_type; + +/* */ +typedef struct { + operation operation; /* */ + int arg; /* */ +} command; + +/* */ +typedef struct opcode_info { + char *name; /* */ + int need_arg; /* , 1, */ +} opcode_info; + +/* op. + * , + * , . + */ + +opcode_info* operation_info(operation op); + +/* address. */ + +void put_command(unsigned int address, operation op, int arg); + +/* . + * + * 0 , + * STOP + * . + */ + +void run(); + +/* value address. */ + +void set_mem(unsigned int address, int value); + +#endif + diff --git a/lab4/vm/vm/vmlex.l b/lab4/vm/vm/vmlex.l new file mode 100644 index 0000000..0ea8f88 --- /dev/null +++ b/lab4/vm/vm/vmlex.l @@ -0,0 +1,51 @@ +%{ +#include "vmparse.tab.h" +#include + +#ifndef __GNUC__ +#define YY_NO_UNISTD_H +#endif +%} + +%option noyywrap + +WHITESPACE [ \t]+ +EOL \n +INT -?[0-9]+ +COMMENT ;[^\n]*\n + +%% + +{EOL} +{COMMENT} +{WHITESPACE} +{INT} { yylval = atoi(yytext); return T_INT; } + +: { return T_COLON; } + +SET { return T_SET; } +STOP { return T_STOP; } +LOAD { return T_LOAD; } +STORE { return T_STORE; } +BLOAD { return T_BLOAD; } +BSTORE { return T_BSTORE; } +PUSH { return T_PUSH; } +POP { return T_POP; } +DUP { return T_DUP; } +INVERT { return T_INVERT; } +ADD { return T_ADD; } +SUB { return T_SUB; } +MULT { return T_MULT; } +DIV { return T_DIV; } +COMPARE { return T_COMPARE; } +JUMP { return T_JUMP; } +JUMP_YES { return T_JUMP_YES; } +JUMP_NO { return T_JUMP_NO; } +INPUT { return T_INPUT; } +PRINT { return T_PRINT; } +NOP { return T_NOP; } + +<> { yyterminate(); } + +%% + diff --git a/lab4/vm/vm/vmparse.tab.c b/lab4/vm/vm/vmparse.tab.c new file mode 100644 index 0000000..a703788 --- /dev/null +++ b/lab4/vm/vm/vmparse.tab.c @@ -0,0 +1,1736 @@ + +/* A Bison parser, made by GNU Bison 2.4.1. */ + +/* Skeleton implementation for Bison's Yacc-like parsers in C + + Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* C LALR(1) parser skeleton written by Richard Stallman, by + simplifying the original so-called "semantic" parser. */ + +/* All symbols defined below should begin with yy or YY, to avoid + infringing on user name space. This should be done even for local + variables, as they might otherwise be expanded by user macros. + There are some unavoidable exceptions within include files to + define necessary library symbols; they are noted "INFRINGES ON + USER NAME SPACE" below. */ + +/* Identify Bison output. */ +#define YYBISON 1 + +/* Bison version. */ +#define YYBISON_VERSION "2.4.1" + +/* Skeleton name. */ +#define YYSKELETON_NAME "yacc.c" + +/* Pure parsers. */ +#define YYPURE 0 + +/* Push parsers. */ +#define YYPUSH 0 + +/* Pull parsers. */ +#define YYPULL 1 + +/* Using locations. */ +#define YYLSP_NEEDED 0 + + + +/* Copy the first part of user declarations. */ + +/* Line 189 of yacc.c */ +#line 1 "vmparse.y" + +#include "vm.h" +#include +#include + +#define YYSTYPE int + +int yylex(); +void yyerror(char const *); + + +/* Line 189 of yacc.c */ +#line 85 "vmparse.tab.c" + +/* Enabling traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif + +/* Enabling verbose error messages. */ +#ifdef YYERROR_VERBOSE +# undef YYERROR_VERBOSE +# define YYERROR_VERBOSE 1 +#else +# define YYERROR_VERBOSE 0 +#endif + +/* Enabling the token table. */ +#ifndef YYTOKEN_TABLE +# define YYTOKEN_TABLE 0 +#endif + + +/* Tokens. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + /* Put the tokens into the symbol table, so that GDB and other debuggers + know about them. */ + enum yytokentype { + T_INT = 258, + T_SET = 259, + T_NOP = 260, + T_STOP = 261, + T_LOAD = 262, + T_STORE = 263, + T_BLOAD = 264, + T_BSTORE = 265, + T_PUSH = 266, + T_POP = 267, + T_DUP = 268, + T_INVERT = 269, + T_ADD = 270, + T_SUB = 271, + T_MULT = 272, + T_DIV = 273, + T_COMPARE = 274, + T_JUMP = 275, + T_JUMP_YES = 276, + T_JUMP_NO = 277, + T_INPUT = 278, + T_PRINT = 279, + T_COLON = 280 + }; +#endif + + + +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED +typedef int YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define yystype YYSTYPE /* obsolescent; will be withdrawn */ +# define YYSTYPE_IS_DECLARED 1 +#endif + + +/* Copy the second part of user declarations. */ + + +/* Line 264 of yacc.c */ +#line 152 "vmparse.tab.c" + +#ifdef short +# undef short +#endif + +#ifdef YYTYPE_UINT8 +typedef YYTYPE_UINT8 yytype_uint8; +#else +typedef unsigned char yytype_uint8; +#endif + +#ifdef YYTYPE_INT8 +typedef YYTYPE_INT8 yytype_int8; +#elif (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +typedef signed char yytype_int8; +#else +typedef short int yytype_int8; +#endif + +#ifdef YYTYPE_UINT16 +typedef YYTYPE_UINT16 yytype_uint16; +#else +typedef unsigned short int yytype_uint16; +#endif + +#ifdef YYTYPE_INT16 +typedef YYTYPE_INT16 yytype_int16; +#else +typedef short int yytype_int16; +#endif + +#ifndef YYSIZE_T +# ifdef __SIZE_TYPE__ +# define YYSIZE_T __SIZE_TYPE__ +# elif defined size_t +# define YYSIZE_T size_t +# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +# include /* INFRINGES ON USER NAME SPACE */ +# define YYSIZE_T size_t +# else +# define YYSIZE_T unsigned int +# endif +#endif + +#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) + +#ifndef YY_ +# if YYENABLE_NLS +# if ENABLE_NLS +# include /* INFRINGES ON USER NAME SPACE */ +# define YY_(msgid) dgettext ("bison-runtime", msgid) +# endif +# endif +# ifndef YY_ +# define YY_(msgid) msgid +# endif +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YYUSE(e) ((void) (e)) +#else +# define YYUSE(e) /* empty */ +#endif + +/* Identity function, used to suppress warnings about constant conditions. */ +#ifndef lint +# define YYID(n) (n) +#else +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static int +YYID (int yyi) +#else +static int +YYID (yyi) + int yyi; +#endif +{ + return yyi; +} +#endif + +#if ! defined yyoverflow || YYERROR_VERBOSE + +/* The parser invokes alloca or malloc; define the necessary symbols. */ + +# ifdef YYSTACK_USE_ALLOCA +# if YYSTACK_USE_ALLOCA +# ifdef __GNUC__ +# define YYSTACK_ALLOC __builtin_alloca +# elif defined __BUILTIN_VA_ARG_INCR +# include /* INFRINGES ON USER NAME SPACE */ +# elif defined _AIX +# define YYSTACK_ALLOC __alloca +# elif defined _MSC_VER +# include /* INFRINGES ON USER NAME SPACE */ +# define alloca _alloca +# else +# define YYSTACK_ALLOC alloca +# if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +# include /* INFRINGES ON USER NAME SPACE */ +# ifndef _STDLIB_H +# define _STDLIB_H 1 +# endif +# endif +# endif +# endif +# endif + +# ifdef YYSTACK_ALLOC + /* Pacify GCC's `empty if-body' warning. */ +# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) +# ifndef YYSTACK_ALLOC_MAXIMUM + /* The OS might guarantee only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + invoke alloca (N) if N exceeds 4096. Use a slightly smaller number + to allow for a few compiler-allocated temporary stack slots. */ +# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ +# endif +# else +# define YYSTACK_ALLOC YYMALLOC +# define YYSTACK_FREE YYFREE +# ifndef YYSTACK_ALLOC_MAXIMUM +# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM +# endif +# if (defined __cplusplus && ! defined _STDLIB_H \ + && ! ((defined YYMALLOC || defined malloc) \ + && (defined YYFREE || defined free))) +# include /* INFRINGES ON USER NAME SPACE */ +# ifndef _STDLIB_H +# define _STDLIB_H 1 +# endif +# endif +# ifndef YYMALLOC +# define YYMALLOC malloc +# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# ifndef YYFREE +# define YYFREE free +# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +void free (void *); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# endif +#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ + + +#if (! defined yyoverflow \ + && (! defined __cplusplus \ + || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) + +/* A type that is properly aligned for any stack member. */ +union yyalloc +{ + yytype_int16 yyss_alloc; + YYSTYPE yyvs_alloc; +}; + +/* The size of the maximum gap between one aligned stack and the next. */ +# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) + +/* The size of an array large to enough to hold all stacks, each with + N elements. */ +# define YYSTACK_BYTES(N) \ + ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + + YYSTACK_GAP_MAXIMUM) + +/* Copy COUNT objects from FROM to TO. The source and destination do + not overlap. */ +# ifndef YYCOPY +# if defined __GNUC__ && 1 < __GNUC__ +# define YYCOPY(To, From, Count) \ + __builtin_memcpy (To, From, (Count) * sizeof (*(From))) +# else +# define YYCOPY(To, From, Count) \ + do \ + { \ + YYSIZE_T yyi; \ + for (yyi = 0; yyi < (Count); yyi++) \ + (To)[yyi] = (From)[yyi]; \ + } \ + while (YYID (0)) +# endif +# endif + +/* Relocate STACK from its old location to the new one. The + local variables YYSIZE and YYSTACKSIZE give the old and new number of + elements in the stack, and YYPTR gives the new location of the + stack. Advance YYPTR to a properly aligned location for the next + stack. */ +# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ + do \ + { \ + YYSIZE_T yynewbytes; \ + YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ + Stack = &yyptr->Stack_alloc; \ + yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ + yyptr += yynewbytes / sizeof (*yyptr); \ + } \ + while (YYID (0)) + +#endif + +/* YYFINAL -- State number of the termination state. */ +#define YYFINAL 7 +/* YYLAST -- Last index in YYTABLE. */ +#define YYLAST 37 + +/* YYNTOKENS -- Number of terminals. */ +#define YYNTOKENS 26 +/* YYNNTS -- Number of nonterminals. */ +#define YYNNTS 3 +/* YYNRULES -- Number of rules. */ +#define YYNRULES 24 +/* YYNRULES -- Number of states. */ +#define YYNSTATES 39 + +/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ +#define YYUNDEFTOK 2 +#define YYMAXUTOK 280 + +#define YYTRANSLATE(YYX) \ + ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) + +/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ +static const yytype_uint8 yytranslate[] = +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25 +}; + +#if YYDEBUG +/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in + YYRHS. */ +static const yytype_uint8 yyprhs[] = +{ + 0, 0, 3, 6, 8, 12, 16, 21, 26, 31, + 36, 41, 45, 49, 53, 57, 61, 65, 69, 74, + 79, 84, 89, 93, 97 +}; + +/* YYRHS -- A `-1'-separated list of the rules' RHS. */ +static const yytype_int8 yyrhs[] = +{ + 27, 0, -1, 28, 27, -1, 28, -1, 3, 25, + 5, -1, 3, 25, 6, -1, 3, 25, 7, 3, + -1, 3, 25, 8, 3, -1, 3, 25, 9, 3, + -1, 3, 25, 10, 3, -1, 3, 25, 11, 3, + -1, 3, 25, 12, -1, 3, 25, 13, -1, 3, + 25, 14, -1, 3, 25, 15, -1, 3, 25, 16, + -1, 3, 25, 17, -1, 3, 25, 18, -1, 3, + 25, 19, 3, -1, 3, 25, 20, 3, -1, 3, + 25, 21, 3, -1, 3, 25, 22, 3, -1, 3, + 25, 23, -1, 3, 25, 24, -1, 4, 3, 3, + -1 +}; + +/* YYRLINE[YYN] -- source line where rule number YYN was defined. */ +static const yytype_uint8 yyrline[] = +{ + 0, 38, 38, 39, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62 +}; +#endif + +#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE +/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + First, the terminals, then, starting at YYNTOKENS, nonterminals. */ +static const char *const yytname[] = +{ + "$end", "error", "$undefined", "T_INT", "T_SET", "T_NOP", "T_STOP", + "T_LOAD", "T_STORE", "T_BLOAD", "T_BSTORE", "T_PUSH", "T_POP", "T_DUP", + "T_INVERT", "T_ADD", "T_SUB", "T_MULT", "T_DIV", "T_COMPARE", "T_JUMP", + "T_JUMP_YES", "T_JUMP_NO", "T_INPUT", "T_PRINT", "T_COLON", "$accept", + "program", "line", 0 +}; +#endif + +# ifdef YYPRINT +/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to + token YYLEX-NUM. */ +static const yytype_uint16 yytoknum[] = +{ + 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, + 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, + 275, 276, 277, 278, 279, 280 +}; +# endif + +/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ +static const yytype_uint8 yyr1[] = +{ + 0, 26, 27, 27, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28 +}; + +/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ +static const yytype_uint8 yyr2[] = +{ + 0, 2, 2, 1, 3, 3, 4, 4, 4, 4, + 4, 3, 3, 3, 3, 3, 3, 3, 4, 4, + 4, 4, 3, 3, 3 +}; + +/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state + STATE-NUM when YYTABLE doesn't specify something else to do. Zero + means the default is an error. */ +static const yytype_uint8 yydefact[] = +{ + 0, 0, 0, 0, 3, 0, 0, 1, 2, 4, + 5, 0, 0, 0, 0, 0, 11, 12, 13, 14, + 15, 16, 17, 0, 0, 0, 0, 22, 23, 24, + 6, 7, 8, 9, 10, 18, 19, 20, 21 +}; + +/* YYDEFGOTO[NTERM-NUM]. */ +static const yytype_int8 yydefgoto[] = +{ + -1, 3, 4 +}; + +/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + STATE-NUM. */ +#define YYPACT_NINF -6 +static const yytype_int8 yypact[] = +{ + 17, -3, 20, 24, 17, -5, 22, -6, -6, -6, + -6, 23, 25, 26, 27, 28, -6, -6, -6, -6, + -6, -6, -6, 29, 30, 31, 32, -6, -6, -6, + -6, -6, -6, -6, -6, -6, -6, -6, -6 +}; + +/* YYPGOTO[NTERM-NUM]. */ +static const yytype_int8 yypgoto[] = +{ + -6, 33, -6 +}; + +/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If + positive, shift that token. If negative, reduce the rule which + number is the opposite. If zero, do what YYDEFACT says. + If YYTABLE_NINF, syntax error. */ +#define YYTABLE_NINF -1 +static const yytype_uint8 yytable[] = +{ + 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 1, 2, 5, 6, 7, 29, 30, 0, 31, 32, + 33, 34, 35, 36, 37, 38, 0, 8 +}; + +static const yytype_int8 yycheck[] = +{ + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 3, 4, 25, 3, 0, 3, 3, -1, 3, 3, + 3, 3, 3, 3, 3, 3, -1, 4 +}; + +/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing + symbol of state STATE-NUM. */ +static const yytype_uint8 yystos[] = +{ + 0, 3, 4, 27, 28, 25, 3, 0, 27, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3 +}; + +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) +#define YYEMPTY (-2) +#define YYEOF 0 + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab + + +/* Like YYERROR except do call yyerror. This remains here temporarily + to ease the transition to the new meaning of YYERROR, for GCC. + Once GCC version 2 has supplanted version 1, this can go. */ + +#define YYFAIL goto yyerrlab + +#define YYRECOVERING() (!!yyerrstatus) + +#define YYBACKUP(Token, Value) \ +do \ + if (yychar == YYEMPTY && yylen == 1) \ + { \ + yychar = (Token); \ + yylval = (Value); \ + yytoken = YYTRANSLATE (yychar); \ + YYPOPSTACK (1); \ + goto yybackup; \ + } \ + else \ + { \ + yyerror (YY_("syntax error: cannot back up")); \ + YYERROR; \ + } \ +while (YYID (0)) + + +#define YYTERROR 1 +#define YYERRCODE 256 + + +/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. + If N is 0, then set CURRENT to the empty location which ends + the previous symbol: RHS[0] (always defined). */ + +#define YYRHSLOC(Rhs, K) ((Rhs)[K]) +#ifndef YYLLOC_DEFAULT +# define YYLLOC_DEFAULT(Current, Rhs, N) \ + do \ + if (YYID (N)) \ + { \ + (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ + (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ + (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ + (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ + } \ + else \ + { \ + (Current).first_line = (Current).last_line = \ + YYRHSLOC (Rhs, 0).last_line; \ + (Current).first_column = (Current).last_column = \ + YYRHSLOC (Rhs, 0).last_column; \ + } \ + while (YYID (0)) +#endif + + +/* YY_LOCATION_PRINT -- Print the location on the stream. + This macro was not mandated originally: define only if we know + we won't break user code: when these are the locations we know. */ + +#ifndef YY_LOCATION_PRINT +# if YYLTYPE_IS_TRIVIAL +# define YY_LOCATION_PRINT(File, Loc) \ + fprintf (File, "%d.%d-%d.%d", \ + (Loc).first_line, (Loc).first_column, \ + (Loc).last_line, (Loc).last_column) +# else +# define YY_LOCATION_PRINT(File, Loc) ((void) 0) +# endif +#endif + + +/* YYLEX -- calling `yylex' with the right arguments. */ + +#ifdef YYLEX_PARAM +# define YYLEX yylex (YYLEX_PARAM) +#else +# define YYLEX yylex () +#endif + +/* Enable debugging if requested. */ +#if YYDEBUG + +# ifndef YYFPRINTF +# include /* INFRINGES ON USER NAME SPACE */ +# define YYFPRINTF fprintf +# endif + +# define YYDPRINTF(Args) \ +do { \ + if (yydebug) \ + YYFPRINTF Args; \ +} while (YYID (0)) + +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ +do { \ + if (yydebug) \ + { \ + YYFPRINTF (stderr, "%s ", Title); \ + yy_symbol_print (stderr, \ + Type, Value); \ + YYFPRINTF (stderr, "\n"); \ + } \ +} while (YYID (0)) + + +/*--------------------------------. +| Print this symbol on YYOUTPUT. | +`--------------------------------*/ + +/*ARGSUSED*/ +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static void +yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) +#else +static void +yy_symbol_value_print (yyoutput, yytype, yyvaluep) + FILE *yyoutput; + int yytype; + YYSTYPE const * const yyvaluep; +#endif +{ + if (!yyvaluep) + return; +# ifdef YYPRINT + if (yytype < YYNTOKENS) + YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); +# else + YYUSE (yyoutput); +# endif + switch (yytype) + { + default: + break; + } +} + + +/*--------------------------------. +| Print this symbol on YYOUTPUT. | +`--------------------------------*/ + +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static void +yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) +#else +static void +yy_symbol_print (yyoutput, yytype, yyvaluep) + FILE *yyoutput; + int yytype; + YYSTYPE const * const yyvaluep; +#endif +{ + if (yytype < YYNTOKENS) + YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); + else + YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); + + yy_symbol_value_print (yyoutput, yytype, yyvaluep); + YYFPRINTF (yyoutput, ")"); +} + +/*------------------------------------------------------------------. +| yy_stack_print -- Print the state stack from its BOTTOM up to its | +| TOP (included). | +`------------------------------------------------------------------*/ + +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static void +yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) +#else +static void +yy_stack_print (yybottom, yytop) + yytype_int16 *yybottom; + yytype_int16 *yytop; +#endif +{ + YYFPRINTF (stderr, "Stack now"); + for (; yybottom <= yytop; yybottom++) + { + int yybot = *yybottom; + YYFPRINTF (stderr, " %d", yybot); + } + YYFPRINTF (stderr, "\n"); +} + +# define YY_STACK_PRINT(Bottom, Top) \ +do { \ + if (yydebug) \ + yy_stack_print ((Bottom), (Top)); \ +} while (YYID (0)) + + +/*------------------------------------------------. +| Report that the YYRULE is going to be reduced. | +`------------------------------------------------*/ + +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static void +yy_reduce_print (YYSTYPE *yyvsp, int yyrule) +#else +static void +yy_reduce_print (yyvsp, yyrule) + YYSTYPE *yyvsp; + int yyrule; +#endif +{ + int yynrhs = yyr2[yyrule]; + int yyi; + unsigned long int yylno = yyrline[yyrule]; + YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", + yyrule - 1, yylno); + /* The symbols being reduced. */ + for (yyi = 0; yyi < yynrhs; yyi++) + { + YYFPRINTF (stderr, " $%d = ", yyi + 1); + yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], + &(yyvsp[(yyi + 1) - (yynrhs)]) + ); + YYFPRINTF (stderr, "\n"); + } +} + +# define YY_REDUCE_PRINT(Rule) \ +do { \ + if (yydebug) \ + yy_reduce_print (yyvsp, Rule); \ +} while (YYID (0)) + +/* Nonzero means print parse trace. It is left uninitialized so that + multiple parsers can coexist. */ +int yydebug; +#else /* !YYDEBUG */ +# define YYDPRINTF(Args) +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) +# define YY_STACK_PRINT(Bottom, Top) +# define YY_REDUCE_PRINT(Rule) +#endif /* !YYDEBUG */ + + +/* YYINITDEPTH -- initial size of the parser's stacks. */ +#ifndef YYINITDEPTH +# define YYINITDEPTH 200 +#endif + +/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only + if the built-in stack extension method is used). + + Do not make this value too large; the results are undefined if + YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) + evaluated with infinite-precision integer arithmetic. */ + +#ifndef YYMAXDEPTH +# define YYMAXDEPTH 10000 +#endif + + + +#if YYERROR_VERBOSE + +# ifndef yystrlen +# if defined __GLIBC__ && defined _STRING_H +# define yystrlen strlen +# else +/* Return the length of YYSTR. */ +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static YYSIZE_T +yystrlen (const char *yystr) +#else +static YYSIZE_T +yystrlen (yystr) + const char *yystr; +#endif +{ + YYSIZE_T yylen; + for (yylen = 0; yystr[yylen]; yylen++) + continue; + return yylen; +} +# endif +# endif + +# ifndef yystpcpy +# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE +# define yystpcpy stpcpy +# else +/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in + YYDEST. */ +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static char * +yystpcpy (char *yydest, const char *yysrc) +#else +static char * +yystpcpy (yydest, yysrc) + char *yydest; + const char *yysrc; +#endif +{ + char *yyd = yydest; + const char *yys = yysrc; + + while ((*yyd++ = *yys++) != '\0') + continue; + + return yyd - 1; +} +# endif +# endif + +# ifndef yytnamerr +/* Copy to YYRES the contents of YYSTR after stripping away unnecessary + quotes and backslashes, so that it's suitable for yyerror. The + heuristic is that double-quoting is unnecessary unless the string + contains an apostrophe, a comma, or backslash (other than + backslash-backslash). YYSTR is taken from yytname. If YYRES is + null, do not copy; instead, return the length of what the result + would have been. */ +static YYSIZE_T +yytnamerr (char *yyres, const char *yystr) +{ + if (*yystr == '"') + { + YYSIZE_T yyn = 0; + char const *yyp = yystr; + + for (;;) + switch (*++yyp) + { + case '\'': + case ',': + goto do_not_strip_quotes; + + case '\\': + if (*++yyp != '\\') + goto do_not_strip_quotes; + /* Fall through. */ + default: + if (yyres) + yyres[yyn] = *yyp; + yyn++; + break; + + case '"': + if (yyres) + yyres[yyn] = '\0'; + return yyn; + } + do_not_strip_quotes: ; + } + + if (! yyres) + return yystrlen (yystr); + + return yystpcpy (yyres, yystr) - yyres; +} +# endif + +/* Copy into YYRESULT an error message about the unexpected token + YYCHAR while in state YYSTATE. Return the number of bytes copied, + including the terminating null byte. If YYRESULT is null, do not + copy anything; just return the number of bytes that would be + copied. As a special case, return 0 if an ordinary "syntax error" + message will do. Return YYSIZE_MAXIMUM if overflow occurs during + size calculation. */ +static YYSIZE_T +yysyntax_error (char *yyresult, int yystate, int yychar) +{ + int yyn = yypact[yystate]; + + if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) + return 0; + else + { + int yytype = YYTRANSLATE (yychar); + YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); + YYSIZE_T yysize = yysize0; + YYSIZE_T yysize1; + int yysize_overflow = 0; + enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; + char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; + int yyx; + +# if 0 + /* This is so xgettext sees the translatable formats that are + constructed on the fly. */ + YY_("syntax error, unexpected %s"); + YY_("syntax error, unexpected %s, expecting %s"); + YY_("syntax error, unexpected %s, expecting %s or %s"); + YY_("syntax error, unexpected %s, expecting %s or %s or %s"); + YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); +# endif + char *yyfmt; + char const *yyf; + static char const yyunexpected[] = "syntax error, unexpected %s"; + static char const yyexpecting[] = ", expecting %s"; + static char const yyor[] = " or %s"; + char yyformat[sizeof yyunexpected + + sizeof yyexpecting - 1 + + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) + * (sizeof yyor - 1))]; + char const *yyprefix = yyexpecting; + + /* Start YYX at -YYN if negative to avoid negative indexes in + YYCHECK. */ + int yyxbegin = yyn < 0 ? -yyn : 0; + + /* Stay within bounds of both yycheck and yytname. */ + int yychecklim = YYLAST - yyn + 1; + int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; + int yycount = 1; + + yyarg[0] = yytname[yytype]; + yyfmt = yystpcpy (yyformat, yyunexpected); + + for (yyx = yyxbegin; yyx < yyxend; ++yyx) + if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) + { + if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) + { + yycount = 1; + yysize = yysize0; + yyformat[sizeof yyunexpected - 1] = '\0'; + break; + } + yyarg[yycount++] = yytname[yyx]; + yysize1 = yysize + yytnamerr (0, yytname[yyx]); + yysize_overflow |= (yysize1 < yysize); + yysize = yysize1; + yyfmt = yystpcpy (yyfmt, yyprefix); + yyprefix = yyor; + } + + yyf = YY_(yyformat); + yysize1 = yysize + yystrlen (yyf); + yysize_overflow |= (yysize1 < yysize); + yysize = yysize1; + + if (yysize_overflow) + return YYSIZE_MAXIMUM; + + if (yyresult) + { + /* Avoid sprintf, as that infringes on the user's name space. + Don't have undefined behavior even if the translation + produced a string with the wrong number of "%s"s. */ + char *yyp = yyresult; + int yyi = 0; + while ((*yyp = *yyf) != '\0') + { + if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) + { + yyp += yytnamerr (yyp, yyarg[yyi++]); + yyf += 2; + } + else + { + yyp++; + yyf++; + } + } + } + return yysize; + } +} +#endif /* YYERROR_VERBOSE */ + + +/*-----------------------------------------------. +| Release the memory associated to this symbol. | +`-----------------------------------------------*/ + +/*ARGSUSED*/ +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +static void +yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) +#else +static void +yydestruct (yymsg, yytype, yyvaluep) + const char *yymsg; + int yytype; + YYSTYPE *yyvaluep; +#endif +{ + YYUSE (yyvaluep); + + if (!yymsg) + yymsg = "Deleting"; + YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); + + switch (yytype) + { + + default: + break; + } +} + +/* Prevent warnings from -Wmissing-prototypes. */ +#ifdef YYPARSE_PARAM +#if defined __STDC__ || defined __cplusplus +int yyparse (void *YYPARSE_PARAM); +#else +int yyparse (); +#endif +#else /* ! YYPARSE_PARAM */ +#if defined __STDC__ || defined __cplusplus +int yyparse (void); +#else +int yyparse (); +#endif +#endif /* ! YYPARSE_PARAM */ + + +/* The lookahead symbol. */ +int yychar; + +/* The semantic value of the lookahead symbol. */ +YYSTYPE yylval; + +/* Number of syntax errors so far. */ +int yynerrs; + + + +/*-------------------------. +| yyparse or yypush_parse. | +`-------------------------*/ + +#ifdef YYPARSE_PARAM +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +int +yyparse (void *YYPARSE_PARAM) +#else +int +yyparse (YYPARSE_PARAM) + void *YYPARSE_PARAM; +#endif +#else /* ! YYPARSE_PARAM */ +#if (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus || defined _MSC_VER) +int +yyparse (void) +#else +int +yyparse () + +#endif +#endif +{ + + + int yystate; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus; + + /* The stacks and their tools: + `yyss': related to states. + `yyvs': related to semantic values. + + Refer to the stacks thru separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* The state stack. */ + yytype_int16 yyssa[YYINITDEPTH]; + yytype_int16 *yyss; + yytype_int16 *yyssp; + + /* The semantic value stack. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs; + YYSTYPE *yyvsp; + + YYSIZE_T yystacksize; + + int yyn; + int yyresult; + /* Lookahead token as an internal (translated) token number. */ + int yytoken; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + +#if YYERROR_VERBOSE + /* Buffer for error messages, and its allocated size. */ + char yymsgbuf[128]; + char *yymsg = yymsgbuf; + YYSIZE_T yymsg_alloc = sizeof yymsgbuf; +#endif + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + yytoken = 0; + yyss = yyssa; + yyvs = yyvsa; + yystacksize = YYINITDEPTH; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + + /* Initialize stack pointers. + Waste one element of value and location stack + so that they stay on the same level as the state stack. + The wasted elements are never initialized. */ + yyssp = yyss; + yyvsp = yyvs; + + goto yysetstate; + +/*------------------------------------------------------------. +| yynewstate -- Push a new state, which is found in yystate. | +`------------------------------------------------------------*/ + yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + yysetstate: + *yyssp = yystate; + + if (yyss + yystacksize - 1 <= yyssp) + { + /* Get the current used size of the three stacks, in elements. */ + YYSIZE_T yysize = yyssp - yyss + 1; + +#ifdef yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + YYSTYPE *yyvs1 = yyvs; + yytype_int16 *yyss1 = yyss; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * sizeof (*yyssp), + &yyvs1, yysize * sizeof (*yyvsp), + &yystacksize); + + yyss = yyss1; + yyvs = yyvs1; + } +#else /* no yyoverflow */ +# ifndef YYSTACK_RELOCATE + goto yyexhaustedlab; +# else + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + goto yyexhaustedlab; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yytype_int16 *yyss1 = yyss; + union yyalloc *yyptr = + (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); + if (! yyptr) + goto yyexhaustedlab; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif +#endif /* no yyoverflow */ + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + + YYDPRINTF ((stderr, "Stack size increased to %lu\n", + (unsigned long int) yystacksize)); + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } + + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yyn == YYPACT_NINF) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token: ")); + yychar = YYLEX; + } + + if (yychar <= YYEOF) + { + yychar = yytoken = YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yyn == 0 || yyn == YYTABLE_NINF) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + + /* Discard the shifted token. */ + yychar = YYEMPTY; + + yystate = yyn; + *++yyvsp = yylval; + + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + +/*-----------------------------. +| yyreduce -- Do a reduction. | +`-----------------------------*/ +yyreduce: + /* yyn is the number of a rule to reduce with. */ + yylen = yyr2[yyn]; + + /* If YYLEN is nonzero, implement the default value of the action: + `$$ = $1'. + + Otherwise, the following line sets YYVAL to garbage. + This behavior is undocumented and Bison + users should not rely upon it. Assigning to YYVAL + unconditionally makes the parser a bit smaller, and it avoids a + GCC warning that YYVAL may be used uninitialized. */ + yyval = yyvsp[1-yylen]; + + + YY_REDUCE_PRINT (yyn); + switch (yyn) + { + case 4: + +/* Line 1455 of yacc.c */ +#line 42 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), NOP, 0); ;} + break; + + case 5: + +/* Line 1455 of yacc.c */ +#line 43 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), STOP, 0); ;} + break; + + case 6: + +/* Line 1455 of yacc.c */ +#line 44 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), LOAD, (yyvsp[(4) - (4)])); ;} + break; + + case 7: + +/* Line 1455 of yacc.c */ +#line 45 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), STORE, (yyvsp[(4) - (4)])); ;} + break; + + case 8: + +/* Line 1455 of yacc.c */ +#line 46 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), BLOAD, (yyvsp[(4) - (4)])); ;} + break; + + case 9: + +/* Line 1455 of yacc.c */ +#line 47 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), BSTORE, (yyvsp[(4) - (4)])); ;} + break; + + case 10: + +/* Line 1455 of yacc.c */ +#line 48 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), PUSH, (yyvsp[(4) - (4)])); ;} + break; + + case 11: + +/* Line 1455 of yacc.c */ +#line 49 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), POP, 0); ;} + break; + + case 12: + +/* Line 1455 of yacc.c */ +#line 50 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), DUP, 0); ;} + break; + + case 13: + +/* Line 1455 of yacc.c */ +#line 51 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), INVERT, 0); ;} + break; + + case 14: + +/* Line 1455 of yacc.c */ +#line 52 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), ADD, 0); ;} + break; + + case 15: + +/* Line 1455 of yacc.c */ +#line 53 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), SUB, 0); ;} + break; + + case 16: + +/* Line 1455 of yacc.c */ +#line 54 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), MULT, 0); ;} + break; + + case 17: + +/* Line 1455 of yacc.c */ +#line 55 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), DIV, 0); ;} + break; + + case 18: + +/* Line 1455 of yacc.c */ +#line 56 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), COMPARE, (yyvsp[(4) - (4)])); ;} + break; + + case 19: + +/* Line 1455 of yacc.c */ +#line 57 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), JUMP, (yyvsp[(4) - (4)])); ;} + break; + + case 20: + +/* Line 1455 of yacc.c */ +#line 58 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), JUMP_YES, (yyvsp[(4) - (4)])); ;} + break; + + case 21: + +/* Line 1455 of yacc.c */ +#line 59 "vmparse.y" + { put_command((yyvsp[(1) - (4)]), JUMP_NO, (yyvsp[(4) - (4)])); ;} + break; + + case 22: + +/* Line 1455 of yacc.c */ +#line 60 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), INPUT, 0); ;} + break; + + case 23: + +/* Line 1455 of yacc.c */ +#line 61 "vmparse.y" + { put_command((yyvsp[(1) - (3)]), PRINT, 0); ;} + break; + + case 24: + +/* Line 1455 of yacc.c */ +#line 62 "vmparse.y" + { set_mem((yyvsp[(2) - (3)]), (yyvsp[(3) - (3)])); ;} + break; + + + +/* Line 1455 of yacc.c */ +#line 1517 "vmparse.tab.c" + default: break; + } + YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); + + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + + *++yyvsp = yyval; + + /* Now `shift' the result of the reduction. Determine what state + that goes to, based on the state we popped back to and the rule + number reduced by. */ + + yyn = yyr1[yyn]; + + yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; + if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) + yystate = yytable[yystate]; + else + yystate = yydefgoto[yyn - YYNTOKENS]; + + goto yynewstate; + + +/*------------------------------------. +| yyerrlab -- here on detecting error | +`------------------------------------*/ +yyerrlab: + /* If not already recovering from an error, report this error. */ + if (!yyerrstatus) + { + ++yynerrs; +#if ! YYERROR_VERBOSE + yyerror (YY_("syntax error")); +#else + { + YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); + if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) + { + YYSIZE_T yyalloc = 2 * yysize; + if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) + yyalloc = YYSTACK_ALLOC_MAXIMUM; + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); + yymsg = (char *) YYSTACK_ALLOC (yyalloc); + if (yymsg) + yymsg_alloc = yyalloc; + else + { + yymsg = yymsgbuf; + yymsg_alloc = sizeof yymsgbuf; + } + } + + if (0 < yysize && yysize <= yymsg_alloc) + { + (void) yysyntax_error (yymsg, yystate, yychar); + yyerror (yymsg); + } + else + { + yyerror (YY_("syntax error")); + if (yysize != 0) + goto yyexhaustedlab; + } + } +#endif + } + + + + if (yyerrstatus == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + if (yychar <= YYEOF) + { + /* Return failure if at end of input. */ + if (yychar == YYEOF) + YYABORT; + } + else + { + yydestruct ("Error: discarding", + yytoken, &yylval); + yychar = YYEMPTY; + } + } + + /* Else will try to reuse lookahead token after shifting the error + token. */ + goto yyerrlab1; + + +/*---------------------------------------------------. +| yyerrorlab -- error raised explicitly by YYERROR. | +`---------------------------------------------------*/ +yyerrorlab: + + /* Pacify compilers like GCC when the user code never invokes + YYERROR and the label yyerrorlab therefore never appears in user + code. */ + if (/*CONSTCOND*/ 0) + goto yyerrorlab; + + /* Do not reclaim the symbols of the rule which action triggered + this YYERROR. */ + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + yystate = *yyssp; + goto yyerrlab1; + + +/*-------------------------------------------------------------. +| yyerrlab1 -- common code for both syntax error and YYERROR. | +`-------------------------------------------------------------*/ +yyerrlab1: + yyerrstatus = 3; /* Each real token shifted decrements this. */ + + for (;;) + { + yyn = yypact[yystate]; + if (yyn != YYPACT_NINF) + { + yyn += YYTERROR; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) + { + yyn = yytable[yyn]; + if (0 < yyn) + break; + } + } + + /* Pop the current state because it cannot handle the error token. */ + if (yyssp == yyss) + YYABORT; + + + yydestruct ("Error: popping", + yystos[yystate], yyvsp); + YYPOPSTACK (1); + yystate = *yyssp; + YY_STACK_PRINT (yyss, yyssp); + } + + *++yyvsp = yylval; + + + /* Shift the error token. */ + YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); + + yystate = yyn; + goto yynewstate; + + +/*-------------------------------------. +| yyacceptlab -- YYACCEPT comes here. | +`-------------------------------------*/ +yyacceptlab: + yyresult = 0; + goto yyreturn; + +/*-----------------------------------. +| yyabortlab -- YYABORT comes here. | +`-----------------------------------*/ +yyabortlab: + yyresult = 1; + goto yyreturn; + +#if !defined(yyoverflow) || YYERROR_VERBOSE +/*-------------------------------------------------. +| yyexhaustedlab -- memory exhaustion comes here. | +`-------------------------------------------------*/ +yyexhaustedlab: + yyerror (YY_("memory exhausted")); + yyresult = 2; + /* Fall through. */ +#endif + +yyreturn: + if (yychar != YYEMPTY) + yydestruct ("Cleanup: discarding lookahead", + yytoken, &yylval); + /* Do not reclaim the symbols of the rule which action triggered + this YYABORT or YYACCEPT. */ + YYPOPSTACK (yylen); + YY_STACK_PRINT (yyss, yyssp); + while (yyssp != yyss) + { + yydestruct ("Cleanup: popping", + yystos[*yyssp], yyvsp); + YYPOPSTACK (1); + } +#ifndef yyoverflow + if (yyss != yyssa) + YYSTACK_FREE (yyss); +#endif +#if YYERROR_VERBOSE + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); +#endif + /* Make sure YYID is used. */ + return YYID (yyresult); +} + + + +/* Line 1675 of yacc.c */ +#line 64 "vmparse.y" + + +void yyerror(char const *str) +{ + printf("Error: %s\n", str); +} + + diff --git a/lab4/vm/vm/vmparse.tab.h b/lab4/vm/vm/vmparse.tab.h new file mode 100644 index 0000000..79a4da0 --- /dev/null +++ b/lab4/vm/vm/vmparse.tab.h @@ -0,0 +1,79 @@ + +/* A Bison parser, made by GNU Bison 2.4.1. */ + +/* Skeleton interface for Bison's Yacc-like parsers in C + + Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 + Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + + +/* Tokens. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + /* Put the tokens into the symbol table, so that GDB and other debuggers + know about them. */ + enum yytokentype { + T_INT = 258, + T_SET = 259, + T_NOP = 260, + T_STOP = 261, + T_LOAD = 262, + T_STORE = 263, + T_BLOAD = 264, + T_BSTORE = 265, + T_PUSH = 266, + T_POP = 267, + T_DUP = 268, + T_INVERT = 269, + T_ADD = 270, + T_SUB = 271, + T_MULT = 272, + T_DIV = 273, + T_COMPARE = 274, + T_JUMP = 275, + T_JUMP_YES = 276, + T_JUMP_NO = 277, + T_INPUT = 278, + T_PRINT = 279, + T_COLON = 280 + }; +#endif + + + +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED +typedef int YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define yystype YYSTYPE /* obsolescent; will be withdrawn */ +# define YYSTYPE_IS_DECLARED 1 +#endif + +extern YYSTYPE yylval; + + diff --git a/lab4/vm/vm/vmparse.y b/lab4/vm/vm/vmparse.y new file mode 100644 index 0000000..8d1fa79 --- /dev/null +++ b/lab4/vm/vm/vmparse.y @@ -0,0 +1,70 @@ +%{ +#include "vm.h" +#include +#include + +#define YYSTYPE int + +int yylex(); +void yyerror(char const *); +%} + +%token T_INT +%token T_SET +%token T_NOP +%token T_STOP +%token T_LOAD +%token T_STORE +%token T_BLOAD +%token T_BSTORE +%token T_PUSH +%token T_POP +%token T_DUP +%token T_INVERT +%token T_ADD +%token T_SUB +%token T_MULT +%token T_DIV +%token T_COMPARE +%token T_JUMP +%token T_JUMP_YES +%token T_JUMP_NO +%token T_INPUT +%token T_PRINT +%token T_COLON + +%% + +program : line program + | line + ; + +line : T_INT T_COLON T_NOP { put_command($1, NOP, 0); } + | T_INT T_COLON T_STOP { put_command($1, STOP, 0); } + | T_INT T_COLON T_LOAD T_INT { put_command($1, LOAD, $4); } + | T_INT T_COLON T_STORE T_INT { put_command($1, STORE, $4); } + | T_INT T_COLON T_BLOAD T_INT { put_command($1, BLOAD, $4); } + | T_INT T_COLON T_BSTORE T_INT { put_command($1, BSTORE, $4); } + | T_INT T_COLON T_PUSH T_INT { put_command($1, PUSH, $4); } + | T_INT T_COLON T_POP { put_command($1, POP, 0); } + | T_INT T_COLON T_DUP { put_command($1, DUP, 0); } + | T_INT T_COLON T_INVERT { put_command($1, INVERT, 0); } + | T_INT T_COLON T_ADD { put_command($1, ADD, 0); } + | T_INT T_COLON T_SUB { put_command($1, SUB, 0); } + | T_INT T_COLON T_MULT { put_command($1, MULT, 0); } + | T_INT T_COLON T_DIV { put_command($1, DIV, 0); } + | T_INT T_COLON T_COMPARE T_INT { put_command($1, COMPARE, $4); } + | T_INT T_COLON T_JUMP T_INT { put_command($1, JUMP, $4); } + | T_INT T_COLON T_JUMP_YES T_INT { put_command($1, JUMP_YES, $4); } + | T_INT T_COLON T_JUMP_NO T_INT { put_command($1, JUMP_NO, $4); } + | T_INT T_COLON T_INPUT { put_command($1, INPUT, 0); } + | T_INT T_COLON T_PRINT { put_command($1, PRINT, 0); } + | T_SET T_INT T_INT { set_mem($2, $3); } + ; +%% + +void yyerror(char const *str) +{ + printf("Error: %s\n", str); +} +