-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
428 lines (384 loc) · 15.5 KB
/
main.cpp
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <unordered_map>
#include <sstream>
#include <limits>
#include <cmath>
#include <stack>
using namespace std;
enum TokenType {
COMMAND,
VARIABLE,
OPERATOR,
ASSIGNMENT,
NUMBER,
LPAREN,
RPAREN,
UNKNOWN
};
struct Token {
TokenType type;
string value;
};
vector<Token> tokenize(const string& command) {
vector<Token> tokens;
regex tokenPattern("(BEG|PRINT|HELP|EXIT!|[a-zA-Z_][a-zA-Z0-9_]*|[-]?\\d*\\.?\\d+|=|\\+|\\-|\\*|\\/|\\%|\\(|\\))");
auto words_begin = sregex_iterator(command.begin(), command.end(), tokenPattern);
auto words_end = sregex_iterator();
for (sregex_iterator i = words_begin; i != words_end; ++i) {
smatch match = *i;
string token = match.str();
if (regex_match(token, regex("(BEG|PRINT|HELP|EXIT!)"))) {
tokens.push_back({COMMAND, token});
} else if (regex_match(token, regex("[a-zA-Z_][a-zA-Z0-9_]*"))) {
tokens.push_back({VARIABLE, token});
} else if (regex_match(token, regex("[-]?\\d*\\.?\\d+"))) {
tokens.push_back({NUMBER, token});
} else if (token == "=") {
tokens.push_back({ASSIGNMENT, token});
} else if (token == "(") {
tokens.push_back({LPAREN, token});
} else if (token == ")") {
tokens.push_back({RPAREN, token});
} else if (token == "+" || token == "-" || token == "*" || token == "/" || token == "%") {
tokens.push_back({OPERATOR, token});
} else {
tokens.push_back({UNKNOWN, token});
}
}
// Check for unknown words
string remaining = command;
for (const auto& token : tokens) {
size_t pos = remaining.find(token.value);
if (pos != string::npos) {
remaining.erase(pos, token.value.length());
}
}
remaining = regex_replace(remaining, regex("\\s+"), "");
for (char c : remaining) {
if (!isspace(c)) {
cout << "Unknown word [" << remaining << "]" << endl;
tokens.clear();
break;
}
}
return tokens;
}
// Function to handle the HELP command
void printHelp() {
cout << "Available commands:\n";
cout << "HELP - Display this help message\n";
cout << "BEG <variable> - Input value for given var\n";
cout << "PRINT <variable> - Display value of given variable\n";
cout << "<variable> = <number> | <expression> - Display value of given variable\n";
cout << "EXIT! - Exit the SNOL environment\n";
}
// Storage for variables and their types
unordered_map<string, pair<string, float>> variables;
// Function to handle the BEG command
void beg(const string& varName) {
// Validate variable name
if (!regex_match(varName, regex("^[a-zA-Z_][a-zA-Z0-9_]*$"))) {
cout << "SNOL> Error: Invalid variable name [" << varName << "] Enter HELP for a list of available commands." << endl;
return;
}
cout << "SNOL> Please enter value for [" << varName << "]\nInput: ";
string input;
getline(cin, input);
stringstream ss(input);
float value;
ss >> value;
// Check for invalid number format
if (ss.fail() || !ss.eof()) {
cout << "SNOL> Invalid number format [" << input << "] Enter HELP for a list of available commands." << endl;
return;
}
// Check if the input is a float or int
if (input.find('.') != string::npos) {
variables[varName] = {"float", value};
} else {
variables[varName] = {"int", value};
}
}
// Function to handle the PRINT command
void print(const string& varName) {
if (variables.find(varName) != variables.end()) {
cout << "SNOL> [" << varName << "] = " << variables[varName].second << endl;
} else {
cout << "SNOL> Error! [" << varName << "] is not defined! Enter HELP for a list of available commands." << endl;
}
}
// Helper function to get the precedence of an operator
int getPrecedence(const string& op) {
if (op == "+" || op == "-") return 1;
if (op == "*" || op == "/" || op == "%") return 2;
return 0;
}
// Helper function to perform arithmetic operations
float applyOperator(float a, float b, const string& op) {
if (op == "+") return a + b;
if (op == "-") return a - b;
if (op == "*") return a * b;
if (op == "/") return a / b;
if (op == "%") return fmod(a, b);
throw invalid_argument("SNOL> Invalid operator");
}
// Function to check for balanced parentheses
bool checkParentheses(const vector<Token>& tokens) {
stack<char> parentheses;
for (const auto& token : tokens) {
if (token.type == LPAREN) {
parentheses.push('(');
} else if (token.type == RPAREN) {
if (parentheses.empty()) {
return false;
}
parentheses.pop();
}
}
return parentheses.empty();
}
// Function to evaluate an arithmetic expression using the Shunting Yard algorithm and the Reverse Polish Notation (RPN) evaluation
float evaluateExpression(const vector<Token>& tokens, const string& type) {
stack<float> values;
stack<string> operators;
bool containsInt = false;
bool containsFloat = false;
for (const auto& token : tokens) {
if (token.type == NUMBER) {
float value = stof(token.value);
values.push(value);
if (token.value.find('.') != string::npos) {
containsFloat = true;
} else {
containsInt = true;
}
} else if (token.type == VARIABLE) {
if (variables.find(token.value) == variables.end()) {
cout << "SNOL> Error! [" << token.value << "] is not defined! Enter HELP for a list of available commands." << endl;
throw invalid_argument("Undefined variable");
}
values.push(variables[token.value].second);
if (variables[token.value].first == "float") {
containsFloat = true;
} else {
containsInt = true;
}
} else if (token.type == OPERATOR) {
if (token.value == "%" && (containsFloat || (!values.empty() && modf(values.top(), &values.top()) != 0))) {
cout << "SNOL> Error! Modulo operation is not allowed on floats. Enter HELP for a list of available commands." << endl;
throw invalid_argument("Modulo on floats");
}
while (!operators.empty() && getPrecedence(operators.top()) >= getPrecedence(token.value)) {
float b = values.top();
values.pop();
float a = values.top();
values.pop();
string op = operators.top();
operators.pop();
values.push(applyOperator(a, b, op));
}
operators.push(token.value);
} else if (token.type == LPAREN) {
operators.push(token.value);
} else if (token.type == RPAREN) {
while (!operators.empty() && operators.top() != "(") {
float b = values.top();
values.pop();
float a = values.top();
values.pop();
string op = operators.top();
operators.pop();
values.push(applyOperator(a, b, op));
}
if (operators.empty() || operators.top() != "(") {
cout << "SNOL> Mismatched parentheses. Enter HELP for a list of available commands." << endl;
throw invalid_argument("Mismatched parentheses.");
}
operators.pop(); // Pop the left parenthesis
}
}
while (!operators.empty()) {
float b = values.top();
values.pop();
float a = values.top();
values.pop();
string op = operators.top();
operators.pop();
values.push(applyOperator(a, b, op));
}
// Check for type matching
if (containsInt && containsFloat) {
cout << "SNOL> Error! Operands must be of the same type in an arithmetic operation!" << endl;
throw invalid_argument("Type mismatch");
}
return values.top();
}
// Function to handle the assignment command
void assignVar(unordered_map<string, pair<string, float>>& variables, const string& givenVar, const vector<Token>& tokens) {
if (tokens.size() >= 3 && tokens[1].type == ASSIGNMENT) {
vector<Token> exprTokens(tokens.begin() + 2, tokens.end());
// Check if expression is valid
if (exprTokens.empty() || (exprTokens[0].type != NUMBER && exprTokens[0].type != VARIABLE && exprTokens[0].type != LPAREN)) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
return;
}
// Check for mismatched types in the expression
string type = "int";
for (const auto& token : exprTokens) {
if (token.type == NUMBER && token.value.find('.') != string::npos) {
type = "float";
break;
} else if (token.type == VARIABLE && variables.find(token.value) != variables.end() && variables[token.value].first == "float") {
type = "float";
break;
}
}
// Validate that the expression does not contain invalid sequences
bool lastWasOperator = false;
for (const auto& token : exprTokens) {
if (token.type == OPERATOR) {
if (lastWasOperator) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
return;
}
lastWasOperator = true;
} else {
lastWasOperator = false;
}
}
// Check for balanced parentheses
if (!checkParentheses(exprTokens)) {
cout << "SNOL> Mismatched parentheses. Enter HELP for a list of available commands." << endl;
return;
}
try {
float result = evaluateExpression(exprTokens, type);
variables[givenVar] = {type, result};
} catch (const invalid_argument& e) {
// Error message already printed, do nothing
}
} else {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
}
}
// Function to handle non-assignment operations
void handleOperation(const vector<Token>& tokens) {
if (tokens.size() >= 3 && tokens[1].type == OPERATOR) {
vector<Token> exprTokens(tokens.begin(), tokens.end());
// Check if expression is valid
if (exprTokens.empty() || (exprTokens[0].type != NUMBER && exprTokens[0].type != VARIABLE && exprTokens[0].type != LPAREN)) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
return;
}
// Check for mismatched types in the expression
string type = "int";
for (const auto& token : exprTokens) {
if (token.type == NUMBER && token.value.find('.') != string::npos) {
type = "float";
break;
} else if (token.type == VARIABLE && variables.find(token.value) != variables.end() && variables[token.value].first == "float") {
type = "float";
break;
}
}
// Validate that the expression does not contain invalid sequences
bool lastWasOperator = false;
for (const auto& token : exprTokens) {
if (token.type == OPERATOR) {
if (lastWasOperator) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
return;
}
lastWasOperator = true;
} else {
lastWasOperator = false;
}
}
// Check for balanced parentheses
if (!checkParentheses(exprTokens)) {
cout << "Mismatched parentheses" << endl;
return;
}
try {
evaluateExpression(exprTokens, type);
} catch (const invalid_argument& e) {
// Error message already printed, do nothing
}
} else {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
}
}
int main() {
cout << "The SNOL Environment is now active, you may proceed with giving your commands. Enter HELP for full command list.";
while (true) {
cout << "\n\nCommand: ";
string command;
getline(cin, command);
vector<Token> tokens = tokenize(command);
if (tokens.empty()) {
cout << "\n\nPlease enter a command.";
continue;
}
string cmd = tokens[0].value;
if (cmd == "HELP") {
printHelp();
} else if (cmd == "EXIT!") {
cout << "\n\nInterpreter is now terminated...";
break;
} else if (cmd == "BEG") {
if (tokens.size() != 2) {
cout << "SNOL> Error! BEG command requires exactly one variable name or the variable name is invalid.";
} else if(tokens[1].type == COMMAND){
cout << "SNOL> Error! keywords cannot be used as variable!";
} else {
beg(tokens[1].value);
}
} else if (cmd == "PRINT") {
if (tokens.size() != 2) {
cout << "SNOL> Error! PRINT command requires exactly one variable name or the variable name is invalid.";
}else if(tokens[1].type == COMMAND){
cout << "SNOL> Error! keywords cannot be used as variable!";
} else {
print(tokens[1].value);
}
} else if (tokens[0].type == VARIABLE && tokens.size() > 1 && tokens[1].type == ASSIGNMENT) {
// Handle variable assignment
bool hasCommand = false;
for (const auto& token : tokens) {
if (token.type == COMMAND) {
hasCommand = true;
break;
}
}
if (hasCommand) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
} else {
assignVar(variables, tokens[0].value, tokens);
}
} else if (tokens.size() >= 3 && tokens[1].type == OPERATOR) {
// Handle non-assignment operations
bool hasCommand = false;
for (const auto& token : tokens) {
if (token.type == COMMAND) {
hasCommand = true;
break;
}
}
if (hasCommand) {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands." << endl;
} else {
handleOperation(tokens);
}
} else if (tokens[0].type == VARIABLE && tokens.size() == 1) {
continue;
} else if (tokens[0].type == NUMBER && tokens.size() == 1) {
continue;
}else {
cout << "SNOL> Unknown command! Does not match any valid command of the language. Enter HELP for a list of available commands.";
}
}
return 0;
}