aboutsummaryrefslogtreecommitdiff
path: root/vendor
diff options
context:
space:
mode:
Diffstat (limited to 'vendor')
-rw-r--r--vendor/cmilan/doc/Makefile10
-rw-r--r--vendor/cmilan/src/Makefile23
-rw-r--r--vendor/cmilan/src/codegen.cpp153
-rw-r--r--vendor/cmilan/src/codegen.h106
-rw-r--r--vendor/cmilan/src/main.cpp32
-rw-r--r--vendor/cmilan/src/parser.cpp554
-rw-r--r--vendor/cmilan/src/parser.h149
-rw-r--r--vendor/cmilan/src/scanner.cpp242
-rw-r--r--vendor/cmilan/src/scanner.h175
-rw-r--r--vendor/cmilan/test/add.mil7
-rw-r--r--vendor/cmilan/test/comment.mil14
-rw-r--r--vendor/cmilan/test/factorial.mil10
-rw-r--r--vendor/cmilan/test/fib.mil17
-rw-r--r--vendor/cmilan/test/gcd.mil17
-rw-r--r--vendor/cmilan/test/if.mil7
-rw-r--r--vendor/cmilan/test/invalid.mil5
-rw-r--r--vendor/cmilan/test/invert.mil14
-rw-r--r--vendor/cmilan/test/loop.mil17
-rw-r--r--vendor/cmilan/test/power.mil14
-rw-r--r--vendor/cmilan/test/read2.mil8
-rw-r--r--vendor/cmilan/test/sum.mil9
-rw-r--r--vendor/vm/doc/changelog.txt10
-rw-r--r--vendor/vm/doc/vm.txt230
-rw-r--r--vendor/vm/vm/Makefile15
-rw-r--r--vendor/vm/vm/lex.yy.c1964
-rw-r--r--vendor/vm/vm/main.c47
-rw-r--r--vendor/vm/vm/test/bop1.ms6
-rw-r--r--vendor/vm/vm/test/bop2.ms8
-rw-r--r--vendor/vm/vm/test/fib.ms37
-rw-r--r--vendor/vm/vm/test/fib2.ms21
-rw-r--r--vendor/vm/vm/vm.c458
-rw-r--r--vendor/vm/vm/vm.h94
-rw-r--r--vendor/vm/vm/vmlex.l56
-rw-r--r--vendor/vm/vm/vmparse.y83
34 files changed, 4612 insertions, 0 deletions
diff --git a/vendor/cmilan/doc/Makefile b/vendor/cmilan/doc/Makefile
new file mode 100644
index 0000000..a4b4448
--- /dev/null
+++ b/vendor/cmilan/doc/Makefile
@@ -0,0 +1,10 @@
1cmilan.pdf: cmilan.tex
2 pdflatex cmilan.tex
3 pdflatex cmilan.tex
4 pdflatex cmilan.tex
5
6clean:
7 rm -f cmilan.aux
8 rm -f cmilan.toc
9 rm -f cmilan.log
10
diff --git a/vendor/cmilan/src/Makefile b/vendor/cmilan/src/Makefile
new file mode 100644
index 0000000..9e753a0
--- /dev/null
+++ b/vendor/cmilan/src/Makefile
@@ -0,0 +1,23 @@
1CFLAGS = -Wall -W -Werror -O2 -ggdb3 -std=c++20
2LDFLAGS =
3
4HEADERS = scanner.h \
5 parser.h \
6 codegen.h
7
8OBJS = main.o \
9 codegen.o \
10 scanner.o \
11 parser.o \
12
13EXE = cmilan
14
15$(EXE): $(OBJS) $(HEADERS)
16 $(CXX) $(LDFLAGS) -o $@ $(OBJS)
17
18.cpp.o:
19 $(CXX) $(CFLAGS) -c $< -o $@
20
21clean:
22 -@rm -f $(EXE) $(OBJS)
23
diff --git a/vendor/cmilan/src/codegen.cpp b/vendor/cmilan/src/codegen.cpp
new file mode 100644
index 0000000..4f11a97
--- /dev/null
+++ b/vendor/cmilan/src/codegen.cpp
@@ -0,0 +1,153 @@
1#include "codegen.h"
2
3void Command::print(int address, ostream& os)
4{
5 os << address << ":\t";
6 switch(instruction_) {
7 case NOP:
8 os << "NOP";
9 break;
10
11 case STOP:
12 os << "STOP";
13 break;
14
15 case LOAD:
16 os << "LOAD\t" << arg_;
17 break;
18
19 case STORE:
20 os << "STORE\t" << arg_;
21 break;
22
23 case BLOAD:
24 os << "BLOAD\t" << arg_;
25 break;
26
27 case BSTORE:
28 os << "BSTORE\t" << arg_;
29 break;
30
31 case PUSH:
32 os << "PUSH\t" << arg_;
33 break;
34
35 case POP:
36 os << "POP";
37 break;
38
39 case DUP:
40 os << "DUP";
41 break;
42
43 case ADD:
44 os << "ADD";
45 break;
46
47 case SUB:
48 os << "SUB";
49 break;
50
51 case MULT:
52 os << "MULT";
53 break;
54
55 case DIV:
56 os << "DIV";
57 break;
58
59 case INVERT:
60 os << "INVERT";
61 break;
62
63 case COMPARE:
64 os << "COMPARE\t" << arg_;
65 break;
66
67 case JUMP:
68 os << "JUMP\t" << arg_;
69 break;
70
71 case JUMP_YES:
72 os << "JUMP_YES\t" << arg_;
73 break;
74
75 case JUMP_NO:
76 os << "JUMP_NO\t" << arg_;
77 break;
78
79 case INPUT:
80 os << "INPUT";
81 break;
82
83 case PRINT:
84 os << "PRINT";
85 break;
86
87 case CALL:
88 os << "CALL\t" << arg_;
89 break;
90
91 case RETURN:
92 os << "RETURN\t" << arg_;
93 break;
94
95 case LOADB:
96 os << "LOADB\t" << arg_;
97 break;
98
99 case STOREB:
100 os << "STOREB\t" << arg_;
101 break;
102
103 case SHIFT:
104 os << "SHIFT\t" << arg_;
105 break;
106
107 default:
108 os << "INVALID\t" << arg_;
109 break;
110 }
111
112 os << endl;
113}
114
115void CodeGen::emit(Instruction instruction)
116{
117 commandBuffer_.push_back(Command(instruction));
118}
119
120void CodeGen::emit(Instruction instruction, int arg)
121{
122 commandBuffer_.push_back(Command(instruction, arg));
123}
124
125void CodeGen::emitAt(int address, Instruction instruction)
126{
127 commandBuffer_[address] = Command(instruction);
128}
129
130void CodeGen::emitAt(int address, Instruction instruction, int arg)
131{
132 commandBuffer_[address] = Command(instruction, arg);
133}
134
135int CodeGen::getCurrentAddress()
136{
137 return commandBuffer_.size();
138}
139
140int CodeGen::reserve()
141{
142 emit(NOP);
143 return commandBuffer_.size() - 1;
144}
145
146void CodeGen::flush()
147{
148 int count = commandBuffer_.size();
149 for(int address = 0; address < count; ++address) {
150 commandBuffer_[address].print(address, output_);
151 }
152 output_.flush();
153}
diff --git a/vendor/cmilan/src/codegen.h b/vendor/cmilan/src/codegen.h
new file mode 100644
index 0000000..c0c01ee
--- /dev/null
+++ b/vendor/cmilan/src/codegen.h
@@ -0,0 +1,106 @@
1#ifndef CMILAN_CODEGEN_H
2#define CMILAN_CODEGEN_H
3
4#include <vector>
5#include <iostream>
6
7using namespace std;
8
9// Инструкции виртуальной машины Милана
10
11enum Instruction
12{
13 NOP, // отсутствие операции
14 STOP, // остановка машины, завершение работы программы
15 LOAD, // LOAD addr - загрузка слова данных в стек из памяти по адресу addr
16 STORE, // STORE addr - запись слова данных с вершины стека в память по адресу addr
17 BLOAD, // BLOAD addr - загрузка слова данных в стек из памяти по адресу addr + значение на вершине стека
18 BSTORE, // BSTORE addr - запись слова данных по адресу addr + значение на вершине стека
19 PUSH, // PUSH n - загрузка в стек константы n
20 POP, // удаление слова с вершины стека
21 DUP, // копирование слова на вершине стека
22 ADD, // сложение двух слов на вершине стека и запись результата вместо них
23 SUB, // вычитание двух слов на вершине стека и запись результата вместо них
24 MULT, // умножение двух слов на вершине стека и запись результата вместо них
25 DIV, // деление двух слов на вершине стека и запись результата вместо них
26 INVERT, // изменение знака слова на вершине стека
27 COMPARE, // COMPARE cmp - сравнение двух слов на вершине стека с помощью операции сравнения с кодом cmp
28 JUMP, // JUMP addr - безусловный переход по адресу addr
29 JUMP_YES, // JUMP_YES addr - переход по адресу addr, если на вершине стека значение 1
30 JUMP_NO, // JUMP_NO addr - переход по адресу addr, если на вершине стека значение 0
31 INPUT, // чтение целого числа со стандартного ввода и загрузка его в стек
32 PRINT, // печать на стандартный вывод числа с вершины стека
33
34 CALL,
35 RETURN,
36 LOADB,
37 STOREB,
38 SHIFT,
39};
40
41// Класс Command представляет машинные инструкции.
42
43class Command
44{
45public:
46 // Конструктор для инструкций без аргументов
47 Command(Instruction instruction)
48 : instruction_(instruction), arg_(0)
49 {}
50
51 // Конструктор для инструкций с одним аргументом
52 Command(Instruction instruction, int arg)
53 : instruction_(instruction), arg_(arg)
54 {}
55
56 // Печать инструкции
57 // int address - адрес инструкции
58 // ostream& os - поток вывода, куда будет напечатана инструкция
59 void print(int address, ostream& os);
60
61private:
62 Instruction instruction_; // Код инструкции
63 int arg_; // Аргумент инструкции
64};
65
66// Кодогенератор.
67// Назначение кодогенератора:
68// - Формировать программу для виртуальной машины Милана
69// - Отслеживать адрес последней инструкции
70// - Буферизовать программу и печатать ее в указанный поток вывода
71
72class CodeGen
73{
74public:
75 explicit CodeGen(ostream& output)
76 : output_(output)
77 {
78 }
79
80 // Добавление инструкции без аргументов в конец программы
81 void emit(Instruction instruction);
82
83 // Добавление инструкции с одним аргументом в конец программы
84 void emit(Instruction instruction, int arg);
85
86 // Запись инструкции без аргументов по указанному адресу
87 void emitAt(int address, Instruction instruction);
88
89 // Запись инструкции с одним аргументом по указанному адресу
90 void emitAt(int address, Instruction instruction, int arg);
91
92 // Получение адреса, непосредственно следующего за последней инструкцией в программе
93 int getCurrentAddress();
94
95 // Формирование "пустой" инструкции (NOP) и возврат ее адреса
96 int reserve();
97
98 // Запись последовательности инструкций в выходной поток
99 void flush();
100
101private:
102 ostream& output_; // Выходной поток
103 vector<Command> commandBuffer_; // Буфер инструкций
104};
105
106#endif
diff --git a/vendor/cmilan/src/main.cpp b/vendor/cmilan/src/main.cpp
new file mode 100644
index 0000000..9de9803
--- /dev/null
+++ b/vendor/cmilan/src/main.cpp
@@ -0,0 +1,32 @@
1#include "parser.h"
2#include <iostream>
3#include <cstdlib>
4
5using namespace std;
6
7void printHelp()
8{
9 cout << "Usage: cmilan input_file" << endl;
10}
11
12int main(int argc, char** argv)
13{
14 if(argc < 2) {
15 printHelp();
16 return EXIT_FAILURE;
17 }
18
19 ifstream input;
20 input.open(argv[1]);
21
22 if(input) {
23 Parser p(argv[1], input);
24 p.parse();
25 return EXIT_SUCCESS;
26 }
27 else {
28 cerr << "File '" << argv[1] << "' not found" << endl;
29 return EXIT_FAILURE;
30 }
31}
32
diff --git a/vendor/cmilan/src/parser.cpp b/vendor/cmilan/src/parser.cpp
new file mode 100644
index 0000000..7623f7c
--- /dev/null
+++ b/vendor/cmilan/src/parser.cpp
@@ -0,0 +1,554 @@
1#include "parser.h"
2#include <sstream>
3
4// Выполняем синтаксический разбор блока program. Если во время
5// разбора не обнаруживаем никаких ошибок, то выводим
6// последовательность команд стек-машины
7void Parser::parse()
8{
9 functionDeclarations();
10 program();
11 functionDefinitions();
12
13 for (auto call : calls_)
14 codegen_->emitAt(call.first, CALL, functions_[call.second].address);
15 for (auto jump : jumps_)
16 codegen_->emitAt(jump.first, JUMP, functions_[jump.second].address);
17
18 if (!error_) {
19 codegen_->flush();
20 }
21}
22
23void Parser::functionDeclarations()
24{
25 while (see(T_FUNC))
26 functionDeclaration();
27}
28
29void Parser::functionDeclaration()
30{
31 struct FuncInfo funcInfo;
32
33 mustBe(T_FUNC);
34 if(!see(T_IDENTIFIER)) {
35 reportError("function identifier expected.");
36 return;
37 }
38 const string &funcName = scanner_->getStringValue();
39 next();
40
41 mustBe(T_LPAREN);
42 if (!see(T_NUMBER)) {
43 reportError("argument count expected.");
44 return;
45 }
46 int argumentCount = scanner_->getIntValue();
47 next();
48 mustBe(T_RPAREN);
49
50 struct FuncDesc funcDesc = { funcName, argumentCount };
51 if (functions_.find(funcDesc) !=
52 functions_.end()) {
53 reportError("function already declared.");
54 return;
55 }
56
57 if (match(T_RETURNS)) {
58 funcInfo.returns = true;
59 }
60
61 mustBe(T_SEMICOLON);
62 functions_[funcDesc] = funcInfo;
63}
64
65void Parser::functionDefinitions()
66{
67 while (see(T_FUNC))
68 functionDefinition();
69}
70
71void Parser::functionDefinition()
72{
73 localVariables_.clear();
74
75 mustBe(T_FUNC);
76 if(!see(T_IDENTIFIER)) {
77 reportError("function identifier expected.");
78 return;
79 }
80 const string &funcName = scanner_->getStringValue();
81 next();
82
83 mustBe(T_LPAREN);
84 argumentList();
85 mustBe(T_RPAREN);
86 int argCount = localVariables_.size();
87 struct FuncDesc funcDesc = { funcName, argCount };
88
89 struct FuncInfo &funcInfo = findFunction(funcDesc);
90 if (funcInfo.address) {
91 reportError("function already defined.");
92 return;
93 }
94
95 currentFuncDesc_ = &funcDesc;
96 funcInfo.address = codegen_->getCurrentAddress();
97
98 bool returns = false;
99 if (match(T_RETURNS))
100 returns = true;
101 if (returns != funcInfo.returns) {
102 reportError("returns in function definition doesn't match it's declaration.");
103 return;
104 }
105
106 mustBe(T_BEGIN);
107 if (see(T_LOCALS))
108 localVariableList();
109 if (localVariables_.size() - argCount > 0)
110 codegen_->emit(SHIFT, localVariables_.size() - argCount);
111 bool returned = statementList();
112 mustBe(T_END);
113 if (returns && !returned) {
114 reportError("function which returns didn't return.");
115 return;
116 }
117
118 if (!returned)
119 codegen_->emit(RETURN, argCount);
120}
121
122void Parser::argumentList()
123{
124 int count = 0;
125 while (see(T_IDENTIFIER)) {
126 const string &variableName = scanner_->getStringValue();
127 if (localVariables_.find(variableName) != localVariables_.end()) {
128 reportError("argument name already used.");
129 return;
130 }
131 localVariables_[variableName] = count++;
132 next();
133 }
134
135 for (auto &var : localVariables_)
136 var.second -= 2 + count;
137}
138
139void Parser::localVariableList()
140{
141 mustBe(T_LOCALS);
142 int address = 0;
143 while (!see(T_SEMICOLON)) {
144 if(!see(T_IDENTIFIER)) {
145 reportError("variable identifier expected.");
146 return;
147 }
148 const string &variableName = scanner_->getStringValue();
149 if (localVariables_.find(variableName) != localVariables_.end()) {
150 reportError("local variable name already used.");
151 return;
152 }
153 localVariables_[variableName] = address++;
154 next();
155 }
156 next();
157}
158
159void Parser::program()
160{
161 mustBe(T_BEGIN);
162 if (see(T_LOCALS))
163 localVariableList();
164 if (localVariables_.size() > 0)
165 codegen_->emit(SHIFT, localVariables_.size());
166 bool returned = statementList();
167 mustBe(T_END);
168 if (!returned)
169 codegen_->emit(STOP);
170}
171
172bool Parser::statementList()
173{
174 // Если список операторов пуст, очередной лексемой будет одна из
175 // возможных "закрывающих скобок": END, OD, ELSE, FI. В этом случае
176 // результатом разбора будет пустой блок (его список операторов
177 // равен null). Если очередная лексема не входит в этот список, то
178 // ее мы считаем началом оператора и вызываем метод statement.
179 // Признаком последнего оператора является отсутствие после
180 // оператора точки с запятой.
181 if(see(T_END) || see(T_OD) || see(T_ELSE) || see(T_FI)) {
182 return false;
183 }
184
185 bool more = true;
186 bool returned = false;
187 while(more /* && !returned -- only use with codegen blocking */) {
188 returned = statement() || returned;
189 more = match(T_SEMICOLON);
190 }
191 return returned;
192}
193
194bool Parser::statement()
195{
196 // Если встречаем переменную, то запоминаем ее адрес или добавляем
197 // новую если не встретили. Следующей лексемой должно быть
198 // присваивание. Затем идет блок expression, который возвращает
199 // значение на вершину стека. Записываем это значение по адресу
200 // нашей переменной
201 if(see(T_IDENTIFIER)) {
202 const string &identifier = scanner_->getStringValue();
203 next();
204 if (see(T_ASSIGN)) {
205 next();
206 pair<bool, int> var = findOrAddVariable(identifier);
207 expression();
208 codegen_->emit(var.first ? STOREB : STORE, var.second);
209 return false;
210 } else if (see(T_LPAREN)) {
211 next();
212 int argCount = 0;
213 bool more = !see(T_RPAREN);
214 while (more) {
215 expression();
216 more = match(T_COMMA);
217 }
218 mustBe(T_RPAREN);
219 struct FuncDesc funcDesc = { identifier, argCount };
220 const struct FuncInfo &funcInfo = findFunction(funcDesc);
221
222 calls_[codegen_->reserve()] = funcDesc;
223 if (funcInfo.returns)
224 codegen_->emit(SHIFT, -1);
225 return false;
226 }
227 }
228 // Если встретили IF, то затем должно следовать условие. На вершине
229 // стека лежит 1 или 0 в зависимости от выполнения условия. Затем
230 // зарезервируем место для условного перехода JUMP_NO к блоку ELSE
231 // (переход в случае ложного условия). Адрес перехода станет
232 // известным только после того, как будет сгенерирован код для блока
233 // THEN.
234 else if(match(T_IF)) {
235 relation();
236
237 int jumpNoAddress = codegen_->reserve();
238
239 mustBe(T_THEN);
240 bool returned = statementList();
241 if(match(T_ELSE)) {
242 // Если есть блок ELSE, то чтобы не выполнять его в случае
243 // выполнения THEN, зарезервируем место для команды JUMP в конец
244 // этого блока
245 int jumpAddress = codegen_->reserve();
246 // Заполним зарезервированное место после проверки условия
247 // инструкцией перехода в начало блока ELSE.
248 codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress());
249 returned = statementList() && returned;
250 // Заполним второй адрес инструкцией перехода в конец условного
251 // блока ELSE.
252 codegen_->emitAt(jumpAddress, JUMP, codegen_->getCurrentAddress());
253 mustBe(T_FI);
254 return returned;
255 } else {
256 // Если блок ELSE отсутствует, то в зарезервированный адрес
257 // после проверки условия будет записана инструкция условного
258 // перехода в конец оператора IF...THEN
259 codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress());
260 mustBe(T_FI);
261 return false;
262 }
263 } else if(match(T_WHILE)) {
264 // запоминаем адрес начала проверки условия.
265 int conditionAddress = codegen_->getCurrentAddress();
266 relation();
267 // резервируем место под инструкцию условного перехода для выхода
268 // из цикла.
269 int jumpNoAddress = codegen_->reserve();
270 mustBe(T_DO);
271 statementList();
272 mustBe(T_OD);
273 // переходим по адресу проверки условия
274 codegen_->emit(JUMP, conditionAddress);
275 // заполняем зарезервированный адрес инструкцией условного
276 // перехода на следующий за циклом оператор.
277 codegen_->emitAt(jumpNoAddress, JUMP_NO, codegen_->getCurrentAddress());
278 return false;
279 } else if(match(T_WRITE)) {
280 mustBe(T_LPAREN);
281 expression();
282 mustBe(T_RPAREN);
283 codegen_->emit(PRINT);
284 return false;
285 } else if(match(T_RETURN)) {
286 if (currentFuncDesc_) {
287 const struct FuncInfo &funcInfo = findFunction(*currentFuncDesc_);
288 if (funcInfo.returns) {
289 if (see(T_IDENTIFIER)) {
290 const string &identifier = scanner_->getStringValue();
291 next();
292 if (match(T_LPAREN)) {
293 int argCount = 0;
294 bool more = !see(T_RPAREN);
295 while (more) {
296 expression();
297 argCount += 1;
298 more = match(T_COMMA);
299 }
300 mustBe(T_RPAREN);
301
302 struct FuncDesc funcDesc = { identifier, argCount };
303 const struct FuncInfo &funcInfo = findFunction(funcDesc);
304 if (!funcInfo.returns) {
305 reportError("function call which doesn't return used in an return statement which has to return.");
306 return false;
307 }
308
309 if (argCount == currentFuncDesc_->argumentCount) {
310 for (int i = 0; i < argCount; ++i)
311 codegen_->emit(STOREB, -3 - i);
312 jumps_[codegen_->reserve()] = funcDesc;
313 } else {
314 calls_[codegen_->reserve()] = funcDesc;
315 codegen_->emit(STOREB, -3 - ((currentFuncDesc_->argumentCount ?: 1) - 1));
316 codegen_->emit(RETURN, (currentFuncDesc_->argumentCount ?: 1) - 1);
317 }
318 } else {
319 pair<bool, int> var = findOrAddVariable(identifier);
320 codegen_->emit(var.first ? LOADB : LOAD, var.second);
321 codegen_->emit(STOREB, -3 - ((currentFuncDesc_->argumentCount ?: 1) - 1));
322 codegen_->emit(RETURN, (currentFuncDesc_->argumentCount ?: 1) - 1);
323 }
324 } else {
325 expression();
326 codegen_->emit(STOREB, -3 - ((currentFuncDesc_->argumentCount ?: 1) - 1));
327 codegen_->emit(RETURN, (currentFuncDesc_->argumentCount ?: 1) - 1);
328 }
329 } else {
330 if (match(T_LPAREN)) mustBe(T_RPAREN);
331 codegen_->emit(RETURN, currentFuncDesc_->argumentCount);
332 }
333 } else {
334 if (match(T_LPAREN)) mustBe(T_RPAREN);
335 codegen_->emit(STOP);
336 }
337
338 return true;
339 }
340
341 reportError("statement expected.");
342 return false;
343}
344
345void Parser::expression()
346{
347
348 /*
349 Арифметическое выражение описывается следующими правилами:
350 <expression> -> <term> | <term> + <term> | <term> - <term> При
351 разборе сначала смотрим первый терм, затем анализируем очередной
352 символ. Если это '+' или '-', удаляем его из потока и разбираем
353 очередное слагаемое (вычитаемое). Повторяем проверку и разбор
354 очередного терма, пока не встретим за термом символ, отличный от
355 '+' и '-'
356 */
357
358 term();
359 while(see(T_ADDOP)) {
360 Arithmetic op = scanner_->getArithmeticValue();
361 next();
362 term();
363
364 if(op == A_PLUS) {
365 codegen_->emit(ADD);
366 }
367 else {
368 codegen_->emit(SUB);
369 }
370 }
371}
372
373void Parser::term()
374{
375 /*
376 Терм описывается следующими правилами: <expression> -> <factor>
377 | <factor> + <factor> | <factor> - <factor> При разборе сначала
378 смотрим первый множитель, затем анализируем очередной
379 символ. Если это '*' или '/', удаляем его из потока и разбираем
380 очередное слагаемое (вычитаемое). Повторяем проверку и разбор
381 очередного множителя, пока не встретим за ним символ, отличный
382 от '*' и '/'
383 */
384 factor();
385 while(see(T_MULOP)) {
386 Arithmetic op = scanner_->getArithmeticValue();
387 next();
388 factor();
389
390 if(op == A_MULTIPLY) {
391 codegen_->emit(MULT);
392 }
393 else {
394 codegen_->emit(DIV);
395 }
396 }
397}
398
399void Parser::factor()
400{
401 /*
402 Множитель описывается следующими правилами:
403 <factor> -> number | identifier | identifier (<expressions>) | -<factor> | (<expression>) | READ
404 */
405 if(see(T_NUMBER)) {
406 int value = scanner_->getIntValue();
407 next();
408 codegen_->emit(PUSH, value);
409 // Если встретили число, то преобразуем его в целое и записываем
410 // на вершину стека
411 }
412 else if(see(T_IDENTIFIER)) {
413 const string &identifier = scanner_->getStringValue();
414 next();
415 if (see(T_LPAREN)) {
416 next();
417 int argCount = 0;
418 bool more = !see(T_RPAREN);
419 while (more) {
420 expression();
421 argCount += 1;
422 more = match(T_COMMA);
423 }
424 mustBe(T_RPAREN);
425
426 struct FuncDesc funcDesc = { identifier, argCount };
427 const struct FuncInfo &funcInfo = findFunction(funcDesc);
428 if (!funcInfo.returns) {
429 reportError("function which doesn't return used in an expression.");
430 return;
431 }
432
433 calls_[codegen_->reserve()] = funcDesc;
434 } else {
435 pair<bool, int> var = findOrAddVariable(identifier);
436 codegen_->emit(var.first ? LOADB : LOAD, var.second);
437 // Если встретили переменную, то выгружаем значение, лежащее по ее
438 // адресу, на вершину стека
439 }
440 }
441 else if(see(T_ADDOP) && scanner_->getArithmeticValue() == A_MINUS) {
442 next();
443 factor();
444 codegen_->emit(INVERT);
445 // Если встретили знак "-", и за ним <factor> то инвертируем
446 // значение, лежащее на вершине стека
447 }
448 else if(match(T_LPAREN)) {
449 expression();
450 mustBe(T_RPAREN);
451 // Если встретили открывающую скобку, тогда следом может идти
452 // любое арифметическое выражение и обязательно закрывающая
453 // скобка.
454 }
455 else if(match(T_READ)) {
456 codegen_->emit(INPUT);
457 // Если встретили зарезервированное слово READ, то записываем на
458 // вершину стека идет запись со стандартного ввода
459 }
460 else {
461 reportError("expression expected.");
462 }
463}
464
465void Parser::relation()
466{
467 // Условие сравнивает два выражения по какому-либо из знаков. Каждый
468 // знак имеет свой номер. В зависимости от результата сравнения на
469 // вершине стека окажется 0 или 1.
470 expression();
471 if(see(T_CMP)) {
472 Cmp cmp = scanner_->getCmpValue();
473 next();
474 expression();
475 switch(cmp) {
476 //для знака "=" - номер 0
477 case C_EQ:
478 codegen_->emit(COMPARE, 0);
479 break;
480 //для знака "!=" - номер 1
481 case C_NE:
482 codegen_->emit(COMPARE, 1);
483 break;
484 //для знака "<" - номер 2
485 case C_LT:
486 codegen_->emit(COMPARE, 2);
487 break;
488 //для знака ">" - номер 3
489 case C_GT:
490 codegen_->emit(COMPARE, 3);
491 break;
492 //для знака "<=" - номер 4
493 case C_LE:
494 codegen_->emit(COMPARE, 4);
495 break;
496 //для знака ">=" - номер 5
497 case C_GE:
498 codegen_->emit(COMPARE, 5);
499 break;
500 };
501 }
502 else {
503 reportError("comparison operator expected.");
504 }
505}
506
507struct Parser::FuncInfo &Parser::findFunction(const struct FuncDesc &funcDesc)
508{
509 FuncTable::iterator it = functions_.find(funcDesc);
510 if(it == functions_.end())
511 reportError("function not found.");
512
513 return it->second;
514}
515
516pair<bool, int> Parser::findOrAddVariable(const string& var)
517{
518 VarTable::iterator it = localVariables_.find(var);
519 if(it != localVariables_.end())
520 return make_pair(true, it->second);
521
522 it = globalVariables_.find(var);
523 if(it != globalVariables_.end())
524 return make_pair(false, it->second);
525
526 globalVariables_[var] = lastGlobalVar_;
527 return make_pair(false, lastGlobalVar_++);
528}
529
530void Parser::mustBe(Token t)
531{
532 if(!match(t)) {
533 error_ = true;
534
535 // Подготовим сообщение об ошибке
536 std::ostringstream msg;
537 msg << tokenToString(scanner_->token()) << " found while " << tokenToString(t) << " expected.";
538 reportError(msg.str());
539
540 // Попытка восстановления после ошибки.
541 recover(t);
542 }
543}
544
545void Parser::recover(Token t)
546{
547 while(!see(t) && !see(T_EOF)) {
548 next();
549 }
550
551 if(see(t)) {
552 next();
553 }
554}
diff --git a/vendor/cmilan/src/parser.h b/vendor/cmilan/src/parser.h
new file mode 100644
index 0000000..86f5c3f
--- /dev/null
+++ b/vendor/cmilan/src/parser.h
@@ -0,0 +1,149 @@
1#ifndef CMILAN_PARSER_H
2#define CMILAN_PARSER_H
3
4#include "scanner.h"
5#include "codegen.h"
6#include <iostream>
7#include <sstream>
8#include <string>
9#include <map>
10
11using namespace std;
12
13/* Синтаксический анализатор.
14 *
15 * Задачи:
16 * - проверка корректности программы,
17 * - генерация кода для виртуальной машины в процессе анализа,
18 * - простейшее восстановление после ошибок.
19 *
20 * Синтаксический анализатор языка Милан.
21 *
22 * Парсер с помощью переданного ему при инициализации лексического анализатора
23 * читает по одной лексеме и на основе грамматики Милана генерирует код для
24 * стековой виртуальной машины. Синтаксический анализ выполняется методом
25 * рекурсивного спуска.
26 *
27 * При обнаружении ошибки парсер печатает сообщение и продолжает анализ со
28 * следующего оператора, чтобы в процессе разбора найти как можно больше ошибок.
29 * Поскольку стратегия восстановления после ошибки очень проста, возможна печать
30 * сообщений о несуществующих ("наведенных") ошибках или пропуск некоторых
31 * ошибок без печати сообщений. Если в процессе разбора была найдена хотя бы
32 * одна ошибка, код для виртуальной машины не печатается.*/
33
34class Parser
35{
36public:
37 // Конструктор
38 // const string& fileName - имя файла с программой для анализа
39 //
40 // Конструктор создает экземпляры лексического анализатора и генератора.
41
42 Parser(const string& fileName, istream& input)
43 : output_(cout), error_(false), recovered_(true), lastGlobalVar_(0)
44 {
45 scanner_ = new Scanner(fileName, input);
46 codegen_ = new CodeGen(output_);
47 next();
48 }
49
50 ~Parser()
51 {
52 delete codegen_;
53 delete scanner_;
54 }
55
56 void parse(); //проводим синтаксический разбор
57
58private:
59 struct FuncInfo {
60 int address = 0;
61 bool returns = false;
62 };
63 struct FuncDesc {
64 string name;
65 int argumentCount;
66 bool operator<(const FuncDesc& o) const { return name < o.name ||
67 (name == o.name && argumentCount < o.argumentCount); };
68 };
69 typedef map<string, int> VarTable;
70 typedef map<struct FuncDesc, struct FuncInfo> FuncTable;
71 typedef map<int, struct FuncDesc> CallTable;
72 //описание блоков.
73 void functionDeclarations();
74 void functionDeclaration();
75 void functionDefinitions();
76 void functionDefinition();
77 void localVariableList();
78 void argumentList();
79 void program(); //Разбор программы. BEGIN statementList END
80 bool statementList(); // Разбор списка операторов.
81 bool statement(); //разбор оператора.
82 void expression(); //разбор арифметического выражения.
83 void term(); //разбор слагаемого.
84 void factor(); //разбор множителя.
85 void relation(); //разбор условия.
86
87 // Сравнение текущей лексемы с образцом. Текущая позиция в потоке лексем не изменяется.
88 bool see(Token t)
89 {
90 return scanner_->token() == t;
91 }
92
93 // Проверка совпадения текущей лексемы с образцом. Если лексема и образец совпадают,
94 // лексема изымается из потока.
95 bool match(Token t)
96 {
97 if(scanner_->token() == t) {
98 scanner_->nextToken();
99 return true;
100 }
101 else {
102 return false;
103 }
104 }
105
106 // Переход к следующей лексеме.
107 void next()
108 {
109 scanner_->nextToken();
110 }
111
112 // Обработчик ошибок.
113 void reportError(const string& message)
114 {
115 cerr << "Line " << scanner_->getLineNumber() << ": " << message << endl;
116 error_ = true;
117 }
118
119 // проверяем, совпадает ли данная лексема с образцом. Если да, то
120 // лексема изымается из потока. Иначе создаем сообщение об ошибке и
121 // пробуем восстановиться
122 void mustBe(Token t);
123
124 // восстановление после ошибки: идем по коду до тех пор, пока не
125 // встретим эту лексему или лексему конца файла.
126 void recover(Token t);
127
128 // функция пробегает по variables_. Если находит нужную переменную
129 // - возвращает ее номер, иначе добавляет ее в массив, увеличивает
130 // lastVar и возвращает его.
131 pair<bool, int> findOrAddVariable(const string&);
132 struct FuncInfo &findFunction(const struct FuncDesc &);
133
134 Scanner* scanner_; // лексический анализатор для конструктора
135 CodeGen* codegen_; // указатель на виртуальную машину
136 ostream& output_; // выходной поток (в данном случае используем cout)
137 bool error_; // флаг ошибки. Используется чтобы определить, выводим
138 // ли список команд после разбора или нет
139 bool recovered_; // не используется
140 CallTable jumps_; // массив прижков в функции
141 CallTable calls_; // массив вызовов функции
142 FuncTable functions_; // массив деларированных функции
143 VarTable globalVariables_; // массив глобальных переменных
144 VarTable localVariables_; // массив локальных переменных
145 int lastGlobalVar_; // номер последней записанной глобальной переменной
146 struct FuncDesc *currentFuncDesc_ = NULL; // номер последней записанной глобальной переменной
147};
148
149#endif
diff --git a/vendor/cmilan/src/scanner.cpp b/vendor/cmilan/src/scanner.cpp
new file mode 100644
index 0000000..c1e1a84
--- /dev/null
+++ b/vendor/cmilan/src/scanner.cpp
@@ -0,0 +1,242 @@
1#include "scanner.h"
2#include <algorithm>
3#include <iostream>
4#include <cctype>
5
6using namespace std;
7
8static const char * tokenNames_[] = {
9 "end of file",
10 "illegal token",
11 "identifier",
12 "number",
13 "'BEGIN'",
14 "'END'",
15 "'IF'",
16 "'THEN'",
17 "'ELSE'",
18 "'FI'",
19 "'WHILE'",
20 "'DO'",
21 "'OD'",
22 "'WRITE'",
23 "'READ'",
24 "':='",
25 "'+' or '-'",
26 "'*' or '/'",
27 "comparison operator",
28 "'('",
29 "')'",
30 "';'",
31
32 "'FUNC'",
33 "'RETURN'",
34 "'RETURNS'",
35 "'LOCALS'",
36};
37
38void Scanner::nextToken()
39{
40 skipSpace();
41
42 // Пропускаем комментарии
43 // Если встречаем "/", то за ним должна идти "*". Если "*" не встречена, считаем, что встретили операцию деления
44 // и лексему - операция типа умножения. Дальше смотрим все символы, пока не находим звездочку или символ конца файла.
45 // Если нашли * - проверяем на наличие "/" после нее. Если "/" не найден - ищем следующую "*".
46 while(ch_ == '/') {
47 nextChar();
48 if(ch_ == '*') {
49 nextChar();
50 bool inside = true;
51 while(inside) {
52 while(ch_ != '*' && !input_.eof()) {
53 nextChar();
54 }
55
56 if(input_.eof()) {
57 token_ = T_EOF;
58 return;
59 }
60
61 nextChar();
62 if(ch_ == '/') {
63 inside = false;
64 nextChar();
65 }
66 }
67 }
68 else {
69 token_ = T_MULOP;
70 arithmeticValue_ = A_DIVIDE;
71 return;
72 }
73
74 skipSpace();
75 }
76
77 //Если встречен конец файла, считаем за лексему конца файла.
78 if(input_.eof()) {
79 token_ = T_EOF;
80 return;
81 }
82 //Если встретили цифру, то до тех пока дальше идут цифры - считаем как продолжение числа.
83 //Запоминаем полученное целое, а за лексему считаем целочисленный литерал
84
85 if(isdigit(ch_)) {
86 int value = 0;
87 while(isdigit(ch_)) {
88 value = value * 10 + (ch_ - '0'); //поразрядное считывание, преобразуем символьное значение к числу.
89 nextChar();
90 }
91 token_ = T_NUMBER;
92 intValue_ = value;
93 }
94 //Если же следующий символ - буква ЛА - тогда считываем до тех пор, пока дальше буквы ЛА или цифры.
95 //Как только считали имя переменной, сравниваем ее со списком зарезервированных слов. Если не совпадает ни с одним из них,
96 //считаем, что получили переменную, имя которой запоминаем, а за текущую лексему считаем лексему идентификатора.
97 //Если совпадает с каким-либо словом из списка - считаем что получили лексему, соответствующую этому слову.
98 else if(isIdentifierStart(ch_)) {
99 string buffer;
100 while(isIdentifierBody(ch_)) {
101 buffer += ch_;
102 nextChar();
103 }
104
105 transform(buffer.begin(), buffer.end(), buffer.begin(), ::tolower);
106
107 map<string, Token>::iterator kwd = keywords_.find(buffer);
108 if(kwd == keywords_.end()) {
109 token_ = T_IDENTIFIER;
110 stringValue_ = buffer;
111 }
112 else {
113 token_ = kwd->second;
114 }
115 }
116 //Символ не является буквой, цифрой, "/" или признаком конца файла
117 else {
118 switch(ch_) {
119 //Признак лексемы открывающей скобки - встретили "("
120 case '(':
121 token_ = T_LPAREN;
122 nextChar();
123 break;
124 //Признак лексемы закрывающей скобки - встретили ")"
125 case ')':
126 token_ = T_RPAREN;
127 nextChar();
128 break;
129 //Признак лексемы ";" - встретили ";"
130 case ';':
131 token_ = T_SEMICOLON;
132 nextChar();
133 break;
134 //Признак лексемы "," - встретили ","
135 case ',':
136 token_ = T_COMMA;
137 nextChar();
138 break;
139 //Если встречаем ":", то дальше смотрим наличие символа "=". Если находим, то считаем что нашли лексему присваивания
140 //Иначе - лексема ошибки.
141 case ':':
142 nextChar();
143 if(ch_ == '=') {
144 token_ = T_ASSIGN;
145 nextChar();
146
147 }
148 else {
149 token_ = T_ILLEGAL;
150 }
151 break;
152 //Если встретили символ "<", то либо следующий символ "=", тогда лексема нестрогого сравнения. Иначе - строгого.
153 case '<':
154 token_ = T_CMP;
155 nextChar();
156 if(ch_ == '=') {
157 cmpValue_ = C_LE;
158 nextChar();
159 }
160 else {
161 cmpValue_ = C_LT;
162 }
163 break;
164 //Аналогично предыдущему случаю
165 case '>':
166 token_ = T_CMP;
167 nextChar();
168 if(ch_ == '=') {
169 cmpValue_ = C_GE;
170 nextChar();
171 }
172 else {
173 cmpValue_ = C_GT;
174 }
175 break;
176 //Если встретим "!", то дальше должно быть "=", тогда считаем, что получили лексему сравнения
177 //и знак "!=" иначе считаем, что у нас лексема ошибки
178 case '!':
179 nextChar();
180 if(ch_ == '=') {
181 nextChar();
182 token_ = T_CMP;
183 cmpValue_ = C_NE;
184 }
185 else {
186 token_ = T_ILLEGAL;
187 }
188 break;
189 //Если встретим "=" - лексема сравнения и знак "="
190 case '=':
191 token_ = T_CMP;
192 cmpValue_ = C_EQ;
193 nextChar();
194 break;
195 //Знаки операций. Для "+"/"-" получим лексему операции типа сложнения, и соответствующую операцию.
196 //для "*" - лексему операции типа умножения
197 case '+':
198 token_ = T_ADDOP;
199 arithmeticValue_ = A_PLUS;
200 nextChar();
201 break;
202
203 case '-':
204 token_ = T_ADDOP;
205 arithmeticValue_ = A_MINUS;
206 nextChar();
207 break;
208
209 case '*':
210 token_ = T_MULOP;
211 arithmeticValue_ = A_MULTIPLY;
212 nextChar();
213 break;
214 //Иначе лексема ошибки.
215 default:
216 token_ = T_ILLEGAL;
217 nextChar();
218 break;
219 }
220 }
221}
222
223void Scanner::skipSpace()
224{
225 while(isspace(ch_)) {
226 if(ch_ == '\n') {
227 ++lineNumber_;
228 }
229
230 nextChar();
231 }
232}
233
234void Scanner::nextChar()
235{
236 ch_ = input_.get();
237}
238
239const char * tokenToString(Token t)
240{
241 return tokenNames_[t];
242}
diff --git a/vendor/cmilan/src/scanner.h b/vendor/cmilan/src/scanner.h
new file mode 100644
index 0000000..5c23300
--- /dev/null
+++ b/vendor/cmilan/src/scanner.h
@@ -0,0 +1,175 @@
1#ifndef CMILAN_SCANNER_H
2#define CMILAN_SCANNER_H
3
4#include <fstream>
5#include <string>
6#include <map>
7
8using namespace std;
9
10enum Token {
11 T_EOF, // Конец текстового потока
12 T_ILLEGAL, // Признак недопустимого символа
13 T_IDENTIFIER, // Идентификатор
14 T_NUMBER, // Целочисленный литерал
15 T_BEGIN, // Ключевое слово "begin"
16 T_END, // Ключевое слово "end"
17 T_IF, // Ключевое слово "if"
18 T_THEN, // Ключевое слово "then"
19 T_ELSE, // Ключевое слово "else"
20 T_FI, // Ключевое слово "fi"
21 T_WHILE, // Ключевое слово "while"
22 T_DO, // Ключевое слово "do"
23 T_OD, // Ключевое слово "od"
24 T_WRITE, // Ключевое слово "write"
25 T_READ, // Ключевое слово "read"
26 T_ASSIGN, // Оператор ":="
27 T_ADDOP, // Сводная лексема для "+" и "-" (операция типа сложения)
28 T_MULOP, // Сводная лексема для "*" и "/" (операция типа умножения)
29 T_CMP, // Сводная лексема для операторов отношения
30 T_LPAREN, // Открывающая скобка
31 T_RPAREN, // Закрывающая скобка
32 T_SEMICOLON, // ";"
33
34 T_FUNC, // Ключевое слово "func"
35 T_RETURN, // Ключевое слово "return"
36 T_RETURNS, // Ключевое слово "returns"
37 T_LOCALS, // Ключевое слово "LOCALS"
38 T_COMMA, // ","
39};
40
41// Функция tokenToString возвращает описание лексемы.
42// Используется при печати сообщения об ошибке.
43const char * tokenToString(Token t);
44
45// Виды операций сравнения
46enum Cmp {
47 C_EQ, // Операция сравнения "="
48 C_NE, // Операция сравнения "!="
49 C_LT, // Операция сравнения "<"
50 C_LE, // Операция сравнения "<="
51 C_GT, // Операция сравнения ">"
52 C_GE // Операция сравнения ">="
53};
54
55// Виды арифметических операций
56enum Arithmetic {
57 A_PLUS, //операция "+"
58 A_MINUS, //операция "-"
59 A_MULTIPLY, //операция "*"
60 A_DIVIDE //операция "/"
61};
62
63// Лексический анализатор
64
65class Scanner
66{
67public:
68 // Конструктор. В качестве аргумента принимает имя файла и поток,
69 // из которого будут читаться символы транслируемой программы.
70
71 explicit Scanner(const string& fileName, istream& input)
72 : fileName_(fileName), lineNumber_(1), input_(input)
73 {
74 keywords_["begin"] = T_BEGIN;
75 keywords_["end"] = T_END;
76 keywords_["if"] = T_IF;
77 keywords_["then"] = T_THEN;
78 keywords_["else"] = T_ELSE;
79 keywords_["fi"] = T_FI;
80 keywords_["while"] = T_WHILE;
81 keywords_["do"] = T_DO;
82 keywords_["od"] = T_OD;
83 keywords_["write"] = T_WRITE;
84 keywords_["read"] = T_READ;
85
86 keywords_["func"] = T_FUNC;
87 keywords_["return"] = T_RETURN;
88 keywords_["returns"] = T_RETURNS;
89 keywords_["locals"] = T_LOCALS;
90
91 nextChar();
92 }
93
94 // Деструктор
95 virtual ~Scanner()
96 {}
97
98 //getters всех private переменных
99 const string& getFileName() const //не используется
100 {
101 return fileName_;
102 }
103
104 int getLineNumber() const
105 {
106 return lineNumber_;
107 }
108
109 Token token() const
110 {
111 return token_;
112 }
113
114 int getIntValue() const
115 {
116 return intValue_;
117 }
118
119 string getStringValue() const
120 {
121 return stringValue_;
122 }
123
124 Cmp getCmpValue() const
125 {
126 return cmpValue_;
127 }
128
129 Arithmetic getArithmeticValue() const
130 {
131 return arithmeticValue_;
132 }
133
134 // Переход к следующей лексеме.
135 // Текущая лексема записывается в token_ и изымается из потока.
136 void nextToken();
137private:
138
139 // Пропуск всех пробельные символы.
140 // Если встречается символ перевода строки, номер текущей строки
141 // (lineNumber) увеличивается на единицу.
142 void skipSpace();
143
144
145 void nextChar(); //переходит к следующему символу
146 //проверка переменной на первый символ (должен быть буквой латинского алфавита)
147 bool isIdentifierStart(char c)
148 {
149 return ((c >= 'a' && c <= 'z') ||
150 (c >= 'A' && c <= 'Z'));
151 }
152 //проверка на остальные символы переменной (буква или цифра)
153 bool isIdentifierBody(char c)
154 {
155 return isIdentifierStart(c) || isdigit(c);
156 }
157
158
159 const string fileName_; //входной файл
160 int lineNumber_; //номер текущей строки кода
161
162 Token token_; //текущая лексема
163 int intValue_; //значение текущего целого
164 string stringValue_; //имя переменной
165 Cmp cmpValue_; //значение оператора сравнения (>, <, =, !=, >=, <=)
166 Arithmetic arithmeticValue_; //значение знака (+,-,*,/)
167
168 map<string, Token> keywords_; //ассоциативный массив с лексемами и
169 //соответствующими им зарезервированными словами в качестве индексов
170
171 istream& input_; //входной поток для чтения из файла.
172 char ch_; //текущий символ
173};
174
175#endif
diff --git a/vendor/cmilan/test/add.mil b/vendor/cmilan/test/add.mil
new file mode 100644
index 0000000..6822ff5
--- /dev/null
+++ b/vendor/cmilan/test/add.mil
@@ -0,0 +1,7 @@
1BEGIN
2 i := 1;
3 j := 2;
4 k := i + j;
5 WRITE(k)
6END
7
diff --git a/vendor/cmilan/test/comment.mil b/vendor/cmilan/test/comment.mil
new file mode 100644
index 0000000..4909fdf
--- /dev/null
+++ b/vendor/cmilan/test/comment.mil
@@ -0,0 +1,14 @@
1/* это комментарий */
2/* это продолжение комментария */
3
4/*****************************
5 * эта программа печатает 42 *
6 ****************************/
7
8begin /* комментарий в конце строки */
9/* комментарий в начале строки */ write(42)
10/* многострочный
11 комментарий */
12end
13
14/* комментарий в конце файла */
diff --git a/vendor/cmilan/test/factorial.mil b/vendor/cmilan/test/factorial.mil
new file mode 100644
index 0000000..c9e5e50
--- /dev/null
+++ b/vendor/cmilan/test/factorial.mil
@@ -0,0 +1,10 @@
1BEGIN
2 n := READ;
3 factorial := 1;
4 i := 1;
5 WHILE i <= n DO
6 factorial := factorial * i;
7 i := i + 1
8 OD;
9 WRITE(factorial)
10END
diff --git a/vendor/cmilan/test/fib.mil b/vendor/cmilan/test/fib.mil
new file mode 100644
index 0000000..cc8d6c7
--- /dev/null
+++ b/vendor/cmilan/test/fib.mil
@@ -0,0 +1,17 @@
1/* Вычисление N-го числа Фибоначчи */
2
3BEGIN
4 a := 1;
5 b := 1;
6 n := READ;
7
8 WHILE n > 1 DO
9 t := a;
10 a := b;
11 b := b + t;
12 n := n - 1
13 OD;
14
15 WRITE(a)
16END
17
diff --git a/vendor/cmilan/test/gcd.mil b/vendor/cmilan/test/gcd.mil
new file mode 100644
index 0000000..bf65342
--- /dev/null
+++ b/vendor/cmilan/test/gcd.mil
@@ -0,0 +1,17 @@
1/* Greatest common divisor */
2
3BEGIN
4 a := READ;
5 b := READ;
6
7 WHILE a != b DO
8 IF a < b THEN
9 b := b - a
10 ELSE
11 a := a - b
12 FI
13 OD;
14
15 WRITE(a)
16END
17
diff --git a/vendor/cmilan/test/if.mil b/vendor/cmilan/test/if.mil
new file mode 100644
index 0000000..112b41a
--- /dev/null
+++ b/vendor/cmilan/test/if.mil
@@ -0,0 +1,7 @@
1BEGIN
2 i := 1;
3 j := 2;
4
5 IF i < j THEN WRITE(i) FI;
6 IF i < j THEN WRITE(i) ELSE WRITE(j) FI
7END
diff --git a/vendor/cmilan/test/invalid.mil b/vendor/cmilan/test/invalid.mil
new file mode 100644
index 0000000..94be156
--- /dev/null
+++ b/vendor/cmilan/test/invalid.mil
@@ -0,0 +1,5 @@
1BEGIN
2 IF 1 2 THEN WRITE(n) ELSE WRITE(2) FI;
3 X := Y + 1;
4 WRITE (X +)
5END
diff --git a/vendor/cmilan/test/invert.mil b/vendor/cmilan/test/invert.mil
new file mode 100644
index 0000000..47f1bef
--- /dev/null
+++ b/vendor/cmilan/test/invert.mil
@@ -0,0 +1,14 @@
1BEGIN
2 x := READ;
3 x := -x;
4
5 WRITE(-x);
6
7 IF -x > 0 THEN x := 1 FI;
8
9 x := x + -1;
10 x := x - -x;
11
12 x := x -1
13END
14
diff --git a/vendor/cmilan/test/loop.mil b/vendor/cmilan/test/loop.mil
new file mode 100644
index 0000000..c2f6d64
--- /dev/null
+++ b/vendor/cmilan/test/loop.mil
@@ -0,0 +1,17 @@
1BEGIN
2 /* Read a number */
3
4 i := READ;
5
6 /* Count from 0 to this number */
7
8 IF i > 0 THEN step := 1 ELSE step := -1 FI;
9 k := 0;
10 WHILE k != i DO
11 WRITE(k);
12 k := k + step
13 OD;
14
15 WRITE(i)
16END
17
diff --git a/vendor/cmilan/test/power.mil b/vendor/cmilan/test/power.mil
new file mode 100644
index 0000000..ac3a830
--- /dev/null
+++ b/vendor/cmilan/test/power.mil
@@ -0,0 +1,14 @@
1BEGIN
2 N := READ;
3 P := READ;
4
5 S := 1;
6
7 WHILE P > 0 DO
8 S := S * N;
9 P := P - 1
10 OD;
11
12 WRITE(S)
13END
14
diff --git a/vendor/cmilan/test/read2.mil b/vendor/cmilan/test/read2.mil
new file mode 100644
index 0000000..90222fd
--- /dev/null
+++ b/vendor/cmilan/test/read2.mil
@@ -0,0 +1,8 @@
1BEGIN
2 IF READ < READ
3 THEN
4 WRITE(1)
5 ELSE
6 WRITE(2)
7 FI
8END
diff --git a/vendor/cmilan/test/sum.mil b/vendor/cmilan/test/sum.mil
new file mode 100644
index 0000000..e12c940
--- /dev/null
+++ b/vendor/cmilan/test/sum.mil
@@ -0,0 +1,9 @@
1BEGIN
2 i := 8;
3 j := 2;
4
5 WHILE i != j DO
6 IF i < j THEN j := j - i ELSE i := i - j FI
7 OD;
8 WRITE(i)
9END
diff --git a/vendor/vm/doc/changelog.txt b/vendor/vm/doc/changelog.txt
new file mode 100644
index 0000000..104d663
--- /dev/null
+++ b/vendor/vm/doc/changelog.txt
@@ -0,0 +1,10 @@
1История изменений:
2==================
3
4Версия 1.2:
5 * Виртуальная машина отделена от компилятора ymilan в отдельный пакет со своей
6 нумерацией версий.
7 * Добавлена команда NOP (отсутствие операции).
8
9Версия 1.1:
10 * Первоначальная версия виртуальной машины в комплеке компилятора ymilan 1.1.
diff --git a/vendor/vm/doc/vm.txt b/vendor/vm/doc/vm.txt
new file mode 100644
index 0000000..8c27ff3
--- /dev/null
+++ b/vendor/vm/doc/vm.txt
@@ -0,0 +1,230 @@
1== Машинные команды ==
2
3Виртуальная машина Милана содержит из памяти команд, памяти данных и
4стека. В памяти команд находятся исполняемые инструкции. Память
5данных используется для хранения значений переменных. Является рабочей
6областью: команды виртуальной машины считывают свои аргументы из стека
7и заталкивают в стек результаты.
8
9Виртуальная машина Милана исполняет следующие команды.
10
11NOP
12
13 Отсутствие операции; команда пропускается.
14
15STOP
16
17 Прекращает выполнение программы; виртуальная машина возвращает
18 управление операционной системе.
19
20LOAD <адрес>
21
22 Помещает в стек слово, расположенное в памяти по адресу
23 <адрес>.
24
25STORE <адрес>
26
27 Выталкивает из стека слово и записывает его в память по адресу
28 <адрес>. Если нужная ячейка находится за пределами рабочей
29 области памяти, диагностируется ошибка времени исполнения.
30
31
32BLOAD <адрес>
33
34 Помещает в стек слово, адрес которого вычисляется следующим
35 образом: <адрес в памяти> = <адрес> + <значение с вершины
36 стека>. Значение с вершины стека удаляется.
37
38 Команду BLOAD можно использовать, например, для обращения к
39 элементу массива или к переменной, адрес которой вычисляется
40 во время выполнения программы.
41
42BSTORE <адрес>
43
44 Вычисляет адрес в памяти по формуле:
45 <адрес в памяти> = <адрес> + <значение с вершины стека>, значение
46 с вершины стека при этом удаляется. Выталкивает из стека слово и записывает
47 его по адресу <адрес в памяти>.
48
49 Команду BSTORE можно использовать для записи значения в элемент
50 массива или в переменную, адрес которой вычисляется во время выполнения
51 программы.
52
53 Пусть стек имеет вид: [10, 20, ...]. В этом случае команда BSTORE 5
54 запишет по адресу 15 число 20.
55
56PUSH <значение>
57
58 Заталкивает <значение> в стек.
59
60POP
61
62 Выталкивает слово из стека.
63
64DUP
65
66 Заталкивает в стек значение, равное значению на вершине стека.
67
68ADD
69
70 Выталкивает из стека два числа и заталкивает в стек результат
71 их сложения.
72
73MULT
74
75 Выталкивает из стека два числа и заталкивает в стек результат
76 их умножения.
77
78SUB
79
80 Выталкивает из стека число <a>, выталкивает из стека число <b>
81 и заталкивает в стек разность <b> - <a>.
82
83 Пример: после выполнения последовательности команд
84
85 PUSH 10
86 PUSH 8
87 SUB
88
89 на вершине стека будет находиться число 2.
90
91DIV
92
93 Выталкивает из стека число <a>, выталкивает из стека число <b>
94 и заталкивает в стек частное <b> / <a>. Используется
95 целочисленное деление. Если значение <a> = 0, то
96 диагностируется ошибка времени исполнения.
97
98INVERT
99
100 Меняет знак числа на вершине стека на противоположный.
101
102COMPARE <код>
103
104 Выталкивает из стека число <a>, выталкивает из стека число
105 <b>, затем заталкивает в стек результат сравнения <b> и <a>.
106
107 Операция сравнения определяется значением аргумента <код>:
108
109 <код> операция
110
111 0 <b> = <a>
112 1 <b> != <a>
113 2 <b> < <a>
114 3 <b> > <a>
115 4 <b> <= <a>
116 5 <b> >= <a>
117
118 Результатом сравнения является значение 1, если требуемое
119 неравенство выполняется, и 0 в противном случае.
120
121 Пример: после выполнения последовательности команд
122
123 PUSH 5
124 PUSH 7
125 COMPARE 2
126
127 на вершине стека будет находиться значение 1 (так как 5 < 7).
128
129JUMP <адрес>
130
131 Выполняет переход по адресу <адрес>, то есть устанавливает
132 адрес следующей исполняемой команды равным <адрес>. Если
133 <адрес> меньше нуля или больше, чем адрес последней команды в
134 программе, диагностируется ошибка времени исполнения.
135
136
137JUMP_YES <адрес>
138
139 Выполняет переход по адресу <адрес>, если на вершине стека
140 находится ненулевое значение; слово выталкивается из стека.
141
142JUMP_NO <адрес>
143
144 Выполняет переход по адресу <адрес>, если на вершине стека
145 находится значение 0; слово выталкивается из стека. Если
146 <адрес> меньше нуля или больше, чем адрес последней команды в
147 программе, диагностируется ошибка времени исполнения.
148
149INPUT
150
151 Считывает целочисленное значение со стандартного устройства
152 ввода и заталкивает его в стек. В случае ошибки ввода-вывода
153 или несоответсвия формата диагностируется ошибка времени
154 исполнения.
155
156PRINT
157
158 Выталкивает из стека слово и выводит его на стандартное
159 устройство ввода. Значение форматируется как целое число.
160
161Каждая команда исполняется за один такт работы виртуальной машины.
162
163Виртуальная машина формирует содержимое памяти команд и данных, читая
164и интерпретируя текстовый файл программы. Файл имеет следующий формат.
165
166Файл читается как последовательность строк. Символ ';' начинает
167комментарий, все символы, начиная с него и до конца строки,
168игнорируются.
169
170Команда состоит из адреса, кода операции и аргумента, если он
171требуется. Адрес является целым числом, за которым следует символ
172':'. Нумерация команд начинается с 0.
173
174Код операции совпадает с описанным ранее символьным обозначением,
175например: STOP. Если команда имеет аргумент, он должен быть целым
176числом.
177
178Пример корректной программы на языке виртуальной машины Милана:
179
180------------------------------------------------------------
1810: INPUT
1821: STORE 42 ; n := READ
1832: LOAD 14
1843: PUSH 4
1854: LOAD 42
1865: COMPARE 2
1876: JUMP_NO 9
1887: PUSH 10
1898: STORE 42
1909: LOAD 42
19110: PRINT
19211: STOP
193-------------------------------------------------------------
194
195Для инициализации памяти данных используется служебная инструкция
196виртуальной машины SET:
197
198 SET <адрес> <значение>
199
200В результате исполнения инструкции SET по адресу <адрес> в память
201данных записывается слово <значение>.
202
203Инструкция SET не сохраняется в памяти команд. Она служит для
204инициализации памяти перед началом исполнения программы. Компилятор
205может генерировать блок команд SET для задания значений констант и
206статически инициализированных переменных.
207
208Инструкция SET <адрес> <значение> эквивалентна паре команд
209
210 PUSH <значение>
211 STORE <адрес>
212
213и выполняется за один такт.
214
215Инструкция SET не требует указания адреса. Пример корректного
216использованя SET:
217
218------------------------------------
219SET 0 15
220SET 1 40
221
2220: LOAD 0
2231: LOAD 1
2242: ADD
2253: PRINT
2264: STOP
227------------------------------------
228
229В результате выполнения этой программы будет напечатано число 55.
230
diff --git a/vendor/vm/vm/Makefile b/vendor/vm/vm/Makefile
new file mode 100644
index 0000000..c0c1887
--- /dev/null
+++ b/vendor/vm/vm/Makefile
@@ -0,0 +1,15 @@
1mvm: vm.c lex.yy.c vmparse.tab.h main.c
2 gcc -ggdb3 -o mvm main.c vm.c lex.yy.c vmparse.tab.c
3
4lex.yy.c: vmlex.l
5 flex vmlex.l
6
7vmparse.tab.h: vmparse.y
8 bison -d vmparse.y
9
10clean:
11 rm lex.yy.c vmparse.tab.h vmparse.tab.c
12
13distclean:
14 rm mvm lex.yy.c vmparse.tab.h vmparse.tab.c
15
diff --git a/vendor/vm/vm/lex.yy.c b/vendor/vm/vm/lex.yy.c
new file mode 100644
index 0000000..558802d
--- /dev/null
+++ b/vendor/vm/vm/lex.yy.c
@@ -0,0 +1,1964 @@
1
2#line 2 "lex.yy.c"
3
4#define YY_INT_ALIGNED short int
5
6/* A lexical scanner generated by flex */
7
8#define FLEX_SCANNER
9#define YY_FLEX_MAJOR_VERSION 2
10#define YY_FLEX_MINOR_VERSION 6
11#define YY_FLEX_SUBMINOR_VERSION 4
12#if YY_FLEX_SUBMINOR_VERSION > 0
13#define FLEX_BETA
14#endif
15
16/* First, we deal with platform-specific or compiler-specific issues. */
17
18/* begin standard C headers. */
19#include <stdio.h>
20#include <string.h>
21#include <errno.h>
22#include <stdlib.h>
23
24/* end standard C headers. */
25
26/* flex integer type definitions */
27
28#ifndef FLEXINT_H
29#define FLEXINT_H
30
31/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
32
33#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
34
35/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
36 * if you want the limit (max/min) macros for int types.
37 */
38#ifndef __STDC_LIMIT_MACROS
39#define __STDC_LIMIT_MACROS 1
40#endif
41
42#include <inttypes.h>
43typedef int8_t flex_int8_t;
44typedef uint8_t flex_uint8_t;
45typedef int16_t flex_int16_t;
46typedef uint16_t flex_uint16_t;
47typedef int32_t flex_int32_t;
48typedef uint32_t flex_uint32_t;
49#else
50typedef signed char flex_int8_t;
51typedef short int flex_int16_t;
52typedef int flex_int32_t;
53typedef unsigned char flex_uint8_t;
54typedef unsigned short int flex_uint16_t;
55typedef unsigned int flex_uint32_t;
56
57/* Limits of integral types. */
58#ifndef INT8_MIN
59#define INT8_MIN (-128)
60#endif
61#ifndef INT16_MIN
62#define INT16_MIN (-32767-1)
63#endif
64#ifndef INT32_MIN
65#define INT32_MIN (-2147483647-1)
66#endif
67#ifndef INT8_MAX
68#define INT8_MAX (127)
69#endif
70#ifndef INT16_MAX
71#define INT16_MAX (32767)
72#endif
73#ifndef INT32_MAX
74#define INT32_MAX (2147483647)
75#endif
76#ifndef UINT8_MAX
77#define UINT8_MAX (255U)
78#endif
79#ifndef UINT16_MAX
80#define UINT16_MAX (65535U)
81#endif
82#ifndef UINT32_MAX
83#define UINT32_MAX (4294967295U)
84#endif
85
86#ifndef SIZE_MAX
87#define SIZE_MAX (~(size_t)0)
88#endif
89
90#endif /* ! C99 */
91
92#endif /* ! FLEXINT_H */
93
94/* begin standard C++ headers. */
95
96/* TODO: this is always defined, so inline it */
97#define yyconst const
98
99#if defined(__GNUC__) && __GNUC__ >= 3
100#define yynoreturn __attribute__((__noreturn__))
101#else
102#define yynoreturn
103#endif
104
105/* Returned upon end-of-file. */
106#define YY_NULL 0
107
108/* Promotes a possibly negative, possibly signed char to an
109 * integer in range [0..255] for use as an array index.
110 */
111#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
112
113/* Enter a start condition. This macro really ought to take a parameter,
114 * but we do it the disgusting crufty way forced on us by the ()-less
115 * definition of BEGIN.
116 */
117#define BEGIN (yy_start) = 1 + 2 *
118/* Translate the current start state into a value that can be later handed
119 * to BEGIN to return to the state. The YYSTATE alias is for lex
120 * compatibility.
121 */
122#define YY_START (((yy_start) - 1) / 2)
123#define YYSTATE YY_START
124/* Action number for EOF rule of a given start state. */
125#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
126/* Special action meaning "start processing a new file". */
127#define YY_NEW_FILE yyrestart( yyin )
128#define YY_END_OF_BUFFER_CHAR 0
129
130/* Size of default input buffer. */
131#ifndef YY_BUF_SIZE
132#ifdef __ia64__
133/* On IA-64, the buffer size is 16k, not 8k.
134 * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
135 * Ditto for the __ia64__ case accordingly.
136 */
137#define YY_BUF_SIZE 32768
138#else
139#define YY_BUF_SIZE 16384
140#endif /* __ia64__ */
141#endif
142
143/* The state buf must be large enough to hold one state per character in the main buffer.
144 */
145#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
146
147#ifndef YY_TYPEDEF_YY_BUFFER_STATE
148#define YY_TYPEDEF_YY_BUFFER_STATE
149typedef struct yy_buffer_state *YY_BUFFER_STATE;
150#endif
151
152#ifndef YY_TYPEDEF_YY_SIZE_T
153#define YY_TYPEDEF_YY_SIZE_T
154typedef size_t yy_size_t;
155#endif
156
157extern int yyleng;
158
159extern FILE *yyin, *yyout;
160
161#define EOB_ACT_CONTINUE_SCAN 0
162#define EOB_ACT_END_OF_FILE 1
163#define EOB_ACT_LAST_MATCH 2
164
165 #define YY_LESS_LINENO(n)
166 #define YY_LINENO_REWIND_TO(ptr)
167
168/* Return all but the first "n" matched characters back to the input stream. */
169#define yyless(n) \
170 do \
171 { \
172 /* Undo effects of setting up yytext. */ \
173 int yyless_macro_arg = (n); \
174 YY_LESS_LINENO(yyless_macro_arg);\
175 *yy_cp = (yy_hold_char); \
176 YY_RESTORE_YY_MORE_OFFSET \
177 (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
178 YY_DO_BEFORE_ACTION; /* set up yytext again */ \
179 } \
180 while ( 0 )
181#define unput(c) yyunput( c, (yytext_ptr) )
182
183#ifndef YY_STRUCT_YY_BUFFER_STATE
184#define YY_STRUCT_YY_BUFFER_STATE
185struct yy_buffer_state
186 {
187 FILE *yy_input_file;
188
189 char *yy_ch_buf; /* input buffer */
190 char *yy_buf_pos; /* current position in input buffer */
191
192 /* Size of input buffer in bytes, not including room for EOB
193 * characters.
194 */
195 int yy_buf_size;
196
197 /* Number of characters read into yy_ch_buf, not including EOB
198 * characters.
199 */
200 int yy_n_chars;
201
202 /* Whether we "own" the buffer - i.e., we know we created it,
203 * and can realloc() it to grow it, and should free() it to
204 * delete it.
205 */
206 int yy_is_our_buffer;
207
208 /* Whether this is an "interactive" input source; if so, and
209 * if we're using stdio for input, then we want to use getc()
210 * instead of fread(), to make sure we stop fetching input after
211 * each newline.
212 */
213 int yy_is_interactive;
214
215 /* Whether we're considered to be at the beginning of a line.
216 * If so, '^' rules will be active on the next match, otherwise
217 * not.
218 */
219 int yy_at_bol;
220
221 int yy_bs_lineno; /**< The line count. */
222 int yy_bs_column; /**< The column count. */
223
224 /* Whether to try to fill the input buffer when we reach the
225 * end of it.
226 */
227 int yy_fill_buffer;
228
229 int yy_buffer_status;
230
231#define YY_BUFFER_NEW 0
232#define YY_BUFFER_NORMAL 1
233 /* When an EOF's been seen but there's still some text to process
234 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
235 * shouldn't try reading from the input source any more. We might
236 * still have a bunch of tokens to match, though, because of
237 * possible backing-up.
238 *
239 * When we actually see the EOF, we change the status to "new"
240 * (via yyrestart()), so that the user can continue scanning by
241 * just pointing yyin at a new input file.
242 */
243#define YY_BUFFER_EOF_PENDING 2
244
245 };
246#endif /* !YY_STRUCT_YY_BUFFER_STATE */
247
248/* Stack of input buffers. */
249static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
250static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
251static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */
252
253/* We provide macros for accessing buffer states in case in the
254 * future we want to put the buffer states in a more general
255 * "scanner state".
256 *
257 * Returns the top of the stack, or NULL.
258 */
259#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
260 ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
261 : NULL)
262/* Same as previous macro, but useful when we know that the buffer stack is not
263 * NULL or when we need an lvalue. For internal use only.
264 */
265#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
266
267/* yy_hold_char holds the character lost when yytext is formed. */
268static char yy_hold_char;
269static int yy_n_chars; /* number of characters read into yy_ch_buf */
270int yyleng;
271
272/* Points to current character in buffer. */
273static char *yy_c_buf_p = NULL;
274static int yy_init = 0; /* whether we need to initialize */
275static int yy_start = 0; /* start state number */
276
277/* Flag which is used to allow yywrap()'s to do buffer switches
278 * instead of setting up a fresh yyin. A bit of a hack ...
279 */
280static int yy_did_buffer_switch_on_eof;
281
282void yyrestart ( FILE *input_file );
283void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer );
284YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size );
285void yy_delete_buffer ( YY_BUFFER_STATE b );
286void yy_flush_buffer ( YY_BUFFER_STATE b );
287void yypush_buffer_state ( YY_BUFFER_STATE new_buffer );
288void yypop_buffer_state ( void );
289
290static void yyensure_buffer_stack ( void );
291static void yy_load_buffer_state ( void );
292static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file );
293#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER )
294
295YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size );
296YY_BUFFER_STATE yy_scan_string ( const char *yy_str );
297YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len );
298
299void *yyalloc ( yy_size_t );
300void *yyrealloc ( void *, yy_size_t );
301void yyfree ( void * );
302
303#define yy_new_buffer yy_create_buffer
304#define yy_set_interactive(is_interactive) \
305 { \
306 if ( ! YY_CURRENT_BUFFER ){ \
307 yyensure_buffer_stack (); \
308 YY_CURRENT_BUFFER_LVALUE = \
309 yy_create_buffer( yyin, YY_BUF_SIZE ); \
310 } \
311 YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
312 }
313#define yy_set_bol(at_bol) \
314 { \
315 if ( ! YY_CURRENT_BUFFER ){\
316 yyensure_buffer_stack (); \
317 YY_CURRENT_BUFFER_LVALUE = \
318 yy_create_buffer( yyin, YY_BUF_SIZE ); \
319 } \
320 YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
321 }
322#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
323
324/* Begin user sect3 */
325
326#define yywrap() (/*CONSTCOND*/1)
327#define YY_SKIP_YYWRAP
328typedef flex_uint8_t YY_CHAR;
329
330FILE *yyin = NULL, *yyout = NULL;
331
332typedef int yy_state_type;
333
334extern int yylineno;
335int yylineno = 1;
336
337extern char *yytext;
338#ifdef yytext_ptr
339#undef yytext_ptr
340#endif
341#define yytext_ptr yytext
342
343static yy_state_type yy_get_previous_state ( void );
344static yy_state_type yy_try_NUL_trans ( yy_state_type current_state );
345static int yy_get_next_buffer ( void );
346static void yynoreturn yy_fatal_error ( const char* msg );
347
348/* Done after the current pattern has been matched and before the
349 * corresponding action - sets up yytext.
350 */
351#define YY_DO_BEFORE_ACTION \
352 (yytext_ptr) = yy_bp; \
353 yyleng = (int) (yy_cp - yy_bp); \
354 (yy_hold_char) = *yy_cp; \
355 *yy_cp = '\0'; \
356 (yy_c_buf_p) = yy_cp;
357#define YY_NUM_RULES 32
358#define YY_END_OF_BUFFER 33
359/* This struct is not used in this scanner,
360 but its presence is necessary. */
361struct yy_trans_info
362 {
363 flex_int32_t yy_verify;
364 flex_int32_t yy_nxt;
365 };
366static const flex_int16_t yy_accept[106] =
367 { 0,
368 0, 0, 33, 32, 3, 1, 32, 4, 5, 32,
369 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
370 32, 32, 3, 4, 0, 2, 0, 0, 0, 0,
371 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
372 0, 0, 0, 0, 0, 0, 21, 0, 0, 0,
373 0, 24, 19, 0, 0, 0, 0, 0, 31, 18,
374 0, 0, 0, 11, 0, 0, 22, 0, 0, 6,
375 0, 0, 0, 26, 13, 23, 0, 17, 0, 0,
376 12, 0, 15, 0, 0, 29, 0, 0, 8, 30,
377 0, 10, 14, 16, 0, 20, 0, 0, 7, 9,
378
379 25, 28, 0, 27, 0
380 } ;
381
382static const YY_CHAR yy_ec[256] =
383 { 0,
384 1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
385 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
386 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
387 1, 2, 1, 1, 1, 1, 1, 1, 1, 1,
388 1, 1, 1, 1, 4, 1, 1, 5, 5, 5,
389 5, 5, 5, 5, 5, 5, 5, 6, 7, 1,
390 1, 1, 1, 1, 8, 9, 10, 11, 12, 13,
391 1, 14, 15, 16, 1, 17, 18, 19, 20, 21,
392 1, 22, 23, 24, 25, 26, 1, 1, 27, 1,
393 1, 1, 1, 1, 28, 1, 1, 1, 1, 1,
394
395 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
396 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
397 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
398 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
399 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
400 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
401 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
402 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
403 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
404 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
405
406 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
407 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
408 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
409 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
410 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
411 1, 1, 1, 1, 1
412 } ;
413
414static const YY_CHAR yy_meta[29] =
415 { 0,
416 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
417 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
418 1, 1, 1, 1, 1, 1, 1, 1
419 } ;
420
421static const flex_int16_t yy_base[107] =
422 { 0,
423 0, 0, 115, 116, 112, 116, 108, 107, 116, 108,
424 99, 12, 22, 16, 90, 83, 87, 81, 85, 12,
425 92, 24, 101, 97, 98, 116, 89, 79, 74, 80,
426 78, 69, 73, 18, 75, 84, 74, 69, 68, 73,
427 64, 62, 61, 69, 63, 73, 116, 73, 60, 62,
428 57, 116, 116, 52, 64, 54, 63, 49, 116, 116,
429 53, 57, 45, 116, 56, 24, 116, 57, 45, 116,
430 58, 41, 42, 35, 53, 116, 37, 116, 38, 35,
431 116, 46, 116, 45, 34, 116, 31, 24, 116, 116,
432 35, 116, 44, 116, 40, 116, 30, 35, 116, 116,
433
434 116, 116, 17, 116, 116, 32
435 } ;
436
437static const flex_int16_t yy_def[107] =
438 { 0,
439 105, 1, 105, 105, 105, 105, 105, 105, 105, 106,
440 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
441 105, 105, 105, 105, 106, 105, 105, 105, 105, 105,
442 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
443 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
444 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
445 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
446 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
447 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
448 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
449
450 105, 105, 105, 105, 0, 105
451 } ;
452
453static const flex_int16_t yy_nxt[145] =
454 { 0,
455 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
456 14, 4, 4, 4, 15, 16, 17, 18, 19, 4,
457 20, 21, 22, 4, 4, 4, 4, 4, 28, 30,
458 32, 39, 25, 40, 29, 43, 41, 44, 54, 104,
459 33, 31, 97, 55, 81, 82, 103, 45, 46, 102,
460 98, 101, 100, 99, 96, 95, 94, 93, 92, 91,
461 90, 89, 88, 87, 86, 85, 84, 83, 80, 79,
462 78, 77, 76, 75, 74, 73, 72, 71, 70, 69,
463 68, 67, 66, 65, 64, 63, 62, 61, 60, 59,
464 58, 57, 56, 53, 52, 51, 50, 49, 48, 47,
465
466 26, 24, 23, 42, 38, 37, 36, 35, 34, 27,
467 26, 24, 24, 23, 105, 3, 105, 105, 105, 105,
468 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
469 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
470 105, 105, 105, 105
471 } ;
472
473static const flex_int16_t yy_chk[145] =
474 { 0,
475 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
476 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
477 1, 1, 1, 1, 1, 1, 1, 1, 12, 13,
478 14, 20, 106, 20, 12, 22, 20, 22, 34, 103,
479 14, 13, 88, 34, 66, 66, 98, 22, 22, 97,
480 88, 95, 93, 91, 87, 85, 84, 82, 80, 79,
481 77, 75, 74, 73, 72, 71, 69, 68, 65, 63,
482 62, 61, 58, 57, 56, 55, 54, 51, 50, 49,
483 48, 46, 45, 44, 43, 42, 41, 40, 39, 38,
484 37, 36, 35, 33, 32, 31, 30, 29, 28, 27,
485
486 25, 24, 23, 21, 19, 18, 17, 16, 15, 11,
487 10, 8, 7, 5, 3, 105, 105, 105, 105, 105,
488 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
489 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
490 105, 105, 105, 105
491 } ;
492
493static yy_state_type yy_last_accepting_state;
494static char *yy_last_accepting_cpos;
495
496extern int yy_flex_debug;
497int yy_flex_debug = 0;
498
499/* The intent behind this definition is that it'll catch
500 * any uses of REJECT which flex missed.
501 */
502#define REJECT reject_used_but_not_detected
503#define yymore() yymore_used_but_not_detected
504#define YY_MORE_ADJ 0
505#define YY_RESTORE_YY_MORE_OFFSET
506char *yytext;
507#line 1 "vmlex.l"
508#line 2 "vmlex.l"
509#include "vmparse.tab.h"
510#include <stdlib.h>
511
512#ifndef __GNUC__
513#define YY_NO_UNISTD_H
514#endif
515#line 515 "lex.yy.c"
516#line 516 "lex.yy.c"
517
518#define INITIAL 0
519
520#ifndef YY_NO_UNISTD_H
521/* Special case for "unistd.h", since it is non-ANSI. We include it way
522 * down here because we want the user's section 1 to have been scanned first.
523 * The user has a chance to override it with an option.
524 */
525#include <unistd.h>
526#endif
527
528#ifndef YY_EXTRA_TYPE
529#define YY_EXTRA_TYPE void *
530#endif
531
532static int yy_init_globals ( void );
533
534/* Accessor methods to globals.
535 These are made visible to non-reentrant scanners for convenience. */
536
537int yylex_destroy ( void );
538
539int yyget_debug ( void );
540
541void yyset_debug ( int debug_flag );
542
543YY_EXTRA_TYPE yyget_extra ( void );
544
545void yyset_extra ( YY_EXTRA_TYPE user_defined );
546
547FILE *yyget_in ( void );
548
549void yyset_in ( FILE * _in_str );
550
551FILE *yyget_out ( void );
552
553void yyset_out ( FILE * _out_str );
554
555 int yyget_leng ( void );
556
557char *yyget_text ( void );
558
559int yyget_lineno ( void );
560
561void yyset_lineno ( int _line_number );
562
563/* Macros after this point can all be overridden by user definitions in
564 * section 1.
565 */
566
567#ifndef YY_SKIP_YYWRAP
568#ifdef __cplusplus
569extern "C" int yywrap ( void );
570#else
571extern int yywrap ( void );
572#endif
573#endif
574
575#ifndef YY_NO_UNPUT
576
577 static void yyunput ( int c, char *buf_ptr );
578
579#endif
580
581#ifndef yytext_ptr
582static void yy_flex_strncpy ( char *, const char *, int );
583#endif
584
585#ifdef YY_NEED_STRLEN
586static int yy_flex_strlen ( const char * );
587#endif
588
589#ifndef YY_NO_INPUT
590#ifdef __cplusplus
591static int yyinput ( void );
592#else
593static int input ( void );
594#endif
595
596#endif
597
598/* Amount of stuff to slurp up with each read. */
599#ifndef YY_READ_BUF_SIZE
600#ifdef __ia64__
601/* On IA-64, the buffer size is 16k, not 8k */
602#define YY_READ_BUF_SIZE 16384
603#else
604#define YY_READ_BUF_SIZE 8192
605#endif /* __ia64__ */
606#endif
607
608/* Copy whatever the last rule matched to the standard output. */
609#ifndef ECHO
610/* This used to be an fputs(), but since the string might contain NUL's,
611 * we now use fwrite().
612 */
613#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
614#endif
615
616/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
617 * is returned in "result".
618 */
619#ifndef YY_INPUT
620#define YY_INPUT(buf,result,max_size) \
621 if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
622 { \
623 int c = '*'; \
624 int n; \
625 for ( n = 0; n < max_size && \
626 (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
627 buf[n] = (char) c; \
628 if ( c == '\n' ) \
629 buf[n++] = (char) c; \
630 if ( c == EOF && ferror( yyin ) ) \
631 YY_FATAL_ERROR( "input in flex scanner failed" ); \
632 result = n; \
633 } \
634 else \
635 { \
636 errno=0; \
637 while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
638 { \
639 if( errno != EINTR) \
640 { \
641 YY_FATAL_ERROR( "input in flex scanner failed" ); \
642 break; \
643 } \
644 errno=0; \
645 clearerr(yyin); \
646 } \
647 }\
648\
649
650#endif
651
652/* No semi-colon after return; correct usage is to write "yyterminate();" -
653 * we don't want an extra ';' after the "return" because that will cause
654 * some compilers to complain about unreachable statements.
655 */
656#ifndef yyterminate
657#define yyterminate() return YY_NULL
658#endif
659
660/* Number of entries by which start-condition stack grows. */
661#ifndef YY_START_STACK_INCR
662#define YY_START_STACK_INCR 25
663#endif
664
665/* Report a fatal error. */
666#ifndef YY_FATAL_ERROR
667#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
668#endif
669
670/* end tables serialization structures and prototypes */
671
672/* Default declaration of generated scanner - a define so the user can
673 * easily add parameters.
674 */
675#ifndef YY_DECL
676#define YY_DECL_IS_OURS 1
677
678extern int yylex (void);
679
680#define YY_DECL int yylex (void)
681#endif /* !YY_DECL */
682
683/* Code executed at the beginning of each rule, after yytext and yyleng
684 * have been set up.
685 */
686#ifndef YY_USER_ACTION
687#define YY_USER_ACTION
688#endif
689
690/* Code executed at the end of each rule. */
691#ifndef YY_BREAK
692#define YY_BREAK /*LINTED*/break;
693#endif
694
695#define YY_RULE_SETUP \
696 YY_USER_ACTION
697
698/** The main scanner function which does all the work.
699 */
700YY_DECL
701{
702 yy_state_type yy_current_state;
703 char *yy_cp, *yy_bp;
704 int yy_act;
705
706 if ( !(yy_init) )
707 {
708 (yy_init) = 1;
709
710#ifdef YY_USER_INIT
711 YY_USER_INIT;
712#endif
713
714 if ( ! (yy_start) )
715 (yy_start) = 1; /* first start state */
716
717 if ( ! yyin )
718 yyin = stdin;
719
720 if ( ! yyout )
721 yyout = stdout;
722
723 if ( ! YY_CURRENT_BUFFER ) {
724 yyensure_buffer_stack ();
725 YY_CURRENT_BUFFER_LVALUE =
726 yy_create_buffer( yyin, YY_BUF_SIZE );
727 }
728
729 yy_load_buffer_state( );
730 }
731
732 {
733#line 17 "vmlex.l"
734
735
736#line 736 "lex.yy.c"
737
738 while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
739 {
740 yy_cp = (yy_c_buf_p);
741
742 /* Support of yytext. */
743 *yy_cp = (yy_hold_char);
744
745 /* yy_bp points to the position in yy_ch_buf of the start of
746 * the current run.
747 */
748 yy_bp = yy_cp;
749
750 yy_current_state = (yy_start);
751yy_match:
752 do
753 {
754 YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
755 if ( yy_accept[yy_current_state] )
756 {
757 (yy_last_accepting_state) = yy_current_state;
758 (yy_last_accepting_cpos) = yy_cp;
759 }
760 while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
761 {
762 yy_current_state = (int) yy_def[yy_current_state];
763 if ( yy_current_state >= 106 )
764 yy_c = yy_meta[yy_c];
765 }
766 yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
767 ++yy_cp;
768 }
769 while ( yy_base[yy_current_state] != 116 );
770
771yy_find_action:
772 yy_act = yy_accept[yy_current_state];
773 if ( yy_act == 0 )
774 { /* have to back up */
775 yy_cp = (yy_last_accepting_cpos);
776 yy_current_state = (yy_last_accepting_state);
777 yy_act = yy_accept[yy_current_state];
778 }
779
780 YY_DO_BEFORE_ACTION;
781
782do_action: /* This label is used only to access EOF actions. */
783
784 switch ( yy_act )
785 { /* beginning of action switch */
786 case 0: /* must back up */
787 /* undo the effects of YY_DO_BEFORE_ACTION */
788 *yy_cp = (yy_hold_char);
789 yy_cp = (yy_last_accepting_cpos);
790 yy_current_state = (yy_last_accepting_state);
791 goto yy_find_action;
792
793case 1:
794/* rule 1 can match eol */
795YY_RULE_SETUP
796#line 19 "vmlex.l"
797
798 YY_BREAK
799case 2:
800/* rule 2 can match eol */
801YY_RULE_SETUP
802#line 20 "vmlex.l"
803
804 YY_BREAK
805case 3:
806YY_RULE_SETUP
807#line 21 "vmlex.l"
808
809 YY_BREAK
810case 4:
811YY_RULE_SETUP
812#line 22 "vmlex.l"
813{ yylval = atoi(yytext); return T_INT; }
814 YY_BREAK
815case 5:
816YY_RULE_SETUP
817#line 24 "vmlex.l"
818{ return T_COLON; }
819 YY_BREAK
820case 6:
821YY_RULE_SETUP
822#line 26 "vmlex.l"
823{ return T_CALL; }
824 YY_BREAK
825case 7:
826YY_RULE_SETUP
827#line 27 "vmlex.l"
828{ return T_RETURN; }
829 YY_BREAK
830case 8:
831YY_RULE_SETUP
832#line 28 "vmlex.l"
833{ return T_LOADB; }
834 YY_BREAK
835case 9:
836YY_RULE_SETUP
837#line 29 "vmlex.l"
838{ return T_STOREB; }
839 YY_BREAK
840case 10:
841YY_RULE_SETUP
842#line 30 "vmlex.l"
843{ return T_SHIFT; }
844 YY_BREAK
845case 11:
846YY_RULE_SETUP
847#line 32 "vmlex.l"
848{ return T_SET; }
849 YY_BREAK
850case 12:
851YY_RULE_SETUP
852#line 33 "vmlex.l"
853{ return T_STOP; }
854 YY_BREAK
855case 13:
856YY_RULE_SETUP
857#line 34 "vmlex.l"
858{ return T_LOAD; }
859 YY_BREAK
860case 14:
861YY_RULE_SETUP
862#line 35 "vmlex.l"
863{ return T_STORE; }
864 YY_BREAK
865case 15:
866YY_RULE_SETUP
867#line 36 "vmlex.l"
868{ return T_BLOAD; }
869 YY_BREAK
870case 16:
871YY_RULE_SETUP
872#line 37 "vmlex.l"
873{ return T_BSTORE; }
874 YY_BREAK
875case 17:
876YY_RULE_SETUP
877#line 38 "vmlex.l"
878{ return T_PUSH; }
879 YY_BREAK
880case 18:
881YY_RULE_SETUP
882#line 39 "vmlex.l"
883{ return T_POP; }
884 YY_BREAK
885case 19:
886YY_RULE_SETUP
887#line 40 "vmlex.l"
888{ return T_DUP; }
889 YY_BREAK
890case 20:
891YY_RULE_SETUP
892#line 41 "vmlex.l"
893{ return T_INVERT; }
894 YY_BREAK
895case 21:
896YY_RULE_SETUP
897#line 42 "vmlex.l"
898{ return T_ADD; }
899 YY_BREAK
900case 22:
901YY_RULE_SETUP
902#line 43 "vmlex.l"
903{ return T_SUB; }
904 YY_BREAK
905case 23:
906YY_RULE_SETUP
907#line 44 "vmlex.l"
908{ return T_MULT; }
909 YY_BREAK
910case 24:
911YY_RULE_SETUP
912#line 45 "vmlex.l"
913{ return T_DIV; }
914 YY_BREAK
915case 25:
916YY_RULE_SETUP
917#line 46 "vmlex.l"
918{ return T_COMPARE; }
919 YY_BREAK
920case 26:
921YY_RULE_SETUP
922#line 47 "vmlex.l"
923{ return T_JUMP; }
924 YY_BREAK
925case 27:
926YY_RULE_SETUP
927#line 48 "vmlex.l"
928{ return T_JUMP_YES; }
929 YY_BREAK
930case 28:
931YY_RULE_SETUP
932#line 49 "vmlex.l"
933{ return T_JUMP_NO; }
934 YY_BREAK
935case 29:
936YY_RULE_SETUP
937#line 50 "vmlex.l"
938{ return T_INPUT; }
939 YY_BREAK
940case 30:
941YY_RULE_SETUP
942#line 51 "vmlex.l"
943{ return T_PRINT; }
944 YY_BREAK
945case 31:
946YY_RULE_SETUP
947#line 52 "vmlex.l"
948{ return T_NOP; }
949 YY_BREAK
950case YY_STATE_EOF(INITIAL):
951#line 54 "vmlex.l"
952{ yyterminate(); }
953 YY_BREAK
954case 32:
955YY_RULE_SETUP
956#line 56 "vmlex.l"
957ECHO;
958 YY_BREAK
959#line 959 "lex.yy.c"
960
961 case YY_END_OF_BUFFER:
962 {
963 /* Amount of text matched not including the EOB char. */
964 int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
965
966 /* Undo the effects of YY_DO_BEFORE_ACTION. */
967 *yy_cp = (yy_hold_char);
968 YY_RESTORE_YY_MORE_OFFSET
969
970 if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
971 {
972 /* We're scanning a new file or input source. It's
973 * possible that this happened because the user
974 * just pointed yyin at a new source and called
975 * yylex(). If so, then we have to assure
976 * consistency between YY_CURRENT_BUFFER and our
977 * globals. Here is the right place to do so, because
978 * this is the first action (other than possibly a
979 * back-up) that will match for the new input source.
980 */
981 (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
982 YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
983 YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
984 }
985
986 /* Note that here we test for yy_c_buf_p "<=" to the position
987 * of the first EOB in the buffer, since yy_c_buf_p will
988 * already have been incremented past the NUL character
989 * (since all states make transitions on EOB to the
990 * end-of-buffer state). Contrast this with the test
991 * in input().
992 */
993 if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
994 { /* This was really a NUL. */
995 yy_state_type yy_next_state;
996
997 (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
998
999 yy_current_state = yy_get_previous_state( );
1000
1001 /* Okay, we're now positioned to make the NUL
1002 * transition. We couldn't have
1003 * yy_get_previous_state() go ahead and do it
1004 * for us because it doesn't know how to deal
1005 * with the possibility of jamming (and we don't
1006 * want to build jamming into it because then it
1007 * will run more slowly).
1008 */
1009
1010 yy_next_state = yy_try_NUL_trans( yy_current_state );
1011
1012 yy_bp = (yytext_ptr) + YY_MORE_ADJ;
1013
1014 if ( yy_next_state )
1015 {
1016 /* Consume the NUL. */
1017 yy_cp = ++(yy_c_buf_p);
1018 yy_current_state = yy_next_state;
1019 goto yy_match;
1020 }
1021
1022 else
1023 {
1024 yy_cp = (yy_c_buf_p);
1025 goto yy_find_action;
1026 }
1027 }
1028
1029 else switch ( yy_get_next_buffer( ) )
1030 {
1031 case EOB_ACT_END_OF_FILE:
1032 {
1033 (yy_did_buffer_switch_on_eof) = 0;
1034
1035 if ( yywrap( ) )
1036 {
1037 /* Note: because we've taken care in
1038 * yy_get_next_buffer() to have set up
1039 * yytext, we can now set up
1040 * yy_c_buf_p so that if some total
1041 * hoser (like flex itself) wants to
1042 * call the scanner after we return the
1043 * YY_NULL, it'll still work - another
1044 * YY_NULL will get returned.
1045 */
1046 (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
1047
1048 yy_act = YY_STATE_EOF(YY_START);
1049 goto do_action;
1050 }
1051
1052 else
1053 {
1054 if ( ! (yy_did_buffer_switch_on_eof) )
1055 YY_NEW_FILE;
1056 }
1057 break;
1058 }
1059
1060 case EOB_ACT_CONTINUE_SCAN:
1061 (yy_c_buf_p) =
1062 (yytext_ptr) + yy_amount_of_matched_text;
1063
1064 yy_current_state = yy_get_previous_state( );
1065
1066 yy_cp = (yy_c_buf_p);
1067 yy_bp = (yytext_ptr) + YY_MORE_ADJ;
1068 goto yy_match;
1069
1070 case EOB_ACT_LAST_MATCH:
1071 (yy_c_buf_p) =
1072 &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
1073
1074 yy_current_state = yy_get_previous_state( );
1075
1076 yy_cp = (yy_c_buf_p);
1077 yy_bp = (yytext_ptr) + YY_MORE_ADJ;
1078 goto yy_find_action;
1079 }
1080 break;
1081 }
1082
1083 default:
1084 YY_FATAL_ERROR(
1085 "fatal flex scanner internal error--no action found" );
1086 } /* end of action switch */
1087 } /* end of scanning one token */
1088 } /* end of user's declarations */
1089} /* end of yylex */
1090
1091/* yy_get_next_buffer - try to read in a new buffer
1092 *
1093 * Returns a code representing an action:
1094 * EOB_ACT_LAST_MATCH -
1095 * EOB_ACT_CONTINUE_SCAN - continue scanning from current position
1096 * EOB_ACT_END_OF_FILE - end of file
1097 */
1098static int yy_get_next_buffer (void)
1099{
1100 char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
1101 char *source = (yytext_ptr);
1102 int number_to_move, i;
1103 int ret_val;
1104
1105 if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
1106 YY_FATAL_ERROR(
1107 "fatal flex scanner internal error--end of buffer missed" );
1108
1109 if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
1110 { /* Don't try to fill the buffer, so this is an EOF. */
1111 if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
1112 {
1113 /* We matched a single character, the EOB, so
1114 * treat this as a final EOF.
1115 */
1116 return EOB_ACT_END_OF_FILE;
1117 }
1118
1119 else
1120 {
1121 /* We matched some text prior to the EOB, first
1122 * process it.
1123 */
1124 return EOB_ACT_LAST_MATCH;
1125 }
1126 }
1127
1128 /* Try to read more data. */
1129
1130 /* First move last chars to start of buffer. */
1131 number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1);
1132
1133 for ( i = 0; i < number_to_move; ++i )
1134 *(dest++) = *(source++);
1135
1136 if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
1137 /* don't do the read, it's not guaranteed to return an EOF,
1138 * just force an EOF
1139 */
1140 YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
1141
1142 else
1143 {
1144 int num_to_read =
1145 YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
1146
1147 while ( num_to_read <= 0 )
1148 { /* Not enough room in the buffer - grow it. */
1149
1150 /* just a shorter name for the current buffer */
1151 YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
1152
1153 int yy_c_buf_p_offset =
1154 (int) ((yy_c_buf_p) - b->yy_ch_buf);
1155
1156 if ( b->yy_is_our_buffer )
1157 {
1158 int new_size = b->yy_buf_size * 2;
1159
1160 if ( new_size <= 0 )
1161 b->yy_buf_size += b->yy_buf_size / 8;
1162 else
1163 b->yy_buf_size *= 2;
1164
1165 b->yy_ch_buf = (char *)
1166 /* Include room in for 2 EOB chars. */
1167 yyrealloc( (void *) b->yy_ch_buf,
1168 (yy_size_t) (b->yy_buf_size + 2) );
1169 }
1170 else
1171 /* Can't grow it, we don't own it. */
1172 b->yy_ch_buf = NULL;
1173
1174 if ( ! b->yy_ch_buf )
1175 YY_FATAL_ERROR(
1176 "fatal error - scanner input buffer overflow" );
1177
1178 (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
1179
1180 num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
1181 number_to_move - 1;
1182
1183 }
1184
1185 if ( num_to_read > YY_READ_BUF_SIZE )
1186 num_to_read = YY_READ_BUF_SIZE;
1187
1188 /* Read in more data. */
1189 YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
1190 (yy_n_chars), num_to_read );
1191
1192 YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
1193 }
1194
1195 if ( (yy_n_chars) == 0 )
1196 {
1197 if ( number_to_move == YY_MORE_ADJ )
1198 {
1199 ret_val = EOB_ACT_END_OF_FILE;
1200 yyrestart( yyin );
1201 }
1202
1203 else
1204 {
1205 ret_val = EOB_ACT_LAST_MATCH;
1206 YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
1207 YY_BUFFER_EOF_PENDING;
1208 }
1209 }
1210
1211 else
1212 ret_val = EOB_ACT_CONTINUE_SCAN;
1213
1214 if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
1215 /* Extend the array by 50%, plus the number we really need. */
1216 int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
1217 YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
1218 (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size );
1219 if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
1220 YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
1221 /* "- 2" to take care of EOB's */
1222 YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
1223 }
1224
1225 (yy_n_chars) += number_to_move;
1226 YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
1227 YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
1228
1229 (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
1230
1231 return ret_val;
1232}
1233
1234/* yy_get_previous_state - get the state just before the EOB char was reached */
1235
1236 static yy_state_type yy_get_previous_state (void)
1237{
1238 yy_state_type yy_current_state;
1239 char *yy_cp;
1240
1241 yy_current_state = (yy_start);
1242
1243 for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
1244 {
1245 YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
1246 if ( yy_accept[yy_current_state] )
1247 {
1248 (yy_last_accepting_state) = yy_current_state;
1249 (yy_last_accepting_cpos) = yy_cp;
1250 }
1251 while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
1252 {
1253 yy_current_state = (int) yy_def[yy_current_state];
1254 if ( yy_current_state >= 106 )
1255 yy_c = yy_meta[yy_c];
1256 }
1257 yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
1258 }
1259
1260 return yy_current_state;
1261}
1262
1263/* yy_try_NUL_trans - try to make a transition on the NUL character
1264 *
1265 * synopsis
1266 * next_state = yy_try_NUL_trans( current_state );
1267 */
1268 static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
1269{
1270 int yy_is_jam;
1271 char *yy_cp = (yy_c_buf_p);
1272
1273 YY_CHAR yy_c = 1;
1274 if ( yy_accept[yy_current_state] )
1275 {
1276 (yy_last_accepting_state) = yy_current_state;
1277 (yy_last_accepting_cpos) = yy_cp;
1278 }
1279 while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
1280 {
1281 yy_current_state = (int) yy_def[yy_current_state];
1282 if ( yy_current_state >= 106 )
1283 yy_c = yy_meta[yy_c];
1284 }
1285 yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
1286 yy_is_jam = (yy_current_state == 105);
1287
1288 return yy_is_jam ? 0 : yy_current_state;
1289}
1290
1291#ifndef YY_NO_UNPUT
1292
1293 static void yyunput (int c, char * yy_bp )
1294{
1295 char *yy_cp;
1296
1297 yy_cp = (yy_c_buf_p);
1298
1299 /* undo effects of setting up yytext */
1300 *yy_cp = (yy_hold_char);
1301
1302 if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
1303 { /* need to shift things up to make room */
1304 /* +2 for EOB chars. */
1305 int number_to_move = (yy_n_chars) + 2;
1306 char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
1307 YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
1308 char *source =
1309 &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
1310
1311 while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
1312 *--dest = *--source;
1313
1314 yy_cp += (int) (dest - source);
1315 yy_bp += (int) (dest - source);
1316 YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
1317 (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
1318
1319 if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
1320 YY_FATAL_ERROR( "flex scanner push-back overflow" );
1321 }
1322
1323 *--yy_cp = (char) c;
1324
1325 (yytext_ptr) = yy_bp;
1326 (yy_hold_char) = *yy_cp;
1327 (yy_c_buf_p) = yy_cp;
1328}
1329
1330#endif
1331
1332#ifndef YY_NO_INPUT
1333#ifdef __cplusplus
1334 static int yyinput (void)
1335#else
1336 static int input (void)
1337#endif
1338
1339{
1340 int c;
1341
1342 *(yy_c_buf_p) = (yy_hold_char);
1343
1344 if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
1345 {
1346 /* yy_c_buf_p now points to the character we want to return.
1347 * If this occurs *before* the EOB characters, then it's a
1348 * valid NUL; if not, then we've hit the end of the buffer.
1349 */
1350 if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
1351 /* This was really a NUL. */
1352 *(yy_c_buf_p) = '\0';
1353
1354 else
1355 { /* need more input */
1356 int offset = (int) ((yy_c_buf_p) - (yytext_ptr));
1357 ++(yy_c_buf_p);
1358
1359 switch ( yy_get_next_buffer( ) )
1360 {
1361 case EOB_ACT_LAST_MATCH:
1362 /* This happens because yy_g_n_b()
1363 * sees that we've accumulated a
1364 * token and flags that we need to
1365 * try matching the token before
1366 * proceeding. But for input(),
1367 * there's no matching to consider.
1368 * So convert the EOB_ACT_LAST_MATCH
1369 * to EOB_ACT_END_OF_FILE.
1370 */
1371
1372 /* Reset buffer status. */
1373 yyrestart( yyin );
1374
1375 /*FALLTHROUGH*/
1376
1377 case EOB_ACT_END_OF_FILE:
1378 {
1379 if ( yywrap( ) )
1380 return 0;
1381
1382 if ( ! (yy_did_buffer_switch_on_eof) )
1383 YY_NEW_FILE;
1384#ifdef __cplusplus
1385 return yyinput();
1386#else
1387 return input();
1388#endif
1389 }
1390
1391 case EOB_ACT_CONTINUE_SCAN:
1392 (yy_c_buf_p) = (yytext_ptr) + offset;
1393 break;
1394 }
1395 }
1396 }
1397
1398 c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
1399 *(yy_c_buf_p) = '\0'; /* preserve yytext */
1400 (yy_hold_char) = *++(yy_c_buf_p);
1401
1402 return c;
1403}
1404#endif /* ifndef YY_NO_INPUT */
1405
1406/** Immediately switch to a different input stream.
1407 * @param input_file A readable stream.
1408 *
1409 * @note This function does not reset the start condition to @c INITIAL .
1410 */
1411 void yyrestart (FILE * input_file )
1412{
1413
1414 if ( ! YY_CURRENT_BUFFER ){
1415 yyensure_buffer_stack ();
1416 YY_CURRENT_BUFFER_LVALUE =
1417 yy_create_buffer( yyin, YY_BUF_SIZE );
1418 }
1419
1420 yy_init_buffer( YY_CURRENT_BUFFER, input_file );
1421 yy_load_buffer_state( );
1422}
1423
1424/** Switch to a different input buffer.
1425 * @param new_buffer The new input buffer.
1426 *
1427 */
1428 void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
1429{
1430
1431 /* TODO. We should be able to replace this entire function body
1432 * with
1433 * yypop_buffer_state();
1434 * yypush_buffer_state(new_buffer);
1435 */
1436 yyensure_buffer_stack ();
1437 if ( YY_CURRENT_BUFFER == new_buffer )
1438 return;
1439
1440 if ( YY_CURRENT_BUFFER )
1441 {
1442 /* Flush out information for old buffer. */
1443 *(yy_c_buf_p) = (yy_hold_char);
1444 YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
1445 YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
1446 }
1447
1448 YY_CURRENT_BUFFER_LVALUE = new_buffer;
1449 yy_load_buffer_state( );
1450
1451 /* We don't actually know whether we did this switch during
1452 * EOF (yywrap()) processing, but the only time this flag
1453 * is looked at is after yywrap() is called, so it's safe
1454 * to go ahead and always set it.
1455 */
1456 (yy_did_buffer_switch_on_eof) = 1;
1457}
1458
1459static void yy_load_buffer_state (void)
1460{
1461 (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
1462 (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
1463 yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
1464 (yy_hold_char) = *(yy_c_buf_p);
1465}
1466
1467/** Allocate and initialize an input buffer state.
1468 * @param file A readable stream.
1469 * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
1470 *
1471 * @return the allocated buffer state.
1472 */
1473 YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
1474{
1475 YY_BUFFER_STATE b;
1476
1477 b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
1478 if ( ! b )
1479 YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
1480
1481 b->yy_buf_size = size;
1482
1483 /* yy_ch_buf has to be 2 characters longer than the size given because
1484 * we need to put in 2 end-of-buffer characters.
1485 */
1486 b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) );
1487 if ( ! b->yy_ch_buf )
1488 YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
1489
1490 b->yy_is_our_buffer = 1;
1491
1492 yy_init_buffer( b, file );
1493
1494 return b;
1495}
1496
1497/** Destroy the buffer.
1498 * @param b a buffer created with yy_create_buffer()
1499 *
1500 */
1501 void yy_delete_buffer (YY_BUFFER_STATE b )
1502{
1503
1504 if ( ! b )
1505 return;
1506
1507 if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
1508 YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
1509
1510 if ( b->yy_is_our_buffer )
1511 yyfree( (void *) b->yy_ch_buf );
1512
1513 yyfree( (void *) b );
1514}
1515
1516/* Initializes or reinitializes a buffer.
1517 * This function is sometimes called more than once on the same buffer,
1518 * such as during a yyrestart() or at EOF.
1519 */
1520 static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
1521
1522{
1523 int oerrno = errno;
1524
1525 yy_flush_buffer( b );
1526
1527 b->yy_input_file = file;
1528 b->yy_fill_buffer = 1;
1529
1530 /* If b is the current buffer, then yy_init_buffer was _probably_
1531 * called from yyrestart() or through yy_get_next_buffer.
1532 * In that case, we don't want to reset the lineno or column.
1533 */
1534 if (b != YY_CURRENT_BUFFER){
1535 b->yy_bs_lineno = 1;
1536 b->yy_bs_column = 0;
1537 }
1538
1539 b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
1540
1541 errno = oerrno;
1542}
1543
1544/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
1545 * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
1546 *
1547 */
1548 void yy_flush_buffer (YY_BUFFER_STATE b )
1549{
1550 if ( ! b )
1551 return;
1552
1553 b->yy_n_chars = 0;
1554
1555 /* We always need two end-of-buffer characters. The first causes
1556 * a transition to the end-of-buffer state. The second causes
1557 * a jam in that state.
1558 */
1559 b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
1560 b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
1561
1562 b->yy_buf_pos = &b->yy_ch_buf[0];
1563
1564 b->yy_at_bol = 1;
1565 b->yy_buffer_status = YY_BUFFER_NEW;
1566
1567 if ( b == YY_CURRENT_BUFFER )
1568 yy_load_buffer_state( );
1569}
1570
1571/** Pushes the new state onto the stack. The new state becomes
1572 * the current state. This function will allocate the stack
1573 * if necessary.
1574 * @param new_buffer The new state.
1575 *
1576 */
1577void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
1578{
1579 if (new_buffer == NULL)
1580 return;
1581
1582 yyensure_buffer_stack();
1583
1584 /* This block is copied from yy_switch_to_buffer. */
1585 if ( YY_CURRENT_BUFFER )
1586 {
1587 /* Flush out information for old buffer. */
1588 *(yy_c_buf_p) = (yy_hold_char);
1589 YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
1590 YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
1591 }
1592
1593 /* Only push if top exists. Otherwise, replace top. */
1594 if (YY_CURRENT_BUFFER)
1595 (yy_buffer_stack_top)++;
1596 YY_CURRENT_BUFFER_LVALUE = new_buffer;
1597
1598 /* copied from yy_switch_to_buffer. */
1599 yy_load_buffer_state( );
1600 (yy_did_buffer_switch_on_eof) = 1;
1601}
1602
1603/** Removes and deletes the top of the stack, if present.
1604 * The next element becomes the new top.
1605 *
1606 */
1607void yypop_buffer_state (void)
1608{
1609 if (!YY_CURRENT_BUFFER)
1610 return;
1611
1612 yy_delete_buffer(YY_CURRENT_BUFFER );
1613 YY_CURRENT_BUFFER_LVALUE = NULL;
1614 if ((yy_buffer_stack_top) > 0)
1615 --(yy_buffer_stack_top);
1616
1617 if (YY_CURRENT_BUFFER) {
1618 yy_load_buffer_state( );
1619 (yy_did_buffer_switch_on_eof) = 1;
1620 }
1621}
1622
1623/* Allocates the stack if it does not exist.
1624 * Guarantees space for at least one push.
1625 */
1626static void yyensure_buffer_stack (void)
1627{
1628 yy_size_t num_to_alloc;
1629
1630 if (!(yy_buffer_stack)) {
1631
1632 /* First allocation is just for 2 elements, since we don't know if this
1633 * scanner will even need a stack. We use 2 instead of 1 to avoid an
1634 * immediate realloc on the next call.
1635 */
1636 num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
1637 (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
1638 (num_to_alloc * sizeof(struct yy_buffer_state*)
1639 );
1640 if ( ! (yy_buffer_stack) )
1641 YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
1642
1643 memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
1644
1645 (yy_buffer_stack_max) = num_to_alloc;
1646 (yy_buffer_stack_top) = 0;
1647 return;
1648 }
1649
1650 if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
1651
1652 /* Increase the buffer to prepare for a possible push. */
1653 yy_size_t grow_size = 8 /* arbitrary grow size */;
1654
1655 num_to_alloc = (yy_buffer_stack_max) + grow_size;
1656 (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
1657 ((yy_buffer_stack),
1658 num_to_alloc * sizeof(struct yy_buffer_state*)
1659 );
1660 if ( ! (yy_buffer_stack) )
1661 YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
1662
1663 /* zero only the new slots.*/
1664 memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
1665 (yy_buffer_stack_max) = num_to_alloc;
1666 }
1667}
1668
1669/** Setup the input buffer state to scan directly from a user-specified character buffer.
1670 * @param base the character buffer
1671 * @param size the size in bytes of the character buffer
1672 *
1673 * @return the newly allocated buffer state object.
1674 */
1675YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
1676{
1677 YY_BUFFER_STATE b;
1678
1679 if ( size < 2 ||
1680 base[size-2] != YY_END_OF_BUFFER_CHAR ||
1681 base[size-1] != YY_END_OF_BUFFER_CHAR )
1682 /* They forgot to leave room for the EOB's. */
1683 return NULL;
1684
1685 b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) );
1686 if ( ! b )
1687 YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
1688
1689 b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
1690 b->yy_buf_pos = b->yy_ch_buf = base;
1691 b->yy_is_our_buffer = 0;
1692 b->yy_input_file = NULL;
1693 b->yy_n_chars = b->yy_buf_size;
1694 b->yy_is_interactive = 0;
1695 b->yy_at_bol = 1;
1696 b->yy_fill_buffer = 0;
1697 b->yy_buffer_status = YY_BUFFER_NEW;
1698
1699 yy_switch_to_buffer( b );
1700
1701 return b;
1702}
1703
1704/** Setup the input buffer state to scan a string. The next call to yylex() will
1705 * scan from a @e copy of @a str.
1706 * @param yystr a NUL-terminated string to scan
1707 *
1708 * @return the newly allocated buffer state object.
1709 * @note If you want to scan bytes that may contain NUL values, then use
1710 * yy_scan_bytes() instead.
1711 */
1712YY_BUFFER_STATE yy_scan_string (const char * yystr )
1713{
1714
1715 return yy_scan_bytes( yystr, (int) strlen(yystr) );
1716}
1717
1718/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
1719 * scan from a @e copy of @a bytes.
1720 * @param yybytes the byte buffer to scan
1721 * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
1722 *
1723 * @return the newly allocated buffer state object.
1724 */
1725YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len )
1726{
1727 YY_BUFFER_STATE b;
1728 char *buf;
1729 yy_size_t n;
1730 int i;
1731
1732 /* Get memory for full buffer, including space for trailing EOB's. */
1733 n = (yy_size_t) (_yybytes_len + 2);
1734 buf = (char *) yyalloc( n );
1735 if ( ! buf )
1736 YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
1737
1738 for ( i = 0; i < _yybytes_len; ++i )
1739 buf[i] = yybytes[i];
1740
1741 buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
1742
1743 b = yy_scan_buffer( buf, n );
1744 if ( ! b )
1745 YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
1746
1747 /* It's okay to grow etc. this buffer, and we should throw it
1748 * away when we're done.
1749 */
1750 b->yy_is_our_buffer = 1;
1751
1752 return b;
1753}
1754
1755#ifndef YY_EXIT_FAILURE
1756#define YY_EXIT_FAILURE 2
1757#endif
1758
1759static void yynoreturn yy_fatal_error (const char* msg )
1760{
1761 fprintf( stderr, "%s\n", msg );
1762 exit( YY_EXIT_FAILURE );
1763}
1764
1765/* Redefine yyless() so it works in section 3 code. */
1766
1767#undef yyless
1768#define yyless(n) \
1769 do \
1770 { \
1771 /* Undo effects of setting up yytext. */ \
1772 int yyless_macro_arg = (n); \
1773 YY_LESS_LINENO(yyless_macro_arg);\
1774 yytext[yyleng] = (yy_hold_char); \
1775 (yy_c_buf_p) = yytext + yyless_macro_arg; \
1776 (yy_hold_char) = *(yy_c_buf_p); \
1777 *(yy_c_buf_p) = '\0'; \
1778 yyleng = yyless_macro_arg; \
1779 } \
1780 while ( 0 )
1781
1782/* Accessor methods (get/set functions) to struct members. */
1783
1784/** Get the current line number.
1785 *
1786 */
1787int yyget_lineno (void)
1788{
1789
1790 return yylineno;
1791}
1792
1793/** Get the input stream.
1794 *
1795 */
1796FILE *yyget_in (void)
1797{
1798 return yyin;
1799}
1800
1801/** Get the output stream.
1802 *
1803 */
1804FILE *yyget_out (void)
1805{
1806 return yyout;
1807}
1808
1809/** Get the length of the current token.
1810 *
1811 */
1812int yyget_leng (void)
1813{
1814 return yyleng;
1815}
1816
1817/** Get the current token.
1818 *
1819 */
1820
1821char *yyget_text (void)
1822{
1823 return yytext;
1824}
1825
1826/** Set the current line number.
1827 * @param _line_number line number
1828 *
1829 */
1830void yyset_lineno (int _line_number )
1831{
1832
1833 yylineno = _line_number;
1834}
1835
1836/** Set the input stream. This does not discard the current
1837 * input buffer.
1838 * @param _in_str A readable stream.
1839 *
1840 * @see yy_switch_to_buffer
1841 */
1842void yyset_in (FILE * _in_str )
1843{
1844 yyin = _in_str ;
1845}
1846
1847void yyset_out (FILE * _out_str )
1848{
1849 yyout = _out_str ;
1850}
1851
1852int yyget_debug (void)
1853{
1854 return yy_flex_debug;
1855}
1856
1857void yyset_debug (int _bdebug )
1858{
1859 yy_flex_debug = _bdebug ;
1860}
1861
1862static int yy_init_globals (void)
1863{
1864 /* Initialization is the same as for the non-reentrant scanner.
1865 * This function is called from yylex_destroy(), so don't allocate here.
1866 */
1867
1868 (yy_buffer_stack) = NULL;
1869 (yy_buffer_stack_top) = 0;
1870 (yy_buffer_stack_max) = 0;
1871 (yy_c_buf_p) = NULL;
1872 (yy_init) = 0;
1873 (yy_start) = 0;
1874
1875/* Defined in main.c */
1876#ifdef YY_STDINIT
1877 yyin = stdin;
1878 yyout = stdout;
1879#else
1880 yyin = NULL;
1881 yyout = NULL;
1882#endif
1883
1884 /* For future reference: Set errno on error, since we are called by
1885 * yylex_init()
1886 */
1887 return 0;
1888}
1889
1890/* yylex_destroy is for both reentrant and non-reentrant scanners. */
1891int yylex_destroy (void)
1892{
1893
1894 /* Pop the buffer stack, destroying each element. */
1895 while(YY_CURRENT_BUFFER){
1896 yy_delete_buffer( YY_CURRENT_BUFFER );
1897 YY_CURRENT_BUFFER_LVALUE = NULL;
1898 yypop_buffer_state();
1899 }
1900
1901 /* Destroy the stack itself. */
1902 yyfree((yy_buffer_stack) );
1903 (yy_buffer_stack) = NULL;
1904
1905 /* Reset the globals. This is important in a non-reentrant scanner so the next time
1906 * yylex() is called, initialization will occur. */
1907 yy_init_globals( );
1908
1909 return 0;
1910}
1911
1912/*
1913 * Internal utility routines.
1914 */
1915
1916#ifndef yytext_ptr
1917static void yy_flex_strncpy (char* s1, const char * s2, int n )
1918{
1919
1920 int i;
1921 for ( i = 0; i < n; ++i )
1922 s1[i] = s2[i];
1923}
1924#endif
1925
1926#ifdef YY_NEED_STRLEN
1927static int yy_flex_strlen (const char * s )
1928{
1929 int n;
1930 for ( n = 0; s[n]; ++n )
1931 ;
1932
1933 return n;
1934}
1935#endif
1936
1937void *yyalloc (yy_size_t size )
1938{
1939 return malloc(size);
1940}
1941
1942void *yyrealloc (void * ptr, yy_size_t size )
1943{
1944
1945 /* The cast to (char *) in the following accommodates both
1946 * implementations that use char* generic pointers, and those
1947 * that use void* generic pointers. It works with the latter
1948 * because both ANSI C and C++ allow castless assignment from
1949 * any pointer type to void*, and deal with argument conversions
1950 * as though doing an assignment.
1951 */
1952 return realloc(ptr, size);
1953}
1954
1955void yyfree (void * ptr )
1956{
1957 free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
1958}
1959
1960#define YYTABLES_NAME "yytables"
1961
1962#line 56 "vmlex.l"
1963
1964
diff --git a/vendor/vm/vm/main.c b/vendor/vm/vm/main.c
new file mode 100644
index 0000000..0c24238
--- /dev/null
+++ b/vendor/vm/vm/main.c
@@ -0,0 +1,47 @@
1#include "vm.h"
2#include "vmparse.tab.h"
3#include <stdio.h>
4#include <stdlib.h>
5
6extern FILE *yyin;
7int need_close = 0;
8
9int yyparse();
10
11void milan_error(char const * msg)
12{
13 if(need_close)
14 fclose(yyin);
15
16 fprintf(stderr, msg);
17 putc('\n', stderr);
18 exit(1);
19}
20
21int main(int argc, char **argv)
22{
23 if(argc < 2) {
24 yyin = stdin;
25 printf("Reading input from stdin\n");
26 }
27 else {
28 yyin = fopen(argv[1], "rt");
29 if(!yyin) {
30 printf("Unable to read %s\n", argv[1]);
31 return 1;
32 }
33
34 need_close = 1;
35 printf("Reading input from %s\n", argv[1]);
36 }
37
38 if(0 == yyparse()) {
39 run();
40 }
41
42 if(need_close) {
43 fclose(yyin);
44 }
45
46 return 0;
47}
diff --git a/vendor/vm/vm/test/bop1.ms b/vendor/vm/vm/test/bop1.ms
new file mode 100644
index 0000000..11cbf4f
--- /dev/null
+++ b/vendor/vm/vm/test/bop1.ms
@@ -0,0 +1,6 @@
14: STOP
21: PUSH 20
32: ADD
43: PRINT
50: PUSH 10
62: MULT
diff --git a/vendor/vm/vm/test/bop2.ms b/vendor/vm/vm/test/bop2.ms
new file mode 100644
index 0000000..3a1e004
--- /dev/null
+++ b/vendor/vm/vm/test/bop2.ms
@@ -0,0 +1,8 @@
10: PUSH 10
21: PUSH -1
32: BSTORE 2
43: PUSH 0
54: BLOAD 1
65: PRINT
76: STOP
8
diff --git a/vendor/vm/vm/test/fib.ms b/vendor/vm/vm/test/fib.ms
new file mode 100644
index 0000000..fe90ddd
--- /dev/null
+++ b/vendor/vm/vm/test/fib.ms
@@ -0,0 +1,37 @@
1; Âû÷èñëåíèå N-ãî ÷èñëà Ôèáîíà÷÷è
2
3SET 0 0 ; Êîíñòàíòà 0
4SET 1 1 ; Êîíñòàíòà 1
5
6SET 1000 0 ; Ïåðåìåííàÿ n
7SET 1001 1 ; Ïåðåìåííàÿ a
8SET 1002 1 ; Ïåðåìåííàÿ b
9
10; Ïðîãðàììà
11
12 0: INPUT
13 1: STORE 1000 ; n := READ
14
15 2: LOAD 1000
16 3: LOAD 1
17 4: COMPARE 3 ; IF n > 1
18 5: JUMP_NO 17
19
20 6: LOAD 1002 ; STACK <- b
21 7: LOAD 1001 ; STACK <- a
22 8: LOAD 1002
23 9: STORE 1001 ; a := b
2410: ADD
2511: STORE 1002 ; b := ñòàðîå_çíà÷åíèå_a + b
26
2712: LOAD 1000
2813: LOAD 1
2914: SUB
3015: STORE 1000 ; n := n - 1
3116: JUMP 2
32
3317: LOAD 1001 ; WRITE(a)
3418: PRINT
35
3619: STOP
37
diff --git a/vendor/vm/vm/test/fib2.ms b/vendor/vm/vm/test/fib2.ms
new file mode 100644
index 0000000..55f267e
--- /dev/null
+++ b/vendor/vm/vm/test/fib2.ms
@@ -0,0 +1,21 @@
1SET 0 1
2SET 1 1
3
4 0: INPUT
5 1: DUP
6 2: PUSH 1
7 3: COMPARE 3
8 4: JUMP_NO 14
9 5: LOAD 1
10 6: LOAD 0
11 7: LOAD 1
12 8: STORE 0
13 9: ADD
1410: STORE 1
1511: PUSH 1
1612: SUB
1713: JUMP 1
1814: LOAD 0
1915: PRINT
2016: STOP
21 \ No newline at end of file
diff --git a/vendor/vm/vm/vm.c b/vendor/vm/vm/vm.c
new file mode 100644
index 0000000..eb7a9c9
--- /dev/null
+++ b/vendor/vm/vm/vm.c
@@ -0,0 +1,458 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include "vm.h"
5
6void milan_error();
7
8command vm_program[MAX_PROGRAM_SIZE];
9
10int vm_memory[MAX_MEMORY_SIZE];
11int vm_stack[MAX_STACK_SIZE];
12
13unsigned int vm_stack_pointer = 0;
14unsigned int vm_base_pointer = 0;
15unsigned int vm_command_pointer = 0;
16
17opcode_info opcodes_table[] = {
18 {"NOP", 0},
19 {"STOP", 0},
20 {"LOAD", 1},
21 {"STORE", 1},
22 {"BLOAD", 1},
23 {"BSTORE", 1},
24 {"PUSH", 1},
25 {"POP", 0},
26 {"DUP", 0},
27 {"INVERT", 0},
28 {"ADD", 0},
29 {"SUB", 0},
30 {"MULT", 0},
31 {"DIV", 0},
32 {"COMPARE", 1},
33 {"JUMP", 1},
34 {"JUMP_YES", 1},
35 {"JUMP_NO", 1},
36 {"INPUT", 0},
37 {"PRINT", 0},
38
39 {"CALL", 1},
40 {"RETURN", 1},
41 {"LOADB", 1},
42 {"STOREB", 1},
43 {"SHIFT", 1},
44};
45
46int opcodes_table_size = sizeof(opcodes_table) / sizeof(opcode_info);
47
48typedef enum {
49 BAD_DATA_ADDRESS,
50 BAD_CODE_ADDRESS,
51 BAD_RELATION,
52 STACK_OVERFLOW,
53 STACK_UNDERFLOW,
54 DIVISION_BY_ZERO,
55 BAD_INPUT,
56 UNKNOWN_COMMAND
57} runtime_error;
58
59void vm_init()
60{
61 vm_stack_pointer = 0;
62 vm_base_pointer = 0;
63 vm_command_pointer = 0;
64}
65
66void vm_error(runtime_error error)
67{
68 opcode_info* info;
69
70 switch(error) {
71 case BAD_DATA_ADDRESS:
72 fprintf(stderr, "Error: illegal data address\n");
73 break;
74
75 case BAD_CODE_ADDRESS:
76 fprintf(stderr, "Error: illegal address in JUMP* instruction\n");
77 break;
78
79 case BAD_RELATION:
80 fprintf(stderr, "Error: illegal comparison operator\n");
81 break;
82
83 case STACK_OVERFLOW:
84 fprintf(stderr, "Error: stack overflow\n");
85 break;
86
87 case STACK_UNDERFLOW:
88 fprintf(stderr, "Error: stack underflow\n");
89 break;
90
91 case DIVISION_BY_ZERO:
92 fprintf(stderr, "Error: division by zero\n");
93 break;
94
95 case BAD_INPUT:
96 fprintf(stderr, "Error: illegal input\n");
97 break;
98
99 case UNKNOWN_COMMAND:
100 fprintf(stderr, "Error: unknown command, unable to execute\n");
101 break;
102
103 default:
104 fprintf(stderr, "Error: runtime error %d\n", error);
105 }
106
107 fprintf(stderr, "Code:\n\n");
108
109 info = operation_info(vm_program[vm_command_pointer].operation);
110 if(NULL == info) {
111 fprintf(stderr, "%d\t(%d)\t\t%d\n", vm_command_pointer,
112 vm_program[vm_command_pointer].operation,
113 vm_program[vm_command_pointer].arg);
114 }
115 else {
116 if(info->need_arg) {
117 fprintf(stderr, "\t%d\t%s\t\t%d\n", vm_command_pointer, info->name,
118 vm_program[vm_command_pointer].arg);
119 }
120 else {
121 fprintf(stderr, "\t%d\t%s\n", vm_command_pointer, info->name);
122 }
123 }
124
125 milan_error("VM error");
126}
127
128int vm_load(unsigned int address)
129{
130 if(address < MAX_MEMORY_SIZE) {
131 return vm_memory[address];
132 }
133 else {
134 vm_error(BAD_DATA_ADDRESS);
135 return 0;
136 }
137}
138
139void vm_store(unsigned int address, int word)
140{
141 if(address < MAX_MEMORY_SIZE) {
142 vm_memory[address] = word;
143 }
144 else {
145 vm_error(BAD_DATA_ADDRESS);
146 }
147}
148
149int vm_read()
150{
151 int n;
152
153 fprintf(stderr, "> "); fflush(stdout);
154 if(scanf("%d", &n)) {
155 return n;
156 }
157 else {
158 vm_error(BAD_INPUT);
159 return 0;
160 }
161}
162
163void vm_write(int n)
164{
165 fprintf(stderr, "%d\n", n);
166}
167
168int vm_pop()
169{
170 if(vm_stack_pointer > 0) {
171 return vm_stack[--vm_stack_pointer];
172 }
173 else {
174 vm_error(STACK_UNDERFLOW);
175 return 0;
176 }
177}
178
179void vm_push(int word)
180{
181 if(vm_stack_pointer < MAX_STACK_SIZE) {
182 vm_stack[vm_stack_pointer++] = word;
183 }
184 else {
185 vm_error(STACK_OVERFLOW);
186 }
187}
188
189void vm_call(unsigned int address)
190{
191 if (address >= MAX_PROGRAM_SIZE)
192 vm_error(BAD_CODE_ADDRESS);
193
194 vm_push(vm_command_pointer + 1);
195 vm_push(vm_base_pointer);
196 vm_base_pointer = vm_stack_pointer;
197 vm_command_pointer = address;
198}
199
200void vm_return(int shift)
201{
202 vm_stack_pointer = vm_base_pointer;
203
204 vm_base_pointer = vm_pop();
205
206 unsigned int return_address = vm_pop();
207 if (return_address >= MAX_PROGRAM_SIZE)
208 vm_error(BAD_CODE_ADDRESS);
209 vm_command_pointer = return_address;
210
211 while (shift--) vm_pop();
212}
213
214int vm_loadb(int offset)
215{
216 if (offset < 0 && vm_base_pointer < - offset) vm_error(STACK_UNDERFLOW);
217 if (offset > 0 && vm_base_pointer > MAX_STACK_SIZE - offset) vm_error(STACK_OVERFLOW);
218
219 return vm_stack[vm_base_pointer + offset];
220}
221
222void vm_storeb(int offset, int word)
223{
224 if (offset < 0 && vm_base_pointer < - offset) vm_error(STACK_UNDERFLOW);
225 if (offset > 0 && vm_base_pointer > MAX_STACK_SIZE - offset) vm_error(STACK_OVERFLOW);
226
227 vm_stack[vm_base_pointer + offset] = word;
228}
229
230void vm_shift(int offset)
231{
232 if (offset < 0 && vm_stack_pointer < - offset) vm_error(STACK_UNDERFLOW);
233 if (offset > 0 && vm_stack_pointer > MAX_STACK_SIZE - offset) vm_error(STACK_OVERFLOW);
234
235 vm_stack_pointer += offset;
236}
237
238int vm_run_command()
239{
240 unsigned int index = vm_command_pointer;
241
242 operation op = vm_program[index].operation;
243 unsigned int arg = vm_program[index].arg;
244 int data;
245
246 // printf ("IP: %u\n", vm_command_pointer);
247 // printf ("BP: %u\n", vm_base_pointer);
248 // printf ("SP: %u\n", vm_stack_pointer);
249 // printf ("Stack:\n");
250 // for (unsigned int i = 0; i < vm_stack_pointer; ++i)
251 // printf ("0x%04x: %u\n", vm_stack[i]);
252 // printf ("\n");
253
254 switch(op) {
255 case NOP:
256 /* Ничего не делаем */
257 break;
258
259 case STOP:
260 return 0;
261 break;
262
263 case LOAD:
264 vm_push(vm_load(arg));
265 break;
266
267 case STORE:
268 vm_store(arg, vm_pop());
269 break;
270
271 case BLOAD:
272 vm_push(vm_load(arg + vm_pop()));
273 break;
274
275 case BSTORE:
276 data = vm_pop();
277 vm_store(arg + data, vm_pop());
278 break;
279
280 case PUSH:
281 vm_push(arg);
282 break;
283
284 case POP:
285 vm_pop();
286 break;
287
288 case DUP:
289 data = vm_pop();
290 vm_push(data);
291 vm_push(data);
292 break;
293
294 case INVERT:
295 vm_push(-vm_pop());
296 break;
297
298 case ADD:
299 data = vm_pop();
300 vm_push(vm_pop() + data);
301 break;
302
303 case SUB:
304 data = vm_pop();
305 vm_push(vm_pop() - data);
306 break;
307
308 case MULT:
309 data = vm_pop();
310 vm_push(vm_pop() * data);
311 break;
312
313 case DIV:
314 data = vm_pop();
315 if(0 == data) {
316 vm_error(DIVISION_BY_ZERO);
317 }
318 else {
319 vm_push(vm_pop() / data);
320 }
321 break;
322
323 case COMPARE:
324 data = vm_pop();
325 switch(arg) {
326 case EQ:
327 vm_push((vm_pop() == data) ? 1 : 0);
328 break;
329
330 case NE:
331 vm_push((vm_pop() != data) ? 1 : 0);
332 break;
333
334 case LT:
335 vm_push((vm_pop() < data) ? 1 : 0);
336 break;
337
338 case GT:
339 vm_push((vm_pop() > data) ? 1 : 0);
340 break;
341
342 case LE:
343 vm_push((vm_pop() <= data) ? 1 : 0);
344 break;
345
346 case GE:
347 vm_push((vm_pop() >= data) ? 1 : 0);
348 break;
349
350 default:
351 vm_error(BAD_RELATION);
352 }
353 break;
354
355 case JUMP:
356 if(arg < MAX_PROGRAM_SIZE) {
357 vm_command_pointer = arg;
358 return 1;
359 }
360 else {
361 vm_error(BAD_CODE_ADDRESS);
362 }
363
364 break;
365
366 case JUMP_YES:
367 if(arg < MAX_PROGRAM_SIZE) {
368 data = vm_pop();
369 if(data) {
370 vm_command_pointer = arg;
371 return 1;
372 }
373 }
374 else {
375 vm_error(BAD_CODE_ADDRESS);
376 }
377 break;
378
379 case JUMP_NO:
380 if(arg < MAX_PROGRAM_SIZE) {
381 data = vm_pop();
382 if(!data) {
383 vm_command_pointer = arg;
384 return 1;
385 }
386 }
387 else {
388 vm_error(BAD_CODE_ADDRESS);
389 }
390 break;
391
392 case INPUT:
393 vm_push(vm_read());
394 break;
395
396 case PRINT:
397 vm_write(vm_pop());
398 break;
399
400 case CALL:
401 vm_call(arg);
402 return 1;
403 break;
404
405 case RETURN:
406 vm_return(arg);
407 return 1;
408 break;
409
410 case LOADB:
411 vm_push(vm_loadb(arg));
412 break;
413
414 case STOREB:
415 vm_storeb(arg, vm_pop());
416 break;
417
418 case SHIFT:
419 vm_shift(arg);
420 break;
421
422 default:
423 vm_error(UNKNOWN_COMMAND);
424 }
425
426 ++vm_command_pointer;
427 return 1;
428}
429
430void run()
431{
432 vm_command_pointer = 0;
433 while(vm_command_pointer < MAX_PROGRAM_SIZE) {
434 if(!vm_run_command())
435 break;
436 }
437}
438
439opcode_info* operation_info(operation op)
440{
441 return (op < opcodes_table_size) ? &opcodes_table[op] : NULL;
442}
443
444void put_command(unsigned int address, operation op, int arg)
445{
446 if(address < MAX_PROGRAM_SIZE) {
447 vm_program[address].operation = op;
448 vm_program[address].arg = arg;
449 }
450 else {
451 milan_error("Illegal address in put_command()");
452 }
453}
454
455void set_mem(unsigned int address, int value)
456{
457 vm_memory[address] = value;
458}
diff --git a/vendor/vm/vm/vm.h b/vendor/vm/vm/vm.h
new file mode 100644
index 0000000..9b63cef
--- /dev/null
+++ b/vendor/vm/vm/vm.h
@@ -0,0 +1,94 @@
1#ifndef _MILAN_VM_H
2#define _MILAN_VM_H
3
4#include <stdio.h>
5
6/* Константы */
7
8/* Размер памяти команд */
9#define MAX_PROGRAM_SIZE 65536
10
11/* Размер памяти данных */
12#define MAX_MEMORY_SIZE 65536
13
14/* Размер стека */
15#define MAX_STACK_SIZE 8192
16
17/* Команды виртуальной машины */
18typedef enum {
19 NOP = 0, /* Нет операции */
20 STOP, /* Остановка */
21 LOAD, /* Загрузка слова из памяти данных */
22 STORE, /* Запись слова в память данных */
23 BLOAD, /* Загрузка слова из памяти данных с учётом смещения */
24 BSTORE, /* Запись слова в память данныз с учётом смещения */
25 PUSH, /* Заталкивание слова в стек */
26 POP, /* Выталкивание слова из стека */
27 DUP, /* Дублирование слова на вершине стека */
28 INVERT, /* Изменение знака числа на вершине стека */
29 ADD, /* Сложение */
30 SUB, /* Вычитание */
31 MULT, /* Умножение */
32 DIV, /* Целочисленное деление */
33 COMPARE, /* Сравнение */
34 JUMP, /* Безусловный переход */
35 JUMP_YES, /* Условный переход, если на вершине стека не 0 */
36 JUMP_NO, /* Условный переход, если на вершине стека 0 */
37 INPUT, /* Чтение слова со стандартного устройства ввода */
38 PRINT, /* Запись слова на стандартное устройство вывода */
39
40 CALL, /* Выхов функции */
41 RETURN, /* Возвращение из функции */
42 LOADB, /* Загрузка слова из стека относительно начала рамки с учётом смещения */
43 STOREB, /* Запись слова в стек относительно начала рамки с учётом смещения */
44 SHIFT, /* Сдвиг указателя стека */
45} operation;
46
47/* Операции сравнения */
48typedef enum {
49 EQ, /* = */
50 NE, /* !- */
51 LT, /* < */
52 GT, /* > */
53 LE, /* <= */
54 GE /* >= */
55} compare_type;
56
57/* Структура ячейки памяти команд */
58typedef struct {
59 operation operation; /* Код команды */
60 int arg; /* Аргумент */
61} command;
62
63/* Информация о команде */
64typedef struct opcode_info {
65 char *name; /* Текстовое представление команды */
66 int need_arg; /* Признак, равный 1, если команде нужен аргумент */
67} opcode_info;
68
69/* Получение информации о команде с кодом op.
70 * Освобождать память, на которую указывает возвращаемый
71 * указатель, не нужно.
72 */
73
74opcode_info* operation_info(operation op);
75
76/* Запись команды в память команд по адресу address. */
77
78void put_command(unsigned int address, operation op, int arg);
79
80/* Запуск программы.
81 *
82 * Исполнение программы начинается с адреса 0 и заканчивается,
83 * когда встретится команда STOP или будет обнаружена ошибка
84 * времени исполнения.
85 */
86
87void run();
88
89/* Запись значения value в память данных по адресу address. */
90
91void set_mem(unsigned int address, int value);
92
93#endif
94
diff --git a/vendor/vm/vm/vmlex.l b/vendor/vm/vm/vmlex.l
new file mode 100644
index 0000000..2f22e00
--- /dev/null
+++ b/vendor/vm/vm/vmlex.l
@@ -0,0 +1,56 @@
1%{
2#include "vmparse.tab.h"
3#include <stdlib.h>
4
5#ifndef __GNUC__
6#define YY_NO_UNISTD_H
7#endif
8%}
9
10%option noyywrap
11
12WHITESPACE [ \t]+
13EOL \n
14INT -?[0-9]+
15COMMENT ;[^\n]*\n
16
17%%
18
19{EOL}
20{COMMENT}
21{WHITESPACE}
22{INT} { yylval = atoi(yytext); return T_INT; }
23
24: { return T_COLON; }
25
26CALL { return T_CALL; }
27RETURN { return T_RETURN; }
28LOADB { return T_LOADB; }
29STOREB { return T_STOREB; }
30SHIFT { return T_SHIFT; }
31
32SET { return T_SET; }
33STOP { return T_STOP; }
34LOAD { return T_LOAD; }
35STORE { return T_STORE; }
36BLOAD { return T_BLOAD; }
37BSTORE { return T_BSTORE; }
38PUSH { return T_PUSH; }
39POP { return T_POP; }
40DUP { return T_DUP; }
41INVERT { return T_INVERT; }
42ADD { return T_ADD; }
43SUB { return T_SUB; }
44MULT { return T_MULT; }
45DIV { return T_DIV; }
46COMPARE { return T_COMPARE; }
47JUMP { return T_JUMP; }
48JUMP_YES { return T_JUMP_YES; }
49JUMP_NO { return T_JUMP_NO; }
50INPUT { return T_INPUT; }
51PRINT { return T_PRINT; }
52NOP { return T_NOP; }
53
54<<EOF>> { yyterminate(); }
55
56%%
diff --git a/vendor/vm/vm/vmparse.y b/vendor/vm/vm/vmparse.y
new file mode 100644
index 0000000..4c019c5
--- /dev/null
+++ b/vendor/vm/vm/vmparse.y
@@ -0,0 +1,83 @@
1%{
2#include "vm.h"
3#include <stdio.h>
4#include <stdlib.h>
5
6#define YYSTYPE int
7
8int yylex();
9void yyerror(char const *);
10%}
11
12%token T_INT
13%token T_SET
14%token T_NOP
15%token T_STOP
16%token T_LOAD
17%token T_STORE
18%token T_BLOAD
19%token T_BSTORE
20%token T_PUSH
21%token T_POP
22%token T_DUP
23%token T_INVERT
24%token T_ADD
25%token T_SUB
26%token T_MULT
27%token T_DIV
28%token T_COMPARE
29%token T_JUMP
30%token T_JUMP_YES
31%token T_JUMP_NO
32%token T_INPUT
33%token T_PRINT
34%token T_COLON
35
36%token T_CALL
37%token T_RETURN
38%token T_LOADB
39%token T_STOREB
40%token T_SHIFT
41
42%%
43
44program : line program
45 | line
46 ;
47
48line : T_INT T_COLON T_NOP { put_command($1, NOP, 0); }
49 | T_INT T_COLON T_STOP { put_command($1, STOP, 0); }
50 | T_INT T_COLON T_LOAD T_INT { put_command($1, LOAD, $4); }
51 | T_INT T_COLON T_STORE T_INT { put_command($1, STORE, $4); }
52 | T_INT T_COLON T_BLOAD T_INT { put_command($1, BLOAD, $4); }
53 | T_INT T_COLON T_BSTORE T_INT { put_command($1, BSTORE, $4); }
54 | T_INT T_COLON T_PUSH T_INT { put_command($1, PUSH, $4); }
55 | T_INT T_COLON T_POP { put_command($1, POP, 0); }
56 | T_INT T_COLON T_DUP { put_command($1, DUP, 0); }
57 | T_INT T_COLON T_INVERT { put_command($1, INVERT, 0); }
58 | T_INT T_COLON T_ADD { put_command($1, ADD, 0); }
59 | T_INT T_COLON T_SUB { put_command($1, SUB, 0); }
60 | T_INT T_COLON T_MULT { put_command($1, MULT, 0); }
61 | T_INT T_COLON T_DIV { put_command($1, DIV, 0); }
62 | T_INT T_COLON T_COMPARE T_INT { put_command($1, COMPARE, $4); }
63 | T_INT T_COLON T_JUMP T_INT { put_command($1, JUMP, $4); }
64 | T_INT T_COLON T_JUMP_YES T_INT { put_command($1, JUMP_YES, $4); }
65 | T_INT T_COLON T_JUMP_NO T_INT { put_command($1, JUMP_NO, $4); }
66 | T_INT T_COLON T_INPUT { put_command($1, INPUT, 0); }
67 | T_INT T_COLON T_PRINT { put_command($1, PRINT, 0); }
68
69 | T_INT T_COLON T_CALL T_INT { put_command($1, CALL, $4); }
70 | T_INT T_COLON T_RETURN T_INT { put_command($1, RETURN, $4); }
71 | T_INT T_COLON T_LOADB T_INT { put_command($1, LOADB, $4); }
72 | T_INT T_COLON T_STOREB T_INT { put_command($1, STOREB, $4); }
73 | T_INT T_COLON T_SHIFT T_INT { put_command($1, SHIFT, $4); }
74
75 | T_SET T_INT T_INT { set_mem($2, $3); }
76 ;
77%%
78
79void yyerror(char const *str)
80{
81 printf("Error: %s\n", str);
82}
83