This repository was archived by the owner on Sep 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1074.cpp
More file actions
412 lines (384 loc) · 12.7 KB
/
1074.cpp
File metadata and controls
412 lines (384 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#include <cassert>
#include <exception>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <string>
#include <unordered_map>
#include <vector>
constexpr const char *kDivideByZero = "DIVIDE BY ZERO";
constexpr const char *kInvalidNumber = "INVALID NUMBER";
constexpr const char *kLineNumberError = "LINE NUMBER ERROR";
constexpr const char *kSyntaxError = "SYNTAX ERROR";
constexpr const char *kVariableNotDefined = "VARIABLE NOT DEFINED";
constexpr const char *kHelp = "Yet another basic interpreter";
constexpr const char *keyWords[] = {"REM","LET","PRINT","INPUT","END","GOTO","IF","THEN","RUN","LIST","CLEAR","QUIT","HELP"};
template <typename T>
void print (T var) { std::cout << var << std::endl; }
class Error : public std::exception {
public:
const char *message;
Error (const char *message) : message(message) {}
};
class Statement;
struct ProgramState {
int pc = -1;
std::unordered_map<std::string, int> variables;
std::map<int, Statement *> program;
};
ProgramState state;
std::istream *stream = &std::cin;
const std::regex kReName {R"(^[a-zA-Z0-9]+$)"};
void checkName (const std::string &name) {
for (const auto &kw : keyWords) {
if (name.find(kw) != std::string::npos) throw Error(kSyntaxError);
}
if (!std::regex_match(name, kReName)) throw Error(kSyntaxError);
}
void checkLine (int line) {
if (state.program.count(line) < 1) throw Error(kLineNumberError);
}
struct Expression {
virtual int eval () = 0;
virtual ~Expression () = default;
};
enum Op { ADD, SUB, MUL, DIV };
struct OpExpression : public Expression {
Op op;
Expression *lhs;
Expression *rhs;
OpExpression (Op op, Expression *lhs, Expression *rhs) : op(op), lhs(lhs), rhs(rhs) {}
int eval () {
int lhsValue = lhs->eval(), rhsValue = rhs->eval();
switch (op) {
case ADD: return lhsValue + rhsValue;
case SUB: return lhsValue - rhsValue;
case MUL: return lhsValue * rhsValue;
case DIV: {
if (rhsValue == 0) throw Error(kDivideByZero);
return lhsValue / rhsValue;
}
default: assert(false);
}
}
};
struct GroupExpression : public Expression {
Expression *group;
GroupExpression (Expression *group) : group(group) {}
int eval () { return group->eval(); }
};
struct VariableExpression : public Expression {
std::string variable;
VariableExpression (const std::string &variable) : variable(variable) {}
int eval () {
if (state.variables.count(variable) < 1) throw Error(kVariableNotDefined);
return state.variables[variable];
}
};
struct LiteralExpression : public Expression {
int literal;
LiteralExpression (int literal) : literal(literal) {}
int eval () { return literal; }
};
struct Group {
int start;
int end;
Expression *parsed;
};
struct {
const int literal = 1;
const int variable = 2;
const int group = 3;
const int lhspm = 4;
const int pm = 5;
const int rhspm = 6;
const int lhsmul = 7;
const int mul = 8;
const int rhsmul = 9;
} kExprGroups;
const std::regex kReExpr {R"(^(?:(\d+)|([a-zA-Z0-9]+)|(?:__GRP_(\d+)__)|(?:(.+)\s*([+\-])\s*(.+))|(?:(.+)\s*([*/])\s*(.+)))$)"};
const std::regex kReParens {R"([()])"};
Expression *parseExpr (std::string expr, const std::vector<Group> baseGroups = {}) {
while (expr.front() == ' ' || expr.front() == '\r' || expr.front() == '\n') expr.erase(expr.begin());
while (expr.back() == ' ' || expr.back() == '\r' || expr.back() == '\n') expr.pop_back();
std::vector<Group> groups;
if (std::regex_search(expr, kReParens)) {
auto symbol = [] (int i) { return std::string("__GRP_") + std::to_string(i) + std::string("__"); };
int depth = 0, start;
for (int i = 0; i < expr.length(); ++i) {
if (expr[i] == '(') {
if (depth == 0) start = i;
++depth;
} else if (expr[i] == ')') {
--depth;
if (depth == 0) groups.push_back({ .start = start, .end = i, .parsed = parseExpr(expr.substr(start + 1, i - start - 1)) });
if (depth < 0) throw Error(kSyntaxError);
}
}
if (depth > 0) throw Error(kSyntaxError);
std::string originalExpr = expr;
expr = originalExpr.substr(0, groups[0].start);
for (int i = 0; i < groups.size(); ++i) {
expr += symbol(i + baseGroups.size());
expr += originalExpr.substr(groups[i].end + 1, (i + 1 < groups.size() ? groups[i + 1].start : originalExpr.size()) - groups[i].end - 1);
}
}
// I know it's slow... But performance isn't critical here.
for (int i = baseGroups.size() - 1; i >= 0; --i) groups.insert(groups.begin(), baseGroups[i]);
std::smatch match;
if (!std::regex_match(expr, match, kReExpr)) throw Error(kSyntaxError);
if (match[kExprGroups.literal].matched) return new LiteralExpression(std::stoi(match[kExprGroups.literal].str()));
if (match[kExprGroups.variable].matched) return new VariableExpression(match[kExprGroups.variable].str());
if (match[kExprGroups.group].matched) return new GroupExpression(groups[std::stoi(match[kExprGroups.group].str())].parsed);
if (match[kExprGroups.pm].matched) {
return new OpExpression(
match[kExprGroups.pm].str() == "+" ? ADD : SUB,
parseExpr(match[kExprGroups.lhspm].str(), groups),
parseExpr(match[kExprGroups.rhspm].str(), groups)
);
}
if (match[kExprGroups.mul].matched) {
return new OpExpression(
match[kExprGroups.mul].str() == "*" ? MUL : DIV,
parseExpr(match[kExprGroups.lhsmul].str(), groups),
parseExpr(match[kExprGroups.rhsmul].str(), groups)
);
}
assert(false);
}
const std::regex kReStatement {R"(^(?:(?:(\d+)\s*)?(?:(REM\s*.+)|(LET\s*([^ ]+)\s+=\s+(.+))|(PRINT\s*(.+))|(INPUT\s*([^ ]+))|(END\s*(?:))|(GOTO\s*(\d+))|(IF\s*(.+)\s+([<>=])\s+(.+)\s+THEN\s+(\d+))|(RUN\s*)|(LIST\s*)|(CLEAR\s*)|(QUIT\s*)|(HELP\s*))?)$)"};
struct {
const int lineNumber = 1;
const int rem = 2;
const int let = 3;
const int letName = 4;
const int letExpr = 5;
const int print = 6;
const int printExpr = 7;
const int input = 8;
const int inputName = 9;
const int end = 10;
const int goto_ = 11;
const int gotoLine = 12;
const int if_ = 13;
const int ifLhs = 14;
const int ifCmp = 15;
const int ifRhs = 16;
const int ifLine = 17;
const int run = 18;
const int list = 19;
const int clear = 20;
const int quit = 21;
const int help = 22;
} kStatementGroups;
// WARNING: Memory leak ahead!
enum RunnableType { REM, LET, PRINT, INPUT, END, GOTO, IF, RUN, LIST, CLEAR, QUIT, HELP };
class Runnable {
public:
virtual void run () {}
virtual RunnableType getType () = 0;
virtual ~Runnable () {}
};
class Statement : public Runnable {
public:
std::string source;
};
class RemStatement : public Statement {
public:
RunnableType getType () { return REM; }
RemStatement (std::smatch) {}
};
class LetStatement : public Statement {
public:
RunnableType getType () { return LET; }
Expression *expr;
std::string name;
LetStatement (std::smatch match) {
name = match[kStatementGroups.letName].str();
checkName(name);
expr = parseExpr(match[kStatementGroups.letExpr].str());
}
void run () {
state.variables[name] = expr->eval();
}
};
class PrintStatement : public Statement {
public:
RunnableType getType () { return PRINT; }
Expression *expr;
PrintStatement (std::smatch match) {
expr = parseExpr(match[kStatementGroups.printExpr].str());
}
void run () { print(expr->eval()); }
};
const std::regex kInputRegex {R"(^-?\d+$)"};
class InputStatement : public Statement {
public:
RunnableType getType () { return INPUT; }
std::string name;
InputStatement (std::smatch match) {
name = match[kStatementGroups.inputName].str();
checkName(name);
}
std::string read () {
std::cout << " ? ";
std::string input;
std::getline(*stream, input);
return input;
}
void run () {
std::string input = read();
while (!std::regex_match(input, kInputRegex)) {
print(kInvalidNumber);
input = read();
}
state.variables[name] = std::stoi(input);
}
};
class EndStatement : public Statement {
public:
RunnableType getType () { return END; }
EndStatement (std::smatch) {}
};
class GotoStatement : public Statement { // considered harmful
public:
RunnableType getType () { return GOTO; }
int line;
GotoStatement (std::smatch match) {
line = std::stoi(match[kStatementGroups.gotoLine].str());
}
void run () {
checkLine(line);
state.pc = line;
}
};
class IfStatement : public Statement {
public:
RunnableType getType () { return IF; }
Expression *lhs, *rhs;
char cmp;
int line;
IfStatement (std::smatch match) {
lhs = parseExpr(match[kStatementGroups.ifLhs].str());
rhs = parseExpr(match[kStatementGroups.ifRhs].str());
cmp = match[kStatementGroups.ifCmp].str()[0];
line = std::stoi(match[kStatementGroups.ifLine].str());
}
bool conditionMet (int lhs, int rhs) {
switch (cmp) {
case '>': return lhs > rhs;
case '<' : return lhs < rhs;
case '=': return lhs == rhs;
default: assert(false);
}
}
void run () {
if (conditionMet(lhs->eval(),rhs->eval())) {
checkLine(line);
state.pc = line;
}
}
};
class Command : public Runnable {};
class ListCommand : public Command {
public:
RunnableType getType () { return LIST; }
void run () {
for (const auto &[ line, expr ] : state.program) print(expr->source);
}
};
class ClearCommand : public Command {
public:
RunnableType getType () { return CLEAR; }
void run () {
state = ProgramState();
}
};
class QuitCommand : public Command {
public:
RunnableType getType () { return QUIT; }
void run () { exit(0); }
};
class HelpCommand : public Command {
public:
RunnableType getType () { return HELP; }
void run () { print(kHelp); }
};
class RunCommand : public Command {
public:
RunnableType getType () { return RUN; }
void run () {
if (state.program.size() == 0) return;
state.pc = state.program.begin()->first;
try {
while (true) {
Statement *stmt = state.program[state.pc];
if (stmt->getType() == END) break;
auto it = state.program.upper_bound(state.pc);
state.pc = it == state.program.end() ? -1 : it->first;
stmt->run();
if (state.pc == -1) break;
}
} catch (const Error &e) {
print(e.message);
}
}
};
constexpr RunnableType kStatementTypes[] = { REM, LET, PRINT, INPUT, END, GOTO, IF };
constexpr RunnableType kCommandTypes[] = { RUN, LIST, CLEAR, QUIT, HELP };
constexpr RunnableType kImmediateStatementTypes[] = { LET, PRINT, INPUT };
void oneLine () {
if (stream->eof()) exit(0);
std::string line;
std::getline(*stream, line);
if (line.size() == 0) return;
std::smatch match;
if (!std::regex_match(line, match, kReStatement)) throw Error(kSyntaxError);
Runnable *runnable = nullptr;
if (match[kStatementGroups.rem].matched) runnable = new RemStatement(match);
if (match[kStatementGroups.let].matched) runnable = new LetStatement(match);
if (match[kStatementGroups.print].matched) runnable = new PrintStatement(match);
if (match[kStatementGroups.input].matched) runnable = new InputStatement(match);
if (match[kStatementGroups.end].matched) runnable = new EndStatement(match);
if (match[kStatementGroups.goto_].matched) runnable = new GotoStatement(match);
if (match[kStatementGroups.if_].matched) runnable = new IfStatement(match);
if (match[kStatementGroups.run].matched) runnable = new RunCommand();
if (match[kStatementGroups.list].matched) runnable = new ListCommand();
if (match[kStatementGroups.clear].matched) runnable = new ClearCommand();
if (match[kStatementGroups.quit].matched) runnable = new QuitCommand();
if (match[kStatementGroups.help].matched) runnable = new HelpCommand();
int lineNumber = -1;
if (match[kStatementGroups.lineNumber].matched) lineNumber = std::stoi(match[kStatementGroups.lineNumber].str());
if (runnable == nullptr) {
if (lineNumber < 0) throw Error(kSyntaxError);
state.program.erase(lineNumber);
return;
}
bool isCommand = false;
for (const auto &type : kCommandTypes) if (runnable->getType() == type) isCommand = true;
if (isCommand) {
if (lineNumber >= 0) throw Error(kSyntaxError);
runnable->run();
return;
}
dynamic_cast<Statement *>(runnable)->source = line;
if (lineNumber >= 0) {
state.program[lineNumber] = dynamic_cast<Statement *>(runnable);
} else {
bool isImmediateStatement = false;
for (const auto &type : kImmediateStatementTypes) if (runnable->getType() == type) isImmediateStatement = true;
if (!isImmediateStatement) throw Error(kSyntaxError);
runnable->run();
}
}
int main (int argc, char **argv) {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
if (argc > 1) {
std::fstream fs;
fs.open(argv[1], std::ios_base::in);
stream = &fs;
}
while (true) try { oneLine(); } catch (const Error &e) { print(e.message); }
}