-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractMachine.h
More file actions
1360 lines (1149 loc) · 42.5 KB
/
AbstractMachine.h
File metadata and controls
1360 lines (1149 loc) · 42.5 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
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
// AbstractMachine.h : This file defines the AbstractMachine class, which represents a Turing-complete computational model. The AbstractMachine has a tape (modeled by the Substrate resource) and a state register (modeled by the States resource). It can interpret and execute programs written in its language, which is defined by the Language class. The AbstractMachine can be extended with additional resources and commands as needed.
// Copyright © 2026 Guillermo M. Dávila Andino
#pragma once
#include "Language.h"
class Resource {
public:
virtual ~Resource() = default;
std::shared_ptr<Language<char8_t>> language;
Medium<char8_t> name{};
//Language<char8_t> language;
//std::any resource;
};
class States : public Resource {
public:
// command names
std::set<Medium<char8_t>> ld = { u8"load", u8"ld" };
std::set<Medium<char8_t>> ud = { u8"unload", u8"ud" };
std::set<Medium<char8_t>> se = { u8"state", u8"se" };
std::set<Medium<char8_t>> at = { u8"accept", u8"at" };
std::set<Medium<char8_t>> ss = { u8"states", u8"ss" };
// identifiers or parameters
std::set<Medium<char8_t>> ne = { u8"name", u8"ne" };
std::set<Medium<char8_t>> ag = { u8"accepting", u8"ag" };
std::set<Medium<char8_t>> st = { u8"start", u8"st" };
std::set<Medium<char8_t>> tp = { u8"temp", u8"tp" };
//std::set<Medium<char8_t>> in = { u8"instruction", u8"in" };
States(std::shared_ptr<Language<char8_t>> lang) {
name = u8"States";
language = lang;
//language->AddCharacterInterpretations();
language->InterpretMediumFunction(u8"load", ld, [this](const Medium<char8_t>& p) { return this->Load(p); }, name);
language->Interpret(
std::set<Program<char8_t>>{},
u8"unload",
ud,
[this](const Token<char8_t>& prog) { return this->UnloadSyntax(prog); },
[this](const Token<char8_t>& prog) { return this->Unload(std::get<Medium<char8_t>>(prog)); },
name
);
language->InterpretMediumFunction(u8"accepting", ag, [this](const Medium<char8_t>& p) { return this->AcceptingSemantic(p); }, name);
language->InterpretNullaryFunction(u8"state", se, [this]() { return this->State(); }, name);
language->InterpretNullaryVoidFunction(u8"states", ss, [this]() { return this->PrintStates();}, name);
}
enum StateKind : int {
ER = -1, // Error state
NL = 0, // Normal state
AG = 1, // Accepting state
TP = 2 // Temporary state (not accepting by default)
};
std::unordered_map<unsigned long long, Token<char8_t>> states; // Maps state numbers to their corresponding tokens (programs).
std::hash<Token<char8_t>> hasher; // Maps tokens (programs) to their corresponding state numbers for quick lookup.
// state 0 is the starting state by default
unsigned long long state = 0; // current state register
unsigned long long icount = 0; // instruction counter within program
std::vector<unsigned long long> instnum{}; //Instruction number stack
std::vector<unsigned long long> previous{}; //Previous state stack for backtracking
std::set<unsigned long long> accepting{};
std::vector<unsigned long long> temp_states{}; // Temporary states that are not accepting by default, but can be marked as accepting later if needed
//std::vector < Medium<char8_t>> LineStack{};
std::vector<unsigned long long> callstack{}; // Call stack for subroutine calls, if needed in future extensions
unsigned long long State() const { return state; }
unsigned long long Instruction() const { return icount; }
unsigned long long PreviousInstruction() const { return instnum.back(); }
unsigned long long PreviousState() const { return previous.back(); }
// return true if in accepting state
bool Accepting() const { return Accepting(state); }
bool Accepting(unsigned long long st) const {
if (accepting.contains(st)) {
std::cout << "Accepting State.\n";
return true;
}
else {
std::cout << "Not Accepting State.\n";
return false;
}
}
void PrintStates() const {
std::cout << "Current States:\n";
Medium<char8_t> program;
for (const auto& [num, prog] : states) {
program = std::get<Medium<char8_t>>(prog);
std::cout << num << ": " << program;
if (accepting.contains(num)) {
std::cout << " (Accepting)";
}
if (TempState(num) != temp_states.end()) {
std::cout << " (Temporary)";
}
std::cout << "\n";
}
}
// return true if in temporary state
std::vector<unsigned long long>::const_iterator TempState(unsigned long long st) const {
auto it = std::find(temp_states.begin(), temp_states.end(), st);
//return temp_states.contains(st);
return it;
}
// Load returns a pair of the state kind and the new state number.
std::pair<StateKind, unsigned long long> Load(const Token<char8_t>& program) {
Medium<char8_t> prog = std::get<Medium<char8_t>>(program);
StateKind kind = StateKind::NL;
Medium<char8_t> name;
unsigned long long new_state;
language->Munch(prog); // Remove "load"
if (at.contains(std::get<Medium<char8_t>>(ToLower(language->Lick(prog))))) {
kind = StateKind::AG;
language->Munch(prog); // Remove "accept"
}
else if (tp.contains(std::get<Medium<char8_t>>(ToLower(language->Lick(prog))))) {
kind = StateKind::TP; // Temporary states are not accepting by default
// lol.. TP.... like toilet paper
language->Munch(prog); // Remove "temp"
}
if (!prog.empty()) {
if (ne.contains(std::get<Medium<char8_t>>(ToLower(language->Lick(prog))))) {
language->Munch(prog); // Remove "name"
if (!prog.empty()) {
name = language->Munch(prog);
if (!name.empty() && str_predicate(isalpha, name)) {
new_state = hasher(name);
}
else {
return std::make_pair(StateKind::ER, 0ULL); // ← add this
}
}
}
else if (st.contains(std::get<Medium<char8_t>>(ToLower(language->Lick(prog))))) {
new_state = 0;
//language->Munch(prog); // Remove "start"
if (!prog.empty()) {
states[new_state] = prog; // Store the remaining program as the state representation
}
else {
states[new_state] = Medium<char8_t>{}; // Empty state representation
}
if (kind == StateKind::AG) {
Accept(new_state);
}
else if (kind == StateKind::TP) {
Temp(new_state);
}
return std::make_pair(kind, new_state);
}
else {
new_state = hasher(prog);
}
}
else {
return std::make_pair(StateKind::ER, 0); // Invalid name
}
states[new_state] = prog;
if (kind == StateKind::AG) {
Accept(new_state);
}
else if (kind == StateKind::TP) {
Temp(new_state);
}
return std::make_pair(kind, new_state);
}
unsigned long long UnloadSyntax(const Token<char8_t>& program) {
Medium<char8_t> prog = std::get<Medium<char8_t>>(program);
if (ud.contains(language->Munch(prog)) && !prog.empty()) {
Medium<char8_t> arg = language->Munch(prog); // Get the next token which should be the state identifier
if (!prog.empty()) {
if (str_predicate(isalpha, prog) || str_predicate(isdigit, prog)) {
return std::get<Medium<char8_t>>(program).size() - prog.size();
}
}
else return std::get<Medium<char8_t>>(program).size();
}
return 0; // Invalid state identifier
}
unsigned long long Unload(Medium<char8_t> program) {
Medium<char8_t> prog = program;
language->Munch(prog); // Remove the command (e.g., "unload") to get the state identifier
unsigned long long s;
if (prog.empty()) {
s = state;
}
else {
prog = language->Munch(prog); // Get the next token which should be the state identifier
if (!prog.empty()) {
if (str_predicate(isalpha, prog)) {
s = hasher(prog);
}
else if (str_predicate(isdigit, prog)) {
//s = std::stoull(std::string(prog.begin(), prog.end()));
std::string str(reinterpret_cast<const char*>(prog.data()), prog.size());
s = std::stoull(str);
}
else return 0; // Invalid state identifier
}
else return 0; // Invalid state identifier
}
if (states.contains(s)) {
states.erase(s);
if (accepting.contains(s))
accepting.erase(s);
if (state == s) {
state = previous.empty() ? 0 : previous.back();
if (!previous.empty()) {
previous.pop_back();
}
}
return state;
}
return 0; // Invalid state
}
std::any AcceptingSemantic(Medium<char8_t> program) {
Medium<char8_t> prog = program;
language->Munch(prog); // Remove the command (e.g., "accepting") to get the state identifier
if (!prog.empty()) {
prog = language->Munch(prog); // Get the next token which should be the state identifier
if (!prog.empty()) {
if (str_predicate(isalpha, prog)) {
unsigned long long s = hasher(prog);
return Accepting(s);
}
else if (str_predicate(isdigit, prog)) {
//unsigned long s = std::stoull(std::string(prog.begin(), prog.end()));
std::string str(reinterpret_cast<const char*>(prog.data()), prog.size());
unsigned long long s = std::stoull(str);
return Accepting(s);
}
}
}
return Accepting();
}
// Mark a state as accepting
bool Accept(unsigned long long st) {
if (states.contains(st)) {
accepting.insert(st);
return true;
}
else { return false; }
}
// This function register temporary states
bool Temp(unsigned long long st) {
if (states.contains(st)) {
//temp_states.insert(st);
temp_states.push_back(st);
return true;
}
else { return false; }
}
};
// The Value V of the substrate is the type of the symbols on the tape. It can be any type that satisfies the Value concept, which includes primitive types (like char, int, bool) and user-defined types that can be constructed from a string representation.
// The programs that are read are written in ProgramFile<char8_t>. The same as the AbstractMachine's language. The Substrate is a resource of the AbstractMachine, and it provides the basic operations that the machine can perform on its tape.
template <Value V>
class Substrate : public Resource {
public:
std::set<Medium<char8_t>> readcomms = { u8"read", u8"rd" };
std::set<Medium<char8_t>> headcomms = { u8"head", u8"hd" };
std::set<Medium<char8_t>> leftcomms = { u8"left", u8"lt" };
std::set<Medium<char8_t>> rightcomms = { u8"right", u8"rt" };
std::set<Medium<char8_t>> writecomms = { u8"write", u8"we" };
std::set<Medium<char8_t>> gotocomms = { u8"goto", u8"go" };
std::set<Medium<char8_t>> shrinkcomms = { u8"shrink", u8"sk" };
std::set<Medium<char8_t>> movecomms = { u8"move", u8"me" };
std::set<Medium<char8_t>> clearcomms = { u8"clear", u8"cr" };
Medium<V> Tape;
long long head;
unsigned char order;
Substrate(std::shared_ptr<Language<char8_t>> lang) {
language = lang;
name = u8"Tape";
order = 16;
head = 0;
Tape = MakeTape(order);
language->InterpretNullaryFunction(u8"read", readcomms, [this]() { return Read(); }, name);
language->InterpretNullaryFunction(u8"head", headcomms, [this]() { return Head(); }, name);
language->InterpretNullaryFunction(u8"left", leftcomms, [this]() { return Left(); }, name);
language->InterpretNullaryFunction(u8"right", rightcomms, [this]() { return Right(); }, name);
language->InterpretNullaryVoidFunction(u8"shrink", shrinkcomms, [this]() { Shrink(); }, name);
language->InterpretNullaryVoidFunction(u8"clear", clearcomms, [this]() { Clear(); }, name);
language->Interpret(
std::set<char8_t>{},
u8"write",
writecomms,
[this](const Token<char8_t>& prog) { return this->WriteSyntax(prog); },
[this](const Token<char8_t>& prog) { return this->WriteSemantic(prog); },
name
);
language->InterpretIntegerArgumentLongLongFunction(u8"goto", gotocomms, [this](const long long& prog) { return this->GoTo(prog); }, name);
language->InterpretIntegerArgumentLongLongFunction(u8"move", movecomms, [this](const long long& prog) { return this->Move(prog); }, name);
}
long long Head() const { return head; }
std::any WriteSemantic(const Token<char8_t>& prog) {
Medium<char8_t> program = std::get<Medium<char8_t>>(prog);
language->Munch(program); // Remove "write" command
Medium<char8_t> valStr = language->Munch(program); // Get the data to write
// Case 0: Tape stores bool values
if constexpr (std::is_same_v<V, bool>) {
valStr = std::get<Medium<char8_t>>(ToLower(valStr)); // Canonicalize input for boolean parsing
if (valStr == u8"true" || valStr == u8"1") {
return Write(true);
}
else if (valStr == u8"false" || valStr == u8"0") {
return Write(false);
}
else {
std::cout << "Invalid boolean value.\n";
return std::any{};
}
}
// Case 1: The Tape stores full Strings
else if constexpr (String<V>) {
// Program<V> is V, which is a string type.
// We can pass valStr (Medium<char8_t>) directly or cast it.
return Write(V(valStr));
}
// Case 2: The Tape stores single Characters
else if constexpr (Char<V>) {
if (valStr.size() == 1) {
return Write(static_cast<V>(valStr[0]));
}
// Fallback for numeric codes (e.g., "65" -> 'A')
try {
std::string s(reinterpret_cast<const char*>(valStr.data()), valStr.size());
return Write(static_cast<V>(std::stoi(s)));
}
catch (...) { return std::any{}; }
}
// Case 3: The Tape stores Numbers (int, long long, etc.)
else if constexpr (Arithmetic<V>) {
// Convert u8string to a char range for from_chars
const char* first = reinterpret_cast<const char*>(valStr.data());
const char* last = first + valStr.size();
V numericVal = 0;
auto [ptr, ec] = std::from_chars(first, last, numericVal);
if (ec == std::errc{}) {
return Write(numericVal);
}
else {
if (ec == std::errc::invalid_argument)
std::cout << "This is not a number.\n";
else if (ec == std::errc::result_out_of_range)
std::cout << "This number is larger than an int.\n";
// Handle error: result was out of range or not a number
return std::any{ ptr, ec }; // Return parsing result for debugging
}
}
return std::any{};
}
unsigned long long WriteSyntax(const Token<char8_t>& prog) {
if (!std::holds_alternative<Medium<char8_t>>(prog)) return 0;
const Medium<char8_t>& medium = std::get<Medium<char8_t>>(prog);
auto [commandToken, cmdConsumed] = language->Lunch(medium);
// command must be a write command and there must be data after it
if (!writecomms.contains(std::get<Medium<char8_t>>(ToLower(commandToken))) ) {
//if (medium.size() <= cmdConsumed) //throw std::invalid_argument("No value provided to write\n");
return 0;
}
// remaining buffer after the command
Medium<char8_t> remaining(medium.begin() + static_cast<std::ptrdiff_t>(cmdConsumed), medium.end());
auto [valueToken, valConsumed] = language->Lunch(remaining);
if (valueToken.empty()) throw std::invalid_argument("No value provided to write\n");
bool convertible = false;
// --- Check convertibility to V without performing the write ---
if constexpr (std::is_same_v<V, bool>) {
// Use ToLower to canonicalize boolean strings
Token<char8_t> vt = valueToken;
auto lowered = ToLower(vt);
auto& lowerMedium = std::get<Medium<char8_t>>(lowered);
std::u8string lower_s(lowerMedium.begin(), lowerMedium.end());
if (lower_s == u8"true" || lower_s == u8"1" || lower_s == u8"false" || lower_s == u8"0")
convertible = true;
}
else if constexpr (String<V>) {
// any token can be treated as a string-like V
convertible = true;
}
else if constexpr (Char<V>) {
// single character token OK
if (valueToken.size() == 1) convertible = true;
else {
// numeric-code fallback, parse as signed integer then range-check for V
std::string s;
s.reserve(valueToken.size());
for (char8_t c : valueToken) s.push_back(static_cast<char>(c));
long long tmp = 0;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), tmp);
if (ec == std::errc{}) {
using Target = std::remove_cv_t<V>;
if constexpr (std::is_signed_v<Target>) {
long long tmin = static_cast<long long>(std::numeric_limits<Target>::min());
long long tmax = static_cast<long long>(std::numeric_limits<Target>::max());
if (tmp >= tmin && tmp <= tmax) convertible = true;
}
else {
if (tmp >= 0) {
unsigned long long utmp = static_cast<unsigned long long>(tmp);
unsigned long long umax = static_cast<unsigned long long>(std::numeric_limits<Target>::max());
if (utmp <= umax) convertible = true;
}
}
}
}
}
else if constexpr (Arithmetic<V>) {
// try parsing into numeric V
std::string s;
s.reserve(valueToken.size());
for (char8_t c : valueToken) s.push_back(static_cast<char>(c));
V numericVal = 0;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), numericVal);
if (ec == std::errc{}) convertible = true;
}
else if constexpr (Defined<V>) {
// try constructing V from the token
try {
std::u8string s(valueToken.begin(), valueToken.end());
(void)V(s);
convertible = true;
}
catch (...) {
convertible = false;
}
}
// return total consumed length (command + value) when convertible, else 0
return convertible ? (cmdConsumed + valConsumed) : 0;
}
//friend class AbstractMachine;
Medium<V> MakeTape(const unsigned char& k) {
//if (k >= (sizeof(unsigned) * 8)) throw std::overflow_error("Tape order too large");
if (k >= 64) throw std::overflow_error("Tape order too large");
std::size_t size = std::size_t(1) << k;
if constexpr (requires { typename V::inner_type; }) {
using Inner = typename V::inner_type;
if constexpr (std::is_arithmetic_v<Inner>) {
if constexpr (std::is_same_v<Medium<V>, std::valarray<Inner>>) {
return Medium<V>(Inner{}, size); // valarray(value, n) accepted
}
else {
return Medium<V>(size, Inner{}); // vector(size, init)
}
}
else {
return Medium<V>(size, Inner{});
}
}
else if constexpr (Text<V>) {
return Medium<V>(size, V{});
}
else if constexpr (Arithmetic<V>) {
return Medium<V>(V{}, size);
}
else {
return Medium<V>(size);
}
}
void Clear() {
head = 0;
std::fill(std::begin(Tape), std::end(Tape), V{});
}
V Read() {
std::int64_t zero = static_cast<std::int64_t>(Tape.size()) / 2;
std::int64_t idx = head + zero;
if (idx < 0 || static_cast<std::size_t>(idx) >= Tape.size()) {
MoreTape();
zero = static_cast<std::int64_t>(Tape.size()) / 2;
idx = head + zero;
}
if constexpr (requires { typename V::inner_type; }) {
return V(Tape[static_cast<std::size_t>(idx)]);
}
else {
return Tape[static_cast<std::size_t>(idx)];
}
}
bool Write(const Program<V>& a) {
std::int64_t zero = static_cast<std::int64_t>(Tape.size()) / 2;
std::int64_t idx = head + zero;
if (idx < 0 || static_cast<std::size_t>(idx) >= Tape.size()) {
MoreTape();
zero = static_cast<std::int64_t>(Tape.size()) / 2;
idx = head + zero;
}
if constexpr (requires { typename V::inner_type; }) {
Tape[static_cast<std::size_t>(idx)] = a.value;
return true;
}
else {
Tape[static_cast<std::size_t>(idx)] = a;
return true;
}
//return false;
}
bool Left() {
if (--head < -(1LL << (order - 1))) {
if (MoreTape() == false)
return false;
}
if (head <= std::numeric_limits<long long>::max() && head >= std::numeric_limits<long long>::min())
return true;
else
return false;
}
bool Right() {
long long zero = 1LL << (order - 1);
if (++head >= zero) {
if (MoreTape() == false)
return false;
}
if (head <= std::numeric_limits<long long>::max() && head >= std::numeric_limits<long long>::min())
return true;
else
return false;
}
bool Move(const long long& c) {
long long zero = 1LL << (order - 1);
while ((zero + c + head) >= static_cast<long long>(Tape.size())) {
if (MoreTape() == false)
return false;
}
head += c;
if (head <= std::numeric_limits<long long>::max() && head >= std::numeric_limits<long long>::min())
return true;
else
return false;
}
bool GoTo(const long long& s) {
long long zero = 1LL << (order - 1);
while (zero + s >= static_cast<long long>(Tape.size())) {
if (MoreTape() == false)
return false;
}
head = s;
if (head <= std::numeric_limits<long long>::max() && head >= std::numeric_limits<long long>::min())
return true;
else
return false;
}
void NewTape(unsigned char n) {
Tape = MakeTape(n);
//zero = Tape.size() / 2;
order = n;
}
bool MoreTape() {
//if (order + 1 >= (sizeof(unsigned char) * 8)) { // max order = 255 for unsigned char
if (order + 1 >= 64) { // max order = 63 for unsigned long long, which is the largest we can use for indexing the tape
std::cerr << "Max tape order reached\n";
return false;
}
std::size_t oldSize = Tape.size();
std::size_t newSize = oldSize * 2;
Medium<V> VTape = MakeTape(order + 1); // makes newSize
std::size_t oldZero = oldSize / 2;
std::size_t newZero = newSize / 2;
for (std::size_t i = 0; i < oldSize; ++i) {
VTape[i + newZero - oldZero] = Tape[i];
}
Tape = std::move(VTape);
++order;
return true;
}
void Shrink() {
long long zero = 1LL << (order - 1);
long long minIndex = static_cast<long long>(Tape.size()) - 1;
long long maxIndex = -1;
// Find the bounds of non-default values
for (long long i = 0, n = static_cast<long long>(Tape.size()); i < n; ++i) {
V val;
if constexpr (requires { typename V::inner_type; }) {
val = V(Tape[i]);
}
else {
val = Tape[i];
}
if (!(val == V{})) {
minIndex = std::min(minIndex, i);
maxIndex = std::max(maxIndex, i);
}
}
// If no non-default values found, reset to minimal tape
if (maxIndex < minIndex) {
NewTape(1);
head = 0;
return;
}
long long newSize = maxIndex - minIndex + 1;
unsigned char newOrder = static_cast<unsigned>(std::ceil(std::log2(static_cast<double>(newSize))));
Medium<V> newTape = MakeTape(newOrder);
long long newZero = 1LL << (newOrder - 1);
for (long long i = minIndex; i <= maxIndex; ++i) {
newTape[i - minIndex + newZero] = Tape[i];
}
head = head - minIndex;
Tape = std::move(newTape);
order = newOrder;
}
};
// Here, we define Abstract Machine to use a language over char8_t
// but we could easily refactor to any Value V.
//template <Value V>
class AbstractMachine {
public:
// friend class States;
//Language<char8_t> language;
std::shared_ptr<Language<char8_t>> language;
std::vector<std::unique_ptr<Resource>> Resources;
//std::vector<Token<char8_t>> ResourceRegistry;
Substrate<bool>* Tape;
States* StateRegister;
std::set<Medium<char8_t>> RunComms = { u8"run", u8"rn" };
std::set<Medium<char8_t>> TapeComms = { u8"tape", u8"te" };
std::set<Medium<char8_t>> StateComms = { u8"state", u8"se" };
//std::set<Medium<char8_t>> sm = { u8"system", u8"sm" };
std::set<Medium<char8_t>> ng = { u8"nothing", u8"ng" };
std::set<Medium<char8_t>> st = { u8"start", u8"st" };
std::set<Medium<char8_t>> cl = { u8"call", u8"cl" };
std::set<Medium<char8_t>> ed = { u8"end", u8"ed" };
std::set<Medium<char8_t>> rt = { u8"reset", u8"re" };
std::set<Medium<char8_t>> bh = { u8"branch", u8"bh" };
Medium<char8_t> name = u8"Abstract Machine";
typedef bool TapeSymbol;
void Initialize() {
language = std::make_shared<Language<char8_t>>();
language->AddCharacterInterpretations();
language->AddTypeInterpretations();
language->InterpretMediumFunction(u8"run", RunComms, [this](const Medium<char8_t>& prog) { return this->Run(prog); }, name);
/*language->InterpretMediumFunction(u8"system", sm, [this](const Medium<char8_t>& p) {
std::string command(p.begin(), p.end());
this->System(command);
return std::any{};},
name
);*/
language->InterpretNullaryVoidFunction(u8"nothing", ng, [this]() { this->Nothing(); }, name);
language->Interpret(
std::set<Program<char8_t>>{},
u8"start",
st,
[this](const Token<char8_t>& prog) { return this->StartSyntax(prog); },
[this](const Token<char8_t>& prog) { return this->StartSemantic(std::get<Medium<char8_t>>(prog)); },
name
);
language->InterpretNullaryVoidFunction(u8"end", ed, [this]() { this->End(); }, name);
language->Interpret(
std::set<Program<char8_t>>{},
u8"call",
cl,
[this](const Token<char8_t>& prog) { return this->CallSyntax(prog); },
[this](const Token<char8_t>& prog) { return this->CallSemantic(std::get<Medium<char8_t>>(prog)); },
name
);
language->InterpretNullaryVoidFunction(u8"reset", rt, [this]() { this->Reset(); }, name);
language->Interpret(
std::set<Program<char8_t>>{},
u8"branch",
bh,
[this](const Token<char8_t>& prog) { return this->BranchSyntax<TapeSymbol>(prog); },
[this](const Token<char8_t>& prog) { return this->BranchSemantic<TapeSymbol>(prog); },
name
);
AddResource(std::make_unique<Substrate<bool>>(language));
AddResource(std::make_unique<States>(language));
Tape = static_cast<Substrate<TapeSymbol>*>(Resources[0].get());
StateRegister = static_cast<States*>(Resources[1].get());
}
AbstractMachine() {
Initialize();
Start();
}
AbstractMachine(const unsigned long& tape_order) {
Initialize();
Start(tape_order);
}
AbstractMachine(const Token<char8_t>& program) : AbstractMachine() {
LoadAndRun(program);
}
AbstractMachine(const ProgramFile<char8_t>& file) : AbstractMachine() {
LoadAndRun(file);
}
AbstractMachine(const unsigned long& tape_order, const Token<char8_t>& program) : AbstractMachine(tape_order) {
LoadAndRun(program);
}
AbstractMachine(const unsigned long& tape_order, const ProgramFile<char8_t>& file) : AbstractMachine(tape_order) {
LoadAndRun(file);
}
virtual ~AbstractMachine() = default;
/*void System(std::string command) {
system(command.c_str());
}*/
bool is_resource(const Medium<char8_t>& prog) const {
if (language->is_registered(prog, u8"Resource")) {
auto [Concept_Ptr, consumed, cntxt] = language->is_well_formed(prog, u8"Resource");
if (std::get<Medium<char8_t>>(std::get<0>(*Concept_Ptr)) == prog) {
return true;
}
}
return false;
}
ProgramFile<char8_t> ChopLine2(Medium<char8_t> prog) const {
ProgramFile<char8_t> pf;
Medium<char8_t> line;
Medium<char8_t> inst;
Medium<char8_t> program = prog;
bool registered = false;
while (!program.empty()){
inst = language->Munch(program);
if (std::get<Medium<char8_t>>(ToLower(inst)) == u8"load" || std::get<Medium<char8_t>>(ToLower(inst)) == u8"ld") {
pf.push_back(prog);
break;
}
if (!language->is_registered_any(inst).empty()) {
line = inst;
while (!program.empty()) {
inst = language->Munch(program);
registered = !language->is_registered_any(inst).empty();
if (!registered && !inst.empty()) {
line = line + u8" " + inst;
}
else {
registered = false;
pf.push_back(line);
line.clear();
if (!inst.empty())
line = inst;
}
}
if (!line.empty()) {
pf.push_back(line);
}
}
else {
pf.push_back(inst);
}
}
return pf;
}
void ProcessLine(const Medium<char8_t>& prog) {
ProgramFile<char8_t> pf = ChopLine2(prog);
for (auto it = pf.rbegin(); it != pf.rend(); it++) {
//ProcessLine(*it);
unsigned long long tempstate = StateRegister->Load(u8"load temp " + (*it)).second;
Call(tempstate);
}
}
void PrintEvaluationResult(const std::any& result) {
if (!result.has_value()) {
std::cout << "Result: (empty/void)" << std::endl;
return;
}
// Attempt to cast to known types defined in Language.h
if (result.type() == typeid(Token<char8_t>)) {
std::cout << "Token: " << std::any_cast<Token<char8_t>>(result) << std::endl;
}
else if (result.type() == typeid(std::u8string)) {
std::cout << "String: " << std::any_cast<std::u8string>(result) << std::endl;
}
else if (result.type() == typeid(int)) {
std::cout << "Int: " << std::any_cast<int>(result) << std::endl;
}
else if (result.type() == typeid(long long)) {
std::cout << "LL: " << std::any_cast<long long>(result) << std::endl;
}
else if (result.type() == typeid(unsigned long long)) {
std::cout << "ULL: " << std::any_cast<unsigned long long>(result) << std::endl;
}
else if (result.type() == typeid(bool)) {
std::cout << "Bool: " << (std::any_cast<bool>(result) ? "true" : "false") << std::endl;
}
else if (result.type() == typeid(double)) {
std::cout << "Double: " << std::any_cast<double>(result) << std::endl;
}
else if (result.type() == typeid(std::pair<States::StateKind, unsigned long long>)) {
auto [kind, state] = std::any_cast<std::pair<States::StateKind, unsigned long long>>(result);
std::cout << "State " << std::to_string(state) << " ";
switch (kind) {
case States::StateKind::NL: std::cout << "(Normal)"; break;
case States::StateKind::ER: std::cout << "(Error)"; break;
case States::StateKind::AG: std::cout << "(Accepting)"; break;
case States::StateKind::TP: std::cout << "(Temporary)"; break;
}
}
else {
std::cout << "Result holds type: " << result.type().name()
<< " (Printer for this type not implemented)." << std::endl;
}
}
std::vector<std::tuple<Token<char8_t>, std::any, unsigned long long>> Run(const Medium<char8_t>& program) {
std::vector<std::tuple<Token<char8_t>, std::any, unsigned long long>> results;
ProcessLine(program);
while (!StateRegister->callstack.empty()) {
auto [Concept_Ref, result, consumed] = RunStep();
if (consumed > 0) {
auto tok = std::get<0>(Concept_Ref);
std::cout << "Matched: " << tok << " => ";
PrintEvaluationResult(result); // already handles empty std::any gracefully
results.push_back(std::make_tuple(tok, result, consumed));
}
else {
std::cout << "Error: No matching language rule found for part of the input.\n";
}
}
return results;
}
std::tuple<Token<char8_t>, std::any, unsigned long long> RunStep() {
std::tuple<Token<char8_t>, std::any, unsigned long long> result;
Medium<char8_t> program{};
// 1. PEEK at the current executing state (Do not revert the state yet)
unsigned long long currentState = StateRegister->callstack.back();
const Medium<char8_t> line = std::get<Medium<char8_t>>(StateRegister->states[currentState]);
// 2. POP the stacks to consume the instruction, but store the rollback data
StateRegister->callstack.pop_back();
StateRegister->previous.pop_back();
StateRegister->instnum.pop_back();
unsigned long long callerState = StateRegister->previous.back();
unsigned long long callerIcount = StateRegister->instnum.back();
// Notice: We DO NOT assign StateRegister->state = callerState here.
// StateRegister->state remains 'currentState' so the instruction knows its own context.
auto contexts = language->is_well_formed_context(line);
unsigned i = 0;
if (contexts.empty()) {
std::cerr << "No interpretation found for: "
<< reinterpret_cast<const char*>(line.c_str()) << "\n";
return {};
}
else if (contexts.size() > 1) {
for (auto it = contexts.begin(); it != contexts.end(); it++) {
if ((*it) == u8"Literal") {
it = contexts.erase(it);
break;
}
}
if (contexts.size() > 1) {
std::cout << "Choose a non-trivial Context for interpretation.\n";
for (const auto& ctx : contexts) {
std::cout << i++ << ": " << ctx << "\n";
}
std::cout << "# ";
std::cin >> i;
while (i >= contexts.size()) {
std::cerr << "Invalid selection.\n";
std::cout << "# ";
std::cin >> i;
}
}
}
auto [Concept_Ptr, consumed, context] = language->has_interpretation(line, contexts[i]);
if (consumed > 0 && consumed < line.size()) {
program = Medium<char8_t>(line.begin() + consumed, line.end());
ProcessLine(program);
}
// 3. EVALUATE the instruction using the CORRECT current state
if (consumed > 0 && Concept_Ptr != nullptr) {
program = Medium<char8_t>(line.begin(), line.begin() + consumed);
result = std::make_tuple(std::get<0>(*Concept_Ptr), language->Evaluate(*Concept_Ptr, program), consumed);
}