-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.cpp
832 lines (677 loc) · 23.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
// =======================================================
// ====================== INCLUDES =======================
// =======================================================
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <map>
#include <vector>
#include "mewlib/mewmewLexer.h"
#include "mewlib/mewmewParser.h"
#include "mewlib/mewmewBaseVisitor.h"
#include <chrono>
// =================== END INCLUDES ======================
//========================================================
//===================== NAMESPACES =======================
//========================================================
using namespace std;
using namespace antlr4;
using namespace antlrcpp;
//=================== END NAMESPACES =====================
map<string, float> _vartable; // VARTABLE aka. Symbol Table to Hold Variables
//========================================================
//================== UTILITY FUNCTIONS ===================
//========================================================
/*
* -------------------------------------------------------
* Splits a String with given delimiter
* -------------------------------------------------------
*/
vector<string> stringsplit(string input , const string &delimiter){
string token;
vector<string> result;
size_t pos = 0;
while((pos = input.find(delimiter)) != string::npos){
token = input.substr(0 , pos);
result.push_back(token);
input.erase(0 , pos + delimiter.length());
}
result.push_back(input);
return result;
}
/*
* ------------------------------------------------------
* Converts MewMew number to traditional number
* ------------------------------------------------------
*/
float mew_to_float(const string &m){
try{
float n;
if (!(m.find("mew") != string::npos)){
throw runtime_error("Meow Error : Invalid Mew Number!");
}
if (m.find(".") != string::npos){
vector<string> sp = stringsplit(m , ".");
string x = "";
x+= to_string(sp[0].size()/3);
x+= ".";
x+= to_string(sp[1].size()/3);
n = stof(x);
}else{
n = m.size()/3;
}
return n;
}
catch(runtime_error &e){
cerr << "/ᐠx ‸xᐟ\\ " << e.what() << endl;
exit(-1);
}
}
float execute_scratch_func(const int count , const float expr){
switch (count) {
case 1:
return sqrt(expr);
case 2:
return expr * 2;
case 3:
return expr * 5;
case 4:
return expr * 10;
case 5:
return expr * 100;
default:
return expr;
}
}
bool is_formalnum(const string &s){
int state = 0;
for (size_t i = 0; i < s.size(); i++) {
switch (state) {
case 0: // First digit of integer part
if (s[i] >= '0' && s[i] <= '9') {
state = 1;
} else if (s[i] != '-' || i != 0) { // Number can start with a minus, but a digit will still be required
return false; // Doesn't start with a digit or minus sign, not a number
}
break;
case 1: // Rest of integer part
if (s[i] == '.') {
state = 2; // Start parsing decimal part
} else if (s[i] < '0' || s[i] > '9') {
return false; // Not a digit or decimal point, not a number
}
break;
case 2: // First digit of decimal part
if (s[i] >= '0' && s[i] <= '9') {
state = 3;
} else {
return false; // Decimal point must be followed by at least one digit
}
break;
case 3: // Rest of decimal part
if (s[i] < '0' || s[i] > '9') {
return false; // Not a digit, not a number
}
break;
}
}
return state == 1 || state == 3;
}
// ================ END UTILITY FUNCTIONS ==================
//==========================================================
//================== ERROR HANDLER CLASS ===================
//==========================================================
class MewErr : public BaseErrorListener{
public:
void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line, size_t charPositionInLine, const std::string &msg, std::exception_ptr e) override{
underlineError(recognizer, offendingSymbol, line, charPositionInLine);
cout << "/ᐠx ‸xᐟ\\ Syntax Error! at line " << line << " -> " << msg << endl;
}
protected:
void underlineError(Recognizer *recognizer , Token *offendingSymbol , size_t line , int charPositionInLine){
CommonTokenStream* tokens = (CommonTokenStream*)recognizer->getInputStream();
string input = tokens->getTokenSource()->getInputStream()->toString();
vector<string> lines = stringsplit(input, "\n");
string errorline = lines[line-1];
cout << errorline << endl;
for (int i = 0; i < charPositionInLine; ++i) cout << "\e[31m~";
int start = offendingSymbol->getStartIndex();
int stop = offendingSymbol->getStopIndex();
if (start>=0 && stop >=0){
for(int i = start; i<= stop ; ++i) cout << u8"\e[31m^";
}
cout << "\e[39m\n";
}
};
//=============== END ERROR HANDLER CLASS =================
//=========================================================
//============== EVALUATOR VISITOR CLASS ==================
//=========================================================
class MewMewEval : public mewmewBaseVisitor{
public:
/*
* -----------------------------------------------------
* Handles Assign Expressions
*
* first it checks if variable with given name already
* exists [a1] , if yes , then replace the previous
* value of the variable with new evaluated value [a2],
* Otherwise , it creates a new item in symbol table
* [a3].
* Then finally returns 0
*
* -> m = mewmew;
*
* -----------------------------------------------------
*/
antlrcpp::Any visitAssignExpr(mewmewParser::AssignExprContext *ctx) override{
string id = ctx->ID()->toString();
float value = visit(ctx->expr());
if (_vartable.count(id)){ // <--------- a1
_vartable[id] = value; // <--------- a2
}else{
_vartable.insert(pair<string , float>(id , value)); // <--------a3
}
return 0;
}
/*
* ---------------------------------------------------
* Handles Print aka. Meow Say Statements
*
* first it evaluates the given expression and finally
* prints it to stdout
*
* -> ::mewmew;
* => 2
*
* ---------------------------------------------------
*/
antlrcpp::Any visitPrintCharExpr(mewmewParser::PrintCharExprContext *ctx) override{
vector<float> exprlist = visit(ctx->exprlist());
for (float item:exprlist) {
cout << char(item) ;
}
cout << endl;
return 0;
}
antlrcpp::Any visitPrintExprList(mewmewParser::PrintExprListContext *ctx) override{
vector<float> exprlist = visit(ctx->exprlist());
for (float item:exprlist) {
cout << item ;
}
cout << endl;
return 0;
}
antlrcpp::Any visitExprListExpr(mewmewParser::ExprListExprContext *ctx) override{
vector<float> elist;
for (int i = 0 ; i < ctx->expr().size() ; ++i){
float _temp = visit(ctx->expr(i));
elist.push_back(_temp);
}
return elist;
}
/*
* ---------------------------------------------------
* Handles Abs Statements
*
* first it evaluates the given expression and then
* returns the abs value of it.
*
* -> m = -mewmew;
* -> ::~m;
* => 2
* ---------------------------------------------------
*/
antlrcpp::Any visitAbsExpr(mewmewParser::AbsExprContext *ctx) override{
float expr = visit(ctx->expr());
return abs(expr);
}
antlrcpp::Any visitScratchExpr(mewmewParser::ScratchExprContext *ctx) override{
string us = ctx->SCRATCH()->toString();
float expr = visit(ctx->expr());
return execute_scratch_func(us.length() , expr);
}
/*
* ---------------------------------------------------
* Handles Unary Minus Statements
*
* first it evaluates the given expression and then
* returns the unary minus value of it.
*
* -> m = -mewmew;
* -> ::m;
* => -2
*
* ---------------------------------------------------
*/
antlrcpp::Any visitUnaryExpr(mewmewParser::UnaryExprContext *ctx) override{
float exp = visit(ctx->expr());
return -exp;
}
/*
* ---------------------------------------------------
* Handles Modulus (%) Statements
*
* It returns modulus of two given expression
*
* -> m = mewmewmew % mewmew;
* -> ::m;
* => 1
*
* ---------------------------------------------------
*/
antlrcpp::Any visitModExpr(mewmewParser::ModExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
return float((int)left % (int)right);
}
/*
* ---------------------------------------------------
* Handles Addition (+) or Substraction (-) Statements
*
* first it checks the operator of the statement , if
* it is '+' (ADD) [b1] , the returns left expression
* + right expression otherwise it returns left
* expression - right expression
*
* -> m = mew + mewmew - mew ;
* -> ::m;
* => 2
* ---------------------------------------------------
*/
antlrcpp::Any visitAddSubExpr(mewmewParser::AddSubExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
if (ctx->op->getType() == mewmewParser::ADD){ // <----------------- b1
return left + right;
}else{
return left - right;
}
}
/*
* ---------------------------------------------------
* Handles Multiplication (*) or Division (/) Statements
*
* first it checks the operator of the statement , if
* it is '*' (MUL) [b2] , the returns left expression
* x right expression otherwise it returns left
* expression ÷ right expression
*
* -> m = mewmew * mewmew / mewmew ;
* -> ::m;
* => 2
* ---------------------------------------------------
*/
antlrcpp::Any visitMulDivExpr(mewmewParser::MulDivExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
if (ctx->op->getType() == mewmewParser::MUL){ // <------- b2
return left * right;
}else{
return left / right;
}
}
/*
* ---------------------------------------------------
* Handles Power (**) Statements
*
* Evaluates left and right expressions , then
* returns Left to the power Right using cmath library.
*
* -> m = mewmew ** mewmewmew ;
* -> ::m;
* => 8
* ---------------------------------------------------
*/
antlrcpp::Any visitPowExpr(mewmewParser::PowExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
return pow(left , right);
}
/*
* ---------------------------------------------------
* Handles Is Equal to (==) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is equal to
* right expressions otherwise returns 0 (False).
*
* -> m = mewmew == mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitEqExpr(mewmewParser::EqExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left == right;
return result;
}
/*
* ---------------------------------------------------
* Handles Is Greater than Equal to (>=) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is greater than equal to
* right expressions otherwise returns 0 (False).
*
* -> m = mewmewmew >= mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitGeExpr(mewmewParser::GeExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left >= right;
return result;
}
/*
* ---------------------------------------------------
* Handles Is Greater than (>) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is greater than
* right expressions otherwise returns 0 (False).
*
* -> m = mewmewmew > mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitGtExpr(mewmewParser::GtExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left > right;
return result;
}
/*
* ---------------------------------------------------
* Handles Is Less than Equal to (<=) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is less than
* equal to right expressions otherwise returns 0
* (False).
*
* -> m = mew <= mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitLeExpr(mewmewParser::LeExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left <= right;
return result;
}
/*
* ---------------------------------------------------
* Handles Is Less than (<) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is less than
* right expressions otherwise returns 0 (False).
*
* -> m = mew < mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitLtExpr(mewmewParser::LtExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left < right;
return result;
}
/*
* ---------------------------------------------------
* Handles Is Not Equal to (!=) Statements
*
* First evaluates left and right expressions , then
* returns 1 (True) if left expression is not equal to
* right expressions otherwise returns 0 (False).
*
* -> m = mew != mewmew ;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitNeExpr(mewmewParser::NeExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left != right;
return result;
}
/*
* ---------------------------------------------------
* Handles And (&) Expressions
*
* First evaluates left and right expressions , then
* returns 1 (True) if both expression are truthy
* otherwise returns 0 (False).
*
* -> m = mew == mew & mewmew == mewmew;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitAndExpr(mewmewParser::AndExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left && right;
return result;
}
/*
* ---------------------------------------------------
* Handles Or (|) Expressions
*
* First evaluates left and right expressions , then
* returns 1 (True) if any of the expression is
* truthy otherwise returns 0 (False).
*
* -> m = mew == mewmew | mewmew == mewmew;
* -> ::m ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitOrExpr(mewmewParser::OrExprContext *ctx) override{
float left = visit(ctx->expr(0));
float right = visit(ctx->expr(1));
float result = left || right;
return result;
}
/*
* ---------------------------------------------------
* Handles Identifier Statements/Expressions
*
* First it checks if any identifier exists in the
* symbol table with the given name [c1] , if yes,
* it returns the value associated with the
* identifier from symbol table otherwise it prints an
* error message saying the variable is undeclared [c2]
*
* -> m = mewmew ;
* -> ::m ;
* => 2
* ---------------------------------------------------
*/
antlrcpp::Any visitIdExpr(mewmewParser::IdExprContext *ctx) override {
string id = ctx->ID()->toString();
if(_vartable.count(id) == 1){ // <------ c1
return _vartable[id];
}else{
cerr << endl << "/ᐠ–ꞈ–ᐟ\\ Undeclared Variable '" << id << "'" << endl; // <--------- c2
exit(1);
}
}
/*
* ---------------------------------------------------
* Handles Number (mewmew......) Expressions
*
* First it extracts the mewmew... string , with help
* of utility function `mew_to_float` function , it
* converts the string to an equivalent float value.
*
* Mew Numbers can contain decimal (.) to make a
* 'real' floating point number.
*
* for example , `mewmew` will be converted to 2 and
* `mewmew.mewmewmew` will be converted to 2.3
*
* -> m = mewmew.mew ;
* -> ::m ;
* => 2.1
* ---------------------------------------------------
*/
antlrcpp::Any visitNumExpr(mewmewParser::NumExprContext *ctx) override{
string m_ = ctx->MEWNUMBER()->toString();
float x = mew_to_float(m_);
return x;
}
antlrcpp::Any visitScanExpr(mewmewParser::ScanExprContext *ctx) override{
string id = ctx->ID()->toString();
float value;
string _temp;
cin >> _temp;
if (is_formalnum(_temp)){
value = stof(_temp);
}else{
value = mew_to_float(_temp);
if (_temp[0] == '-'){
value = -value;
}
}
/* cout << value << endl; */
if (_vartable.count(id)){ // <--------- a1
_vartable[id] = value; // <--------- a2
}else{
_vartable.insert(pair<string , float>(id , value)); // <--------a3
}
return 0;
}
/*
* ---------------------------------------------------
* Handles If Statements
*
* First it evaluates condition expression , if the
* value is 1 (True) , the statement body is executed
*
* -> mewmew > mew ? ::mewmew; ;
* => 2
* ---------------------------------------------------
*/
antlrcpp::Any visitIfExpr(mewmewParser::IfExprContext *ctx) override{
float cond = visit(ctx->expr());
if (cond == 1){
visit(ctx->stmts());
}
return cond;
}
/*
* ---------------------------------------------------
* Handles If Else Statements
*
* First it evaluates condition expression , if the
* value is 1 (True) , the truthy statement body is
* executed otherwise else statement body is
* executed
*
* -> mewmew < mew ? ::mewmew; : ::mew; ;
* => 1
* ---------------------------------------------------
*/
antlrcpp::Any visitIfElseExpr(mewmewParser::IfElseExprContext *ctx) override{
float cond = visit(ctx->expr());
if (cond == 1) {
visit(ctx->stmts(0));
}else{
visit(ctx->stmts(1));
}
return cond;
}
/*
* ---------------------------------------------------
* Handles Repeat Loop aka. Meow Loop Statements
*
* First it evaluates condition expression , then it
* executes the body N times , where N is value of
* returned by the condition expression
*
* -> m = mew;
* -> @mewmewmew: m = m + mew; ;
* -> ::m;
* => 4
* ---------------------------------------------------
*/
antlrcpp::Any visitRepeatExpr(mewmewParser::RepeatExprContext *ctx) override{
float con = visit(ctx->expr());
for (int i = 1 ; i <= con ; ++i){
visit(ctx->stmts());
}
return con;
}
};
//============ END EVALUATOR VISITOR CLASS ================
/*
* --------------------------------------------------------
* Parses and Evaluates Given Filename
*
* Mostly Copy paste from the book
*
* what it does is , open the file , tokenize the file.
* Feed the tokens to the parser , then a parse tree
* is created, then we tell our visitor class to visit
* the parse tree and execute the commands
*
* ---------------------------------------------------------
*/
void parse(ANTLRFileStream input){
mewmewLexer lexer(&input);
CommonTokenStream tokens(&lexer);
tokens.fill();
mewmewParser parser(&tokens);
parser.removeErrorListeners();
MewErr errorlistener;
parser.addErrorListener(&errorlistener);
tree::ParseTree* tree = parser.prog();
MewMewEval* mv = new MewMewEval();
mv->visit(tree);
}
/*
* --------------------------------------------------------
* Driver Function
*
* It checks if the user has supplied a filename to
* execute , if not , it prints the usage , else
* first it checks if the given filename exits, if
* exists , it calls the parse function to parse the
* user supplied filename , otherwise prints an error
* saying that the filename doesnot exist.
*
* --------------------------------------------------------
*/
int main(int argc, char **argv) {
if (argc < 2) {
cout << endl << u8"/ᐠ。ꞈ。ᐟ\\ MewMew - Program in Cats' Language!" << endl << endl;
cout << "No Specified filename to execute :(" << endl;
cerr << "Usage: ./mewmew FILENAME" << endl;
} else if (argc == 2) {
string path = argv[1]; // filename
ifstream infile(path);
if(infile.good()){ // Checks if file exits
/* auto start = chrono::high_resolution_clock::now(); */
infile.close();
ANTLRFileStream filename(path);
parse(filename);
/* auto stop = chrono::high_resolution_clock::now(); */
/* cout << "-- " << chrono::duration_cast<chrono::microseconds>(stop-start).count() << " --" << endl; */
}else{
cout << "MEOW!! File '" << path << "' " << "Doesn't Exist!" << endl;
}
}
return 0;
}