-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgate_computer_toolset.cpp
More file actions
1908 lines (1638 loc) · 72.6 KB
/
gate_computer_toolset.cpp
File metadata and controls
1908 lines (1638 loc) · 72.6 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
/*
why is output format a string. make it a enum const
Gate Computer Toolset
Interactive CLI tool for assembling code and generating ROMs
Compilation:
g++ -std=c++17 -Wall -o gct gate_computer_toolset.cpp
Usage:
./gct
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <limits>
#include <algorithm>
#include <functional>
#include <cctype>
#include "utils/RomWriter.hpp"
#include "utils/IsaSpec.hpp"
// Tool Registry - holds all registered tools
class ToolRegistry {
private:
static std::vector<class Tool*>& getTools() {
static std::vector<Tool*> tools;
return tools;
}
public:
static void registerTool(Tool* tool) {
getTools().push_back(tool);
}
static const std::vector<Tool*>& getAllTools() {
return getTools();
}
};
// Base class for all tools
class Tool {
public:
std::string name; // Display name shown in menu
std::string description; // Description of what it does
Tool(const std::string& n, const std::string& desc)
: name(n), description(desc) {}
virtual ~Tool() = default;
// Execute the tool - must be implemented by each tool
virtual void execute(RomFormat outputFormat) = 0;
// Get user inputs (override if tool needs specific inputs)
virtual void getInputs() {}
};
// Simple base class for tools
template<typename T>
class AutoRegisterTool : public Tool {
public:
AutoRegisterTool(const std::string& n, const std::string& desc)
: Tool(n, desc) {}
};
// ============================================
// DIGITAL LOGIC SIM HELPER
// ============================================
class DigitalLogicSimHelper {
private:
std::string chipName;
std::string basePath;
public:
DigitalLogicSimHelper(const std::string& chip = "16-CPU")
: chipName(chip),
basePath("C:\\Users\\Limey\\AppData\\LocalLow\\SebastianLague\\Digital-Logic-Sim\\Projects\\16-Bit Computer 1.3\\Chips\\") {}
// Update a single subchip's InternalData array
bool updateSubchipData(const std::string& subchipLabel, const std::vector<uint16_t>& data) {
std::string jsonPath = basePath + chipName + ".json";
// Read entire file
std::ifstream jsonFile(jsonPath);
if (!jsonFile.is_open()) {
std::cerr << "Warning: Could not open Digital Logic Sim file: " << jsonPath << "\n";
return false;
}
std::string fileContent((std::istreambuf_iterator<char>(jsonFile)), std::istreambuf_iterator<char>());
jsonFile.close();
// Find the subchip by label
std::string searchStr = "\"Label\":\"" + subchipLabel + "\"";
size_t labelPos = fileContent.find(searchStr);
if (labelPos == std::string::npos) {
std::cerr << "Warning: Could not find subchip with label '" << subchipLabel << "'\n";
return false;
}
// Find InternalData array start after this label
size_t dataStart = fileContent.find("\"InternalData\":[", labelPos);
if (dataStart == std::string::npos) {
std::cerr << "Warning: Could not find InternalData for '" << subchipLabel << "'\n";
return false;
}
size_t arrayStart = dataStart + 16; // Skip "InternalData":[
size_t arrayEnd = fileContent.find("]", arrayStart);
// Build new array string
std::string newArray;
for (size_t i = 0; i < data.size(); i++) {
if (i > 0) newArray += ",";
newArray += std::to_string(data[i]);
}
// Replace old array with new
fileContent.replace(arrayStart, arrayEnd - arrayStart, newArray);
// Write back to file
std::ofstream outFile(jsonPath);
if (!outFile.is_open()) {
std::cerr << "Error: Could not write to Digital Logic Sim file\n";
return false;
}
outFile << fileContent;
outFile.close();
return true;
}
// Update multiple subchips at once
bool updateMultipleSubchips(const std::vector<std::pair<std::string, std::vector<uint16_t>>>& updates) {
std::string jsonPath = basePath + chipName + ".json";
// Read entire file
std::ifstream jsonFile(jsonPath);
if (!jsonFile.is_open()) {
std::cerr << "Warning: Could not open Digital Logic Sim file: " << jsonPath << "\n";
return false;
}
std::string fileContent((std::istreambuf_iterator<char>(jsonFile)), std::istreambuf_iterator<char>());
jsonFile.close();
// Process each update
for (const auto& update : updates) {
const std::string& subchipLabel = update.first;
const std::vector<uint16_t>& data = update.second;
// Find the subchip by label
std::string searchStr = "\"Label\":\"" + subchipLabel + "\"";
size_t labelPos = fileContent.find(searchStr);
if (labelPos == std::string::npos) {
std::cerr << "Warning: Could not find subchip with label '" << subchipLabel << "'\n";
continue;
}
// Find InternalData array start after this label
size_t dataStart = fileContent.find("\"InternalData\":[", labelPos);
if (dataStart == std::string::npos) {
std::cerr << "Warning: Could not find InternalData for '" << subchipLabel << "'\n";
continue;
}
size_t arrayStart = dataStart + 16; // Skip "InternalData":[
size_t arrayEnd = fileContent.find("]", arrayStart);
// Build new array string
std::string newArray;
for (size_t i = 0; i < data.size(); i++) {
if (i > 0) newArray += ",";
newArray += std::to_string(data[i]);
}
// Replace old array with new
fileContent.replace(arrayStart, arrayEnd - arrayStart, newArray);
}
// Write back to file
std::ofstream outFile(jsonPath);
if (!outFile.is_open()) {
std::cerr << "Error: Could not write to Digital Logic Sim file\n";
return false;
}
outFile << fileContent;
outFile.close();
std::cout << "Updated Digital Logic Sim chip '" << chipName << "' in: " << jsonPath << "\n";
return true;
}
};
// ============================================
// TOOL DEFINITIONS
// ============================================
// Assembler Tool
class AssemblerTool : public AutoRegisterTool<AssemblerTool> {
private:
std::string inputFile;
std::string outputBase;
IsaSpec::ISA_SPEC isaSpec;
// Helper: Check if mnemonic is an ALU operation (based on type in spec)
bool isAluOperation(const std::string& mnemonic) {
// Search through technical instructions for matching mnemonic with TYPE_ALU
for (const auto& instr : isaSpec.instructions_tech) {
if (instr.mnemonic == mnemonic && instr.type == IsaSpec::InstructionType::TYPE_ALU) {
return true;
}
}
return false;
}
// Helper: Find opcode from mnemonic and operand types using ISA spec
// The compiler differentiates by checking if the last operand is a register or immediate
uint8_t findOpcode(const std::string& mnemonic, bool immediate) {
for (const auto& instr : isaSpec.instructions_tech) {
if (instr.mnemonic == mnemonic && instr.flags.IMMEDIATE == immediate) {
return instr.opcode;
}
}
return 0xFF; // Invalid opcode
}
// Helper: Find opcode from mnemonic, type, and immediate flag
uint8_t findOpcodeByType(const std::string& mnemonic, IsaSpec::InstructionType type, bool immediate) {
for (const auto& instr : isaSpec.instructions_tech) {
if (instr.mnemonic == mnemonic && instr.type == type && instr.flags.IMMEDIATE == immediate) {
return instr.opcode;
}
}
return 0xFF; // Invalid opcode
}
// Helper: Find branch condition code from mnemonic
int findBranchCondition(const std::string& mnemonic) {
for (const auto& branch : isaSpec.branch_conditions) {
if (branch.mnemonic == mnemonic) {
return branch.code;
}
}
return -1;
}
// Symbol table for labels
struct Label {
std::string name;
uint8_t address;
};
std::vector<Label> symbolTable;
// Alias table for register aliasing
struct RegisterAlias {
std::string alias;
std::string registerName; // e.g., "X0", "X1"
};
std::vector<RegisterAlias> aliasTable;
// Helper: Validate alias name (alphanumeric + underscore only)
bool isValidAliasName(const std::string& name) {
if (name.empty()) return false;
// Check that name contains only alphanumeric characters and underscores
for (char c : name) {
if (!std::isalnum(c) && c != '_') {
return false;
}
}
// Check that alias doesn't conflict with instruction mnemonics
if (isAluOperation(name)) return false;
// Check against other instruction mnemonics
const char* reserved[] = {
"MOV", "CMP", "B", "BEQ", "BNE", "BLT", "BLE", "BGT", "BGE",
"BCS", "BCC", "BMI", "BPL", "BVS", "BVC", "BHI", "BLS",
"READ", "WRITE", "PRINT", "EXIT", "NOT"
};
for (const char* mnemonic : reserved) {
if (name == mnemonic) return false;
}
return true;
}
// Helper: Resolve alias to register name
std::string resolveAlias(const std::string& str) {
// Check if this is an alias
for (const auto& alias : aliasTable) {
if (alias.alias == str) {
return alias.registerName;
}
}
// Not an alias, return original
return str;
}
// Helper: Parse register (e.g., "X0" -> 0), with alias support
int parseRegister(const std::string& str) {
// First check if it's an alias
std::string resolved = resolveAlias(str);
if (resolved.length() < 2) return -1;
if (resolved[0] != 'X' && resolved[0] != 'x') return -1;
int reg = std::atoi(resolved.c_str() + 1);
if (reg < 0 || reg > 7) return -1;
return reg;
}
// Helper: Parse constant (hex, binary, decimal, ASCII)
int parseConstant(const std::string& str) {
if (str.empty()) return -1;
// ASCII character literal: 'A' -> 65
if (str.length() == 3 && str[0] == '\'' && str[2] == '\'') {
return (int)(unsigned char)str[1];
}
int value;
if (str.length() > 2 && str[0] == '0') {
if (str[1] == 'x' || str[1] == 'X') {
// Hexadecimal
value = std::strtol(str.c_str(), nullptr, 16);
} else if (str[1] == 'b' || str[1] == 'B') {
// Binary
value = std::strtol(str.c_str() + 2, nullptr, 2);
} else {
// Decimal
value = std::atoi(str.c_str());
}
} else {
// Decimal
value = std::atoi(str.c_str());
}
if (value < 0 || value > 65535) return -1;
return value;
}
// Helper: Strip comments from line
void stripComments(std::string& line, bool& inMultiline) {
std::string result;
size_t i = 0;
size_t len = line.length();
while (i < len) {
if (inMultiline) {
// Look for end of multiline comment */
if (i < len - 1 && line[i] == '*' && line[i+1] == '/') {
inMultiline = false;
i += 2;
} else {
i++;
}
} else {
// Check for start of multiline comment /*
if (i < len - 1 && line[i] == '/' && line[i+1] == '*') {
inMultiline = true;
i += 2;
}
// Check for single-line comment //
else if (i < len - 1 && line[i] == '/' && line[i+1] == '/') {
break; // Rest of line is comment
}
// Regular character
else {
result += line[i++];
}
}
}
line = result;
}
// Helper: Check if line is a label
bool isLabel(const std::string& line) {
size_t colonPos = line.find(':');
if (colonPos == std::string::npos) return false;
std::string labelName = line.substr(0, colonPos);
// Trim whitespace
size_t start = labelName.find_first_not_of(" \t");
if (start == std::string::npos) return false;
labelName = labelName.substr(start);
if (labelName.empty()) return false;
if (!std::isalpha(labelName[0]) && labelName[0] != '_' && labelName[0] != '.') return false;
return true;
}
// Helper: Parse label name
std::string parseLabel(const std::string& line) {
size_t colonPos = line.find(':');
std::string labelName = line.substr(0, colonPos);
// Trim whitespace
size_t start = labelName.find_first_not_of(" \t");
if (start != std::string::npos) {
labelName = labelName.substr(start);
}
return labelName;
}
// Helper: Lookup label in symbol table
int lookupLabel(const std::string& name) {
for (const auto& label : symbolTable) {
if (label.name == name) return label.address;
}
return -1;
}
// Helper: Parse branch condition
int parseBranchCondition(const std::string& mnemonic) {
return findBranchCondition(mnemonic);
}
// Encoding functions
uint32_t encodeAlu(uint8_t op, uint8_t dst, uint16_t src1, uint16_t src2, bool isImmediate) {
uint32_t instr = 0;
uint8_t actualOpcode = isImmediate ? (op | 0x10) : op;
instr |= actualOpcode;
instr |= ((dst & 0x7) << 8);
if (!isImmediate) {
instr |= ((src1 & 0x7) << 12);
instr |= ((src2 & 0x7) << 16);
} else {
instr |= ((src1 & 0x7) << 12);
instr |= ((src2 & 0xFFFF) << 16);
}
return instr;
}
uint32_t encodeMove(uint8_t dst, uint16_t srcOrImm, bool isImmediate) {
uint32_t instr = 0;
uint8_t moveOp = findOpcode("MOV", isImmediate);
instr |= moveOp;
instr |= ((dst & 0x7) << 8);
if (!isImmediate) {
instr |= ((srcOrImm & 0x7) << 12);
} else {
instr |= ((uint32_t)(srcOrImm & 0xFFFF) << 16);
}
return instr;
}
uint32_t encodeCmp(uint8_t src1, uint16_t src2, bool isImmediate) {
uint32_t instr = 0;
uint8_t cmpOp = findOpcode("CMP", isImmediate);
instr |= cmpOp;
if (!isImmediate) {
instr |= ((src1 & 0x7) << 12);
instr |= ((src2 & 0x7) << 16);
} else {
instr |= ((src1 & 0x7) << 12);
instr |= ((uint32_t)(src2 & 0xFFFF) << 16);
}
return instr;
}
uint32_t encodeBranch(uint8_t condition, uint16_t target, bool isImmediate) {
uint32_t instr = 0;
uint8_t branchOp = findOpcode("B", isImmediate);
instr |= branchOp;
if (isImmediate) {
// JI format: OPCODE[8] CONDITION[4] [0000] IMMEDIATE[16]
// Bits 0-7: Opcode
// Bits 8-11: Condition
// Bits 12-15: Always 0000
// Bits 16-31: Immediate address (16 bits)
instr |= ((condition & 0xF) << 8);
instr |= ((uint32_t)(target & 0xFFFF) << 16);
} else {
// J format: OPCODE[8] CONDITION[4] [0000] REG[4] [unused]
// Bits 0-7: Opcode
// Bits 8-11: Condition
// Bits 12-15: Always 0000
// Bits 16-19: Register to jump to
// Bits 20-31: Unused
instr |= ((condition & 0xF) << 8);
instr |= ((target & 0xF) << 16);
}
return instr;
}
uint32_t encodeRead(uint8_t dst, uint8_t addrReg) {
uint32_t instr = 0;
uint8_t readOp = findOpcode("READ", false);
instr |= readOp;
instr |= ((dst & 0x7) << 8);
instr |= ((addrReg & 0x7) << 16);
return instr;
}
uint32_t encodeReadI(uint8_t dst, uint16_t addrImm) {
uint32_t instr = 0;
uint8_t readOp = findOpcode("READ", true);
instr |= readOp;
instr |= ((dst & 0x7) << 8);
instr |= ((uint32_t)(addrImm & 0xFFFF) << 16);
return instr;
}
uint32_t encodeWrite(uint8_t dataReg, uint8_t addrReg) {
uint32_t instr = 0;
uint8_t writeOp = findOpcode("WRITE", false);
instr |= writeOp;
instr |= ((dataReg & 0x7) << 12);
instr |= ((addrReg & 0x7) << 16);
return instr;
}
uint32_t encodeWriteI(uint8_t dataReg, uint16_t addrImm) {
uint32_t instr = 0;
uint8_t writeOp = findOpcode("WRITE", true);
instr |= writeOp;
instr |= ((dataReg & 0x7) << 12);
instr |= ((uint32_t)(addrImm & 0xFFFF) << 16);
return instr;
}
// PRINT encoding per ISA: PRINT <address>, <data>
// PRINT_REG: SCN[R[B]] = R[A] -> address in B (bits 16-18), data in A (bits 12-14)
// PRINT_REG_I: SCN[X] = R[A] -> address in X (bits 16-23), data in A (bits 12-14)
// PRINT_CONST: SCN[R[B]] = Y -> address in B (bits 16-18), data in Y (bits 24-31)
// PRINT_CONST_I: SCN[X] = Y -> address in X (bits 16-23), data in Y (bits 24-31)
uint32_t encodePrintReg(uint8_t dataReg, uint8_t posReg) {
uint32_t instr = 0;
uint8_t printOp = findOpcodeByType("PRINT", IsaSpec::InstructionType::TYPE_PRINT_REG, false);
instr |= printOp;
instr |= ((dataReg & 0x7) << 12); // A field: data register
instr |= ((posReg & 0x7) << 16); // B field: position register
return instr;
}
uint32_t encodePrintRegI(uint8_t dataReg, uint8_t posImm) {
uint32_t instr = 0;
uint8_t printOp = findOpcodeByType("PRINT", IsaSpec::InstructionType::TYPE_PRINT_REG, true);
instr |= printOp;
instr |= ((dataReg & 0x7) << 12); // A field: data register
instr |= ((uint32_t)(posImm & 0xFF) << 16); // X (lower byte of immediate): position
return instr;
}
uint32_t encodePrintConst(uint8_t dataConst, uint8_t posReg) {
uint32_t instr = 0;
uint8_t printOp = findOpcodeByType("PRINT", IsaSpec::InstructionType::TYPE_PRINT_CONST, false);
instr |= printOp;
instr |= ((posReg & 0x7) << 16); // B field: position register
instr |= ((uint32_t)(dataConst & 0xFF) << 24); // Y (upper byte): data constant
return instr;
}
uint32_t encodePrintConstI(uint16_t dataConst, uint8_t posImm) {
uint32_t instr = 0;
uint8_t printOp = findOpcodeByType("PRINT", IsaSpec::InstructionType::TYPE_PRINT_CONST, true);
instr |= printOp;
instr |= ((uint32_t)(posImm & 0xFF) << 16); // X (lower byte): position
instr |= ((uint32_t)(dataConst & 0xFF) << 24); // Y (upper byte): data constant
return instr;
}
// Helper: Split string into tokens
std::vector<std::string> tokenize(const std::string& str) {
std::vector<std::string> tokens;
std::string current;
for (char c : str) {
if (c == ',' || std::isspace(c)) {
if (!current.empty()) {
tokens.push_back(current);
current.clear();
}
} else {
current += c;
}
}
if (!current.empty()) tokens.push_back(current);
return tokens;
}
// Helper: Update ROM data in Digital Logic Sim JSON file
bool updateDigitalLogicSimRom(const std::vector<uint16_t>& alphaData, const std::vector<uint16_t>& betaData) {
DigitalLogicSimHelper simHelper("16-CPU");
std::vector<std::pair<std::string, std::vector<uint16_t>>> updates = {
{"Machine Code ALPHA", alphaData},
{"Machine Code BETA", betaData}
};
std::cout << "Updating Digital Logic Sim project...\n";
return simHelper.updateMultipleSubchips(updates);
}
// Parse a single instruction line
uint32_t parseInstruction(const std::string& line, bool& error, int instructionNumber = -1) {
error = false;
// Trim leading whitespace
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos) return 0;
std::string trimmed = line.substr(start);
if (trimmed.empty() || trimmed[0] == ';' || trimmed[0] == '#') return 0;
if (isLabel(trimmed)) return 0;
// Extract mnemonic
size_t spacePos = trimmed.find_first_of(" \t");
std::string mnemonic = (spacePos == std::string::npos) ? trimmed : trimmed.substr(0, spacePos);
// Convert to uppercase
for (char& c : mnemonic) c = std::toupper(c);
// Extract operands
std::string operands = (spacePos == std::string::npos) ? "" : trimmed.substr(spacePos + 1);
std::vector<std::string> tokens = tokenize(operands);
// LR pseudo-instruction (Load Register with instruction number)
if (mnemonic == "LR") {
if (tokens.size() != 1) { error = true; return 0; }
int dst = parseRegister(tokens[0]);
if (dst == -1) { error = true; return 0; }
if (instructionNumber == -1) {
std::cerr << "Error: LR instruction requires instruction number (internal error)\n";
error = true;
return 0;
}
// Replace with MOV dst, instructionNumber
return encodeMove(dst, instructionNumber, true);
}
// EXIT instruction
if (mnemonic == "EXIT") return 0xFFFFFFFF;
// ALU operations
if (isAluOperation(mnemonic)) {
uint8_t op = findOpcode(mnemonic, false);
if (tokens.size() == 3) {
int dst = parseRegister(tokens[0]);
int src1 = parseRegister(tokens[1]);
if (dst == -1 || src1 == -1) { error = true; return 0; }
int src2Reg = parseRegister(tokens[2]);
if (src2Reg != -1) {
return encodeAlu(op, dst, src1, src2Reg, false);
} else {
int src2Const = parseConstant(tokens[2]);
if (src2Const == -1) { error = true; return 0; }
return encodeAlu(op, dst, src1, src2Const, true);
}
} else if (tokens.size() == 2) {
int dst = parseRegister(tokens[0]);
if (dst == -1) { error = true; return 0; }
int srcReg = parseRegister(tokens[1]);
if (srcReg != -1) {
return encodeAlu(op, dst, srcReg, 0, false);
} else {
int srcConst = parseConstant(tokens[1]);
if (srcConst == -1) { error = true; return 0; }
return encodeAlu(op, dst, srcConst, 0, true);
}
}
error = true;
return 0;
}
// NOT operation
if (mnemonic == "NOT") {
if (tokens.size() != 1) { error = true; return 0; }
int dst = parseRegister(tokens[0]);
if (dst == -1) { error = true; return 0; }
uint8_t notOp = findOpcode("NOT", false);
return encodeAlu(notOp, dst, 0, 0, false);
}
// MOV operation
if (mnemonic == "MOV") {
if (tokens.size() != 2) { error = true; return 0; }
int dst = parseRegister(tokens[0]);
if (dst == -1) { error = true; return 0; }
int srcReg = parseRegister(tokens[1]);
if (srcReg != -1) {
return encodeMove(dst, srcReg, false);
} else {
int srcConst = parseConstant(tokens[1]);
if (srcConst == -1) { error = true; return 0; }
return encodeMove(dst, srcConst, true);
}
}
// CMP operation
if (mnemonic == "CMP") {
if (tokens.size() != 2) { error = true; return 0; }
int src1 = parseRegister(tokens[0]);
if (src1 == -1) { error = true; return 0; }
int src2Reg = parseRegister(tokens[1]);
if (src2Reg != -1) {
return encodeCmp(src1, src2Reg, false);
} else {
int src2Const = parseConstant(tokens[1]);
if (src2Const == -1) { error = true; return 0; }
return encodeCmp(src1, src2Const, true);
}
}
// Branch operations
int condition = parseBranchCondition(mnemonic);
if (condition >= 0) {
if (tokens.size() != 1) { error = true; return 0; }
int targetReg = parseRegister(tokens[0]);
if (targetReg != -1) {
return encodeBranch(condition, targetReg, false);
} else {
// Try as immediate or label
int target = parseConstant(tokens[0]);
if (target == 0 && tokens[0] != "0") {
// Try as label
target = lookupLabel(tokens[0]);
if (target < 0) { error = true; return 0; }
}
if (target < 0 || target > 65535) { error = true; return 0; }
return encodeBranch(condition, target, true);
}
}
// READ operation
if (mnemonic == "READ") {
if (tokens.size() != 2) { error = true; return 0; }
int dst = parseRegister(tokens[0]);
if (dst == -1) { error = true; return 0; }
int addrReg = parseRegister(tokens[1]);
if (addrReg != -1) {
return encodeRead(dst, addrReg);
} else {
int addrImm = parseConstant(tokens[1]);
if (addrImm < 0 || addrImm > 65535) { error = true; return 0; }
return encodeReadI(dst, addrImm);
}
}
// WRITE operation
if (mnemonic == "WRITE") {
if (tokens.size() != 2) { error = true; return 0; }
int dataReg = parseRegister(tokens[0]);
if (dataReg == -1) { error = true; return 0; }
int addrReg = parseRegister(tokens[1]);
if (addrReg != -1) {
return encodeWrite(dataReg, addrReg);
} else {
int addrImm = parseConstant(tokens[1]);
if (addrImm < 0 || addrImm > 65535) { error = true; return 0; }
return encodeWriteI(dataReg, addrImm);
}
}
// PRINT operation
if (mnemonic == "PRINT") {
if (tokens.size() != 2) { error = true; return 0; }
bool isAddrReg = (parseRegister(tokens[0]) != -1);
bool isCodeReg = (parseRegister(tokens[1]) != -1);
if (isAddrReg && isCodeReg) {
int addrReg = parseRegister(tokens[0]);
int codeReg = parseRegister(tokens[1]);
return encodePrintReg(codeReg, addrReg);
} else if (!isAddrReg && isCodeReg) {
int addrImm = parseConstant(tokens[0]);
int codeReg = parseRegister(tokens[1]);
if (addrImm < 0 || addrImm > 255) { error = true; return 0; }
return encodePrintRegI(codeReg, addrImm);
} else if (isAddrReg && !isCodeReg) {
int addrReg = parseRegister(tokens[0]);
int codeConst = parseConstant(tokens[1]);
if (codeConst < 0 || codeConst > 255) { error = true; return 0; }
return encodePrintConst(codeConst, addrReg);
} else {
int addrImm = parseConstant(tokens[0]);
int codeConst = parseConstant(tokens[1]);
if (addrImm < 0 || addrImm > 255 || codeConst < 0 || codeConst > 255) { error = true; return 0; }
return encodePrintConstI(codeConst, addrImm);
}
}
error = true;
return 0;
}
public:
AssemblerTool() : AutoRegisterTool("Assemble Code", "Convert assembly to machine code (ALPHA/BETA ROMs)") {
// Generate ISA spec algorithmically
isaSpec = IsaSpec::generateISASpec();
std::cout << "ISA Specification v" << isaSpec.version << " loaded\n";
std::cout << " " << isaSpec.instructions_tech.size() << " technical instructions, "
<< isaSpec.instructions_doc.size() << " documentation entries, "
<< isaSpec.branch_conditions.size() << " branch conditions\n";
}
void getInputs() override {
std::cout << "Input assembly file: ";
std::getline(std::cin, inputFile);
std::cout << "Output base name (for .out files): ";
std::getline(std::cin, outputBase);
}
void execute(RomFormat outputFormat) override {
// Open input file
std::ifstream input(inputFile);
if (!input.is_open()) {
std::cerr << "Error: Could not open file '" << inputFile << "'\n";
return;
}
// Pass 1: Build symbol table and alias table
symbolTable.clear();
aliasTable.clear();
std::string line;
bool inMultiline = false;
int pc = 0;
while (std::getline(input, line) && pc < 256) {
stripComments(line, inMultiline);
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos) continue;
std::string trimmed = line.substr(start);
if (trimmed.empty()) continue;
// Check for #ALIAS directive
if (trimmed.length() > 6 && trimmed.substr(0, 6) == "#ALIAS") {
std::istringstream iss(trimmed.substr(6));
std::string regName, aliasName;
iss >> regName >> aliasName;
// Validate register name (need to temporarily disable alias resolution)
int regNum = -1;
if (regName.length() >= 2 && (regName[0] == 'X' || regName[0] == 'x')) {
regNum = std::atoi(regName.c_str() + 1);
}
if (regNum < 0 || regNum > 7) {
std::cerr << "Error: Invalid register in #ALIAS: " << regName << "\n";
continue;
}
// Validate alias name
if (!isValidAliasName(aliasName)) {
std::cerr << "Error: Invalid alias name: " << aliasName << "\n";
std::cerr << " Alias names must be alphanumeric with underscores only,\n";
std::cerr << " and must not conflict with instruction mnemonics.\n";
continue;
}
// Add or update alias (subsequent calls overwrite)
bool found = false;
for (auto& alias : aliasTable) {
if (alias.alias == aliasName) {
alias.registerName = regName;
found = true;
break;
}
}
if (!found) {
aliasTable.push_back({aliasName, regName});
}
// Don't increment PC for #ALIAS directives
}
else if (isLabel(trimmed)) {
std::string labelName = parseLabel(trimmed);
symbolTable.push_back({labelName, (uint8_t)pc});
} else {
// Regular instruction, increment PC
pc++;
}
}
// Pass 2: Generate instructions
input.clear();
input.seekg(0);
inMultiline = false;
std::vector<uint32_t> instructions;
while (std::getline(input, line) && instructions.size() < 256) {
stripComments(line, inMultiline);
bool error = false;
// Pass current instruction number for LR pseudo-instruction
uint32_t instr = parseInstruction(line, error, instructions.size());
if (error) {
std::cerr << "Warning: Failed to parse line: " << line << "\n";
continue;
}
size_t start = line.find_first_not_of(" \t");
if (start != std::string::npos) {
std::string trimmed = line.substr(start);
// Skip labels and preprocessor directives (like #ALIAS)
if (!trimmed.empty() && !isLabel(trimmed) && trimmed[0] != '#') {
instructions.push_back(instr);
}
}
}
input.close();
// Prepare ALPHA and BETA data arrays (256 entries, padded with zeros)
std::vector<uint16_t> alphaData(256, 0);
std::vector<uint16_t> betaData(256, 0);
for (size_t i = 0; i < instructions.size(); i++) {
alphaData[i] = (instructions[i] >> 16) & 0xFFFF;
betaData[i] = instructions[i] & 0xFFFF;
}
// Write traditional .out ROM files (only if outputBase is not empty)
if (!outputBase.empty()) {
RomWriter alphaWriter(outputBase + "_ALPHA.out", outputFormat);
RomWriter betaWriter(outputBase + "_BETA.out", outputFormat);
for (size_t i = 0; i < 256; i++) {
alphaWriter.set(i, alphaData[i]);
betaWriter.set(i, betaData[i]);
}
bool success = true;
success &= alphaWriter.writeToFile();
success &= betaWriter.writeToFile();
if (success) {
std::cout << "\nCompiled " << instructions.size() << " instructions\n";
std::cout << "Generated ALPHA ROM: " << outputBase << "_ALPHA.out\n";
std::cout << "Generated BETA ROM: " << outputBase << "_BETA.out\n";
}
} else {
std::cout << "\nCompiled " << instructions.size() << " instructions\n";
std::cout << "Skipping .out file generation (no output base name provided)\n";
}
// Update Digital Logic Sim JSON file
std::cout << "\nUpdating Digital Logic Sim project...\n";
updateDigitalLogicSimRom(alphaData, betaData);
}
};
// Opcode Flags ROM Tool
class OpcodeFlagsRomTool : public AutoRegisterTool<OpcodeFlagsRomTool> {
private:
IsaSpec::ISA_SPEC isaSpec;
public:
OpcodeFlagsRomTool() : AutoRegisterTool("Opcode Flags ROM", "Generate opcode flags for instruction decoding") {
isaSpec = IsaSpec::generateISASpec();
}
#define FLAG_VALID (1 << 0) // Bit 0: Valid instruction
#define FLAG_TYPE_ALU (0 << 1) // Bits 1-4: Instruction type
#define FLAG_TYPE_FPU (1 << 1)
#define FLAG_TYPE_MOVE (2 << 1)
#define FLAG_TYPE_CMP (3 << 1)
#define FLAG_TYPE_BRANCH (4 << 1)
#define FLAG_TYPE_MEMORY (5 << 1)
#define FLAG_TYPE_PRINT_REG (6 << 1)
#define FLAG_TYPE_PRINT_CONST (7 << 1)
#define FLAG_TYPE_SERVICE (8 << 1)
#define FLAG_TYPE_MASK (15 << 1)
#define FLAG_IMMEDIATE (1 << 5) // Bit 5: Is immediate format
#define FLAG_OVERRIDE_WRITE (1 << 11) // Bit 11: OVERRIDE WRITE flag
#define FLAG_OVERRIDE_B (1 << 12) // Bit 12: OVERRIDE B flag
#define FLAG_TRY_READ_A (1 << 13) // Bit 13: Try read A operand
#define FLAG_TRY_READ_B (1 << 14) // Bit 14: Try read B operand
#define FLAG_TRY_WRITE (1 << 15) // Bit 15: Try write result
uint16_t encodeInstructionFlags(const IsaSpec::InstructionTech& instr) {
uint16_t flags = 0;
// Valid flag
if (instr.flags.VALID) flags |= FLAG_VALID;
// Instruction type
switch (instr.type) {