-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnarivm.cpp
2245 lines (2145 loc) · 63.8 KB
/
narivm.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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -- NariVM for Katalyn in C++ by Lartu (25G24 00:17) --
#include <iostream>
#include <map>
#include <unordered_map>
#include <stack>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <limits>
#include <thread>
#include <chrono>
#include <queue>
#include <fstream>
#include <set>
#include <sys/stat.h>
#include "lib/tiny-process-library/process.hpp"
#include "lib/linenoise.hpp"
using namespace std;
using namespace TinyProcessLib;
#define NUMB 1 // Numeric Value
#define TEXT 2 // String Value
#define TABLE 3 // Table Value
#define NIL 5 // Null Value
#define ITER 6 // Iterator Value
#define LISTLIMIT 7 // List Limit Value
size_t pc = 0; // Program Counter
void raise_nvm_error(string error_message);
extern const char __attribute__((weak)) user_code[] = "";
string get_type_name(char type)
{
switch (type)
{
case NUMB:
return "NUMBER";
case TEXT:
return "TEXT";
case TABLE:
return "TABLE";
case NIL:
return "NIL";
case ITER:
return "ITERATOR";
case LISTLIMIT:
return "LISTLIMIT";
}
return "???";
}
enum Opcode : uint8_t
{
PUSH,
PNIL,
ADDV,
SUBT,
MULT,
FDIV,
IDIV,
POWR,
MODL,
ISGT,
ISLT,
ISGE,
ISLE,
ISEQ, // Is Equal
ISNE, // Is Not Equal
VSET,
GSET,
VGET,
JOIN,
SSTR,
REPL,
JUMP,
CALL,
RTRN,
JPIF, // Jump If False
TABL,
PSET,
PGET,
ARRR,
DUPL,
DISP,
ACCP,
POPV,
EXIT,
UNST,
PUST,
FORW, // File Open for Read and Write
FORA, // File Open for Read and Append
RFIL, // Read File
FCLS, // File Close
RLNE, // File Read Line
FWRT, // File Write
LNOT,
LAND,
LGOR,
TRIM,
SLEN, // String or Table Length
SWAP,
ISIN,
FLOR,
ADSC,
DLSC,
EXEC,
WAIT,
KEYS,
GITR,
NEXT,
PLIM,
EXPL, // Explode
MXPL, // Multi eXPLode
FORE, // File Open for REad
ISOP, // IS file OPen?
ISNIL,
DEBUG,
};
Opcode opcode_from_string(string_view str)
{
static unordered_map<string_view, Opcode> str_to_opcode = {
{"PUSH", Opcode::PUSH},
{"PNIL", Opcode::PNIL},
{"ADDV", Opcode::ADDV},
{"SUBT", Opcode::SUBT},
{"MULT", Opcode::MULT},
{"FDIV", Opcode::FDIV},
{"IDIV", Opcode::IDIV},
{"POWR", Opcode::POWR},
{"MODL", Opcode::MODL},
{"ISGT", Opcode::ISGT},
{"ISLT", Opcode::ISLT},
{"ISGE", Opcode::ISGE},
{"ISLE", Opcode::ISLE},
{"ISEQ", Opcode::ISEQ},
{"ISNE", Opcode::ISNE},
{"VSET", Opcode::VSET},
{"GSET", Opcode::GSET},
{"VGET", Opcode::VGET},
{"JOIN", Opcode::JOIN},
{"SSTR", Opcode::SSTR},
{"REPL", Opcode::REPL},
{"JUMP", Opcode::JUMP},
{"CALL", Opcode::CALL},
{"RTRN", Opcode::RTRN},
{"JPIF", Opcode::JPIF},
{"TABL", Opcode::TABL},
{"PSET", Opcode::PSET},
{"PGET", Opcode::PGET},
{"ARRR", Opcode::ARRR},
{"DUPL", Opcode::DUPL},
{"DISP", Opcode::DISP},
{"ACCP", Opcode::ACCP},
{"POPV", Opcode::POPV},
{"EXIT", Opcode::EXIT},
{"UNST", Opcode::UNST},
{"PUST", Opcode::PUST},
{"FORW", Opcode::FORW},
{"FORA", Opcode::FORA},
{"RFIL", Opcode::RFIL},
{"FCLS", Opcode::FCLS},
{"RLNE", Opcode::RLNE},
{"FWRT", Opcode::FWRT},
{"LNOT", Opcode::LNOT},
{"LAND", Opcode::LAND},
{"LGOR", Opcode::LGOR},
{"TRIM", Opcode::TRIM},
{"SLEN", Opcode::SLEN},
{"SWAP", Opcode::SWAP},
{"ISIN", Opcode::ISIN},
{"FLOR", Opcode::FLOR},
{"ADSC", Opcode::ADSC},
{"DLSC", Opcode::DLSC},
{"EXEC", Opcode::EXEC},
{"WAIT", Opcode::WAIT},
{"KEYS", Opcode::KEYS},
{"GITR", Opcode::GITR},
{"NEXT", Opcode::NEXT},
{"PLIM", Opcode::PLIM},
{"EXPL", Opcode::EXPL},
{"MXPL", Opcode::MXPL},
{"FORE", Opcode::FORE},
{"ISOP", Opcode::ISOP},
{"NIL?", Opcode::ISNIL},
{"DBUG", Opcode::DEBUG},
};
return str_to_opcode[str];
}
string wrap_text(const string &text, size_t maxLineLength)
{
string result = "";
size_t current_line_len = 0;
for (size_t i = 0; i < text.size(); ++i)
{
if (text[i] == ' ')
{
if (current_line_len >= maxLineLength)
{
result += "\n";
current_line_len = 0;
}
else if (current_line_len > 0)
{
result += " ";
current_line_len += 1;
}
}
else
{
result += string() + text[i];
current_line_len += 1;
if (text[i] == '\n')
{
current_line_len = 0;
}
}
}
return result;
}
string_view opcode_as_string(Opcode opcode)
{
switch (opcode)
{
case Opcode::PUSH:
return "PUSH";
case Opcode::PNIL:
return "PNIL";
case Opcode::ADDV:
return "ADDV";
case Opcode::SUBT:
return "SUBT";
case Opcode::MULT:
return "MULT";
case Opcode::FDIV:
return "FDIV";
case Opcode::IDIV:
return "IDIV";
case Opcode::POWR:
return "POWR";
case Opcode::MODL:
return "MODL";
case Opcode::ISGT:
return "ISGT";
case Opcode::ISLT:
return "ISLT";
case Opcode::ISGE:
return "ISGE";
case Opcode::ISLE:
return "ISLE";
case Opcode::ISEQ:
return "ISEQ"; // Is Equal
case Opcode::ISNE:
return "ISNE"; // Is Not Equal
case Opcode::VSET:
return "VSET";
case Opcode::GSET:
return "GSET";
case Opcode::VGET:
return "VGET";
case Opcode::JOIN:
return "JOIN";
case Opcode::SSTR:
return "SSTR";
case Opcode::REPL:
return "REPL";
case Opcode::JUMP:
return "JUMP";
case Opcode::CALL:
return "CALL";
case Opcode::RTRN:
return "RTRN";
case Opcode::JPIF:
return "JPIF"; // Jump If False
case Opcode::TABL:
return "TABL";
case Opcode::PSET:
return "PSET";
case Opcode::PGET:
return "PGET";
case Opcode::ARRR:
return "ARRR";
case Opcode::DUPL:
return "DUPL";
case Opcode::DISP:
return "DISP";
case Opcode::ACCP:
return "ACCP";
case Opcode::POPV:
return "POPV";
case Opcode::EXIT:
return "EXIT";
case Opcode::UNST:
return "UNST";
case Opcode::PUST:
return "PUST";
case Opcode::FORW:
return "FORW"; // File Open for Read and Write
case Opcode::FORA:
return "FORA"; // File Open for Read and Append
case Opcode::RFIL:
return "RFIL"; // Read File
case Opcode::FCLS:
return "FCLS"; // File Close
case Opcode::RLNE:
return "RLNE"; // File Read Line
case Opcode::FWRT:
return "FWRT"; // File Write
case Opcode::LNOT:
return "LNOT";
case Opcode::LAND:
return "LAND";
case Opcode::LGOR:
return "LGOR";
case Opcode::TRIM:
return "TRIM";
case Opcode::SLEN:
return "SLEN"; // String or Table Length
case Opcode::SWAP:
return "SWAP";
case Opcode::ISIN:
return "ISIN";
case Opcode::FLOR:
return "FLOR";
case Opcode::ADSC:
return "ADSC";
case Opcode::DLSC:
return "DLSC";
case Opcode::EXEC:
return "EXEC";
case Opcode::WAIT:
return "WAIT";
case Opcode::KEYS:
return "KEYS";
case Opcode::GITR:
return "GITR";
case Opcode::NEXT:
return "NEXT";
case Opcode::PLIM:
return "PLIM";
case Opcode::EXPL:
return "EXPL";
case Opcode::MXPL:
return "MXPL";
case Opcode::FORE:
return "FORE";
case Opcode::ISOP:
return "ISOP";
case Opcode::ISNIL:
return "NIL?";
case Opcode::DEBUG:
return "DBUG";
default:
raise_nvm_error("Unknown Nambly opcode");
}
}
#define EPSILON 0.000000
bool num_eq(double a, double b)
{
return fabs(a - b) < numeric_limits<double>::epsilon();
}
string double_to_string(double value)
{
// Check if the value is effectively an integer
if (num_eq(value, floor(value)))
{
return to_string(static_cast<long long>(value)); // Convert to integer string
}
else
{
// Otherwise, keep the precision for non-integers
string str_rep = to_string(value);
while (str_rep[str_rep.size() - 1] == '0' || str_rep[str_rep.size() - 1] == '.')
{
str_rep = str_rep.substr(0, str_rep.size() - 1);
}
return str_rep;
}
}
class Value
{
private:
char type;
bool has_num_rep;
bool has_str_rep;
string str_rep;
double num_rep;
shared_ptr<map<string, Value>> table_rep;
shared_ptr<queue<string> /**/> iterator_elements;
void reset_values()
{
has_num_rep = false;
has_str_rep = false;
table_rep = nullptr;
}
public:
void set_string_value(const string &value)
{
reset_values();
this->str_rep = value;
this->type = TEXT;
has_str_rep = true;
}
void set_number_value(double value)
{
reset_values();
this->num_rep = value;
this->type = NUMB;
has_num_rep = true;
}
void set_table_value()
{
reset_values();
this->table_rep = std::make_shared<map<string, Value>>();
this->type = TABLE;
}
void set_nil_value()
{
reset_values();
this->type = NIL;
}
void set_listlimit_value()
{
reset_values();
this->type = LISTLIMIT;
}
void set_iterator_value()
{
reset_values();
this->iterator_elements = std::make_shared<queue<string>>();
this->type = ITER;
}
char get_type()
{
return type;
}
map<string, Value> *get_table()
{
return table_rep.get();
}
queue<string> *get_iterator_queue()
{
return iterator_elements.get();
}
const string &get_raw_string_value() const
{
// Gets the string value of the value, even if it wasn't set, used for arguments.
return str_rep;
}
const string &get_as_string()
{
if (has_str_rep)
{
return str_rep;
}
else
{
if (type == NIL)
{
raise_nvm_error("Can't convert NIL value to string.");
}
else if (type == LISTLIMIT)
{
raise_nvm_error("Can't convert LISTLIMIT value to string.");
}
else if (type == ITER)
{
raise_nvm_error("Can't convert iterator value to string.");
}
else if (type == TABLE)
{
queue<string> table_values;
for (auto it = get_table()->begin(); it != get_table()->end(); ++it)
{
string table_string = "'" + it->first + "':";
if (it->second.get_type() == TEXT)
{
table_string += "'" + it->second.get_as_string() + "'";
}
else
{
table_string += it->second.get_as_string();
}
table_values.push(table_string);
}
string return_value = "[";
while (!table_values.empty())
{
return_value += table_values.front();
if (table_values.size() > 1)
{
return_value += ", ";
}
table_values.pop();
}
str_rep = return_value + "]";
}
else if (type == NUMB)
{
str_rep = double_to_string(get_as_number());
}
return str_rep;
}
}
double get_as_number()
{
if (has_num_rep)
{
return num_rep;
}
else
{
if (type == NIL)
{
raise_nvm_error("Can't convert NIL value to number.");
}
else if (type == LISTLIMIT)
{
raise_nvm_error("Can't convert LISTLIMIT value to number.");
}
else if (type == ITER)
{
raise_nvm_error("Can't convert iterator value to number.");
}
else if (type == TABLE)
{
num_rep = table_rep != nullptr ? num_rep = table_rep->size() : 0;
}
else if (type == TEXT)
{
try
{
num_rep = stod(str_rep);
}
catch (const invalid_argument &ia)
{
raise_nvm_error("Can't convert value " + str_rep + " to number.");
}
}
return num_rep;
}
}
};
class Command
{
private:
Opcode opcode;
vector<Value> arguments;
const size_t line_number;
const string filename;
// Only for branch instructions
size_t branch_target;
public:
Command(const string command, const size_t line_number, const string filename) : opcode(opcode_from_string(command)), line_number(line_number), filename(filename) {};
Opcode get_opcode() const { return opcode; }
string_view get_command() const { return opcode_as_string(opcode); }
const vector<Value> &get_arguments() const { return arguments; }
void add_argument(const Value &value)
{
arguments.push_back(value);
}
const string get_debug_string() const
{
string debug_string = string(get_command());
if (!arguments.empty())
{
debug_string += " ";
for (size_t i = 0; i < arguments.size(); ++i)
{
debug_string += "[" + arguments[i].get_raw_string_value() + "]";
}
}
return debug_string;
}
const size_t get_line_number() const
{
return line_number;
}
const string get_file() const
{
return filename;
}
// Use only for branch instructions
size_t get_branch_target() const
{
return branch_target;
}
void set_branch_target(size_t pc)
{
branch_target = pc;
}
};
Command *last_command = nullptr;
void raise_nvm_error(string error_message)
{
cerr << endl
<< "====== Oh no! Runtime Error! ======" << endl;
cerr << wrap_text(error_message, 70) << endl;
if (last_command != nullptr)
{
cerr << endl
<< "--- Source File Information --- " << endl;
cerr << "- Source File: " << last_command->get_file() << endl;
cerr << "- Source Line: " << last_command->get_line_number() << endl;
}
cerr << endl
<< "--- NariVM State Information --- " << endl;
cerr << "- PC: " << pc + 1 << endl;
exit(1);
}
vector<unordered_map<string, Value> /**/> variable_tables;
map<string, size_t> label_to_pc;
map<size_t, string> pc_to_label;
stack<Value> execution_stack;
map<string, fstream *> open_files;
set<string> untruncated_files; // Garbage
set<string> read_only_files; // Garbage
stack<size_t> return_stack;
Value get_nil_value()
{
Value nil_value;
nil_value.set_nil_value();
return nil_value;
}
Value get_listlimit_value()
{
Value ll_value;
ll_value.set_listlimit_value();
return ll_value;
}
void print_command_listing(vector<Command> &code_listing)
{
// Prints a code listing to the console.
for (size_t i = 0; i < code_listing.size(); ++i)
{
if (pc_to_label.count(i) > 0)
{
cout << "[" << pc_to_label[i] << "] => ";
}
cout << "(" << i + 1 << ") " << code_listing[i].get_debug_string() << endl;
}
}
string trim(const string &str)
{
const auto strBegin = str.find_first_not_of(" \t");
if (strBegin == string::npos)
return "";
const auto strEnd = str.find_last_not_of(" \t");
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
char get_token_type(const string &text)
{
int begin = 0;
bool found_period = false;
if (text[0] == '"')
{
return TEXT; // Text type if the string starts with a quote
}
if (text[0] == '+' || text[0] == '-')
{
begin = 1; // Skip the sign if it's there
}
for (size_t i = begin; i < text.size(); ++i)
{
char ch = text[i];
if (ch != '.' && !isdigit(ch))
{
return NIL; // Not a number if it contains invalid characters
}
if (ch == '.')
{
if (found_period)
{
return NIL; // Invalid if more than one period is found
}
found_period = true;
}
}
return NUMB;
}
Command split_command_arguments(const string &line, const size_t full_line_number, const string &full_file_name)
{
vector<string> tokens;
string current_token;
bool in_string = false;
bool next_char_escaped = false;
bool uppercase_on_append = false;
for (char ch : line)
{
if (!in_string && isspace(ch))
{
if (!current_token.empty())
{
if (uppercase_on_append)
{
uppercase_on_append = false;
transform(current_token.begin(), current_token.end(), current_token.begin(), ::toupper);
}
tokens.push_back(current_token);
}
current_token.clear();
}
else if (in_string && next_char_escaped)
{
next_char_escaped = false;
if (ch == 'n')
{
current_token += '\n';
}
else if (ch == 't')
{
current_token += '\t';
}
else if (ch == 'r')
{
current_token += '\r';
}
else if (ch == 'b')
{
current_token += '\b';
}
else if (ch == 'f')
{
current_token += '\f';
}
else if (ch == 'v')
{
current_token += '\v';
}
else
{
current_token += ch;
}
}
else if (in_string && ch == '\\')
{
next_char_escaped = true;
}
else if (ch == '"')
{
in_string = !in_string;
current_token += ch;
}
else
{
if (current_token.empty() && ch == '@')
{
uppercase_on_append = true;
}
current_token += ch;
}
}
if (!current_token.empty())
{
if (uppercase_on_append)
{
uppercase_on_append = false;
transform(current_token.begin(), current_token.end(), current_token.begin(), ::toupper);
}
tokens.push_back(current_token);
}
if (in_string)
{
raise_nvm_error("Nambly parsing error: open string for line '" + line + "'");
}
Command new_command(tokens.empty() ? "" : tokens[0], full_line_number, full_file_name);
for (size_t i = 1; i < tokens.size(); ++i)
{
Value value;
value.set_string_value(tokens[i]);
char token_type = get_token_type(value.get_as_string());
if (token_type == TEXT)
{
value.set_string_value(tokens[i].substr(1, tokens[i].size() - 2)); // Remove surrounding quotes
}
else if (token_type == NUMB)
{
value.set_number_value(stod(tokens[i]));
}
new_command.add_argument(value);
}
return new_command;
}
vector<Command> generate_label_map_and_code_listing(const string &code)
{
// Checks a code listing for labels and fills the label map with their PCs.
// Then returns the code without those labels.
size_t pc = 0;
vector<Command> code_listing;
stringstream ss(code);
string line;
size_t full_source_line_number = 0;
string full_source_filename = "";
while (getline(ss, line, '\n'))
{
line = trim(line);
if (line.empty())
{
continue;
}
if (line[0] == '@')
{
int jmp_pc_value = pc;
string label_name = line.substr(1);
if (label_to_pc.find(label_name) == label_to_pc.end())
{
label_to_pc[label_name] = jmp_pc_value;
pc_to_label[pc] = label_name;
}
else
{
raise_nvm_error("Duplicate label: " + label_name);
}
continue;
}
string sub = line.substr(0, 5);
if (sub == ";line")
{
full_source_line_number = stol(trim(line.substr(5)));
continue;
}
if (sub == ";file")
{
full_source_filename = trim(line.substr(5));
continue;
}
if (line[0] != ';')
{
code_listing.push_back(split_command_arguments(line, full_source_line_number, full_source_filename));
++pc;
}
}
for (auto &command : code_listing)
{
switch (command.get_opcode())
{
case Opcode::JUMP:
case Opcode::JPIF:
case Opcode::CALL:
pc = label_to_pc[command.get_arguments()[0].get_raw_string_value()] - 1;
command.set_branch_target(pc);
default:
break;
}
}
return code_listing;
}
void push(Value v)
{
execution_stack.push(std::move(v));
}
Value pop(Command &command)
{
if (execution_stack.empty())
{
raise_nvm_error("Execution stack empty for command: " + command.get_debug_string());
}
auto v = std::move(execution_stack.top());
execution_stack.pop();
return v;
}
void add_scope()
{
variable_tables.push_back(unordered_map<string, Value>());
}
void set_variable(const string &var_name, Value value)
{
if (variable_tables.empty())
{
add_scope();
}
variable_tables[variable_tables.size() - 1][var_name] = std::move(value);
}
void delete_variable(const string &name)
{
if (variable_tables.empty())
{
return; // If there are no scopes, nothing to delete
}
// Try to delete from the current (last) scope
auto ¤t_scope = variable_tables.back(); // Access the last scope
if (current_scope.find(name) != current_scope.end())
{
current_scope.erase(name); // Delete the variable from the current scope
return;
}
// Try to delete from the global (first) scope
auto &global_scope = variable_tables.front(); // Access the first scope
if (global_scope.find(name) != global_scope.end())
{
global_scope.erase(name); // Delete the variable from the global scope
return;
}
}
void set_global_variable(const string &var_name, Value value)
{
if (variable_tables.empty())
{
add_scope();
}
variable_tables[0][var_name] = value;
}
const Value &get_variable(const string &var_name)
{
if (!variable_tables.empty())
{
// TODO esta busqueda es ineficiente para variables en el scope global porque busca dos veces
auto location = variable_tables[variable_tables.size() - 1].find(var_name);
if (location != variable_tables[variable_tables.size() - 1].end())
{
return location->second;
}
location = variable_tables[0].find(var_name);
if (location != variable_tables[0].end())
{
return location->second;
}
}
static Value nil_value;
nil_value.set_nil_value(); // Refresh the nil just in case
return nil_value;
}
string substring(const string &s, long long from, long long count)
{
long long len = s.size();
// Handle negative indices
if (from < 0)
{
from += len; // Negative index counts from the end
}
// Ensure `from` is within bounds
if (from < 0)
{
from = 0;