Repository navigation
Expand file tree
/
Copy pathmultipassassembler.cpp
More file actions
1448 lines (1253 loc) · 66.6 KB
/
Copy pathmultipassassembler.cpp
File metadata and controls
1448 lines (1253 loc) · 66.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
#include <iostream>
#include <iomanip>
#include <format>
#include <stack>
#include <sstream>
#include "opcodedict.h"
#include "multipassassembler.h"
#include "opcodeinfo.h"
#include "getmangledsymbol.h"
#include "findanonlabel.h"
#include "utilities.h"
/**
* @file multipassassembler.cpp
* @author Paul Baxter
*/
/**
* @brief Maps 6502 addressing modes to their byte length.
* @param mode Addressing mode (`OP_TYPE`).
* @return Instruction byte count (1 to 3).
*/
size_t MultiPassAssembler::GetInstructionSize(OP_TYPE mode) {
switch (mode) {
case OP_TYPE::Op_Implied:
case OP_TYPE::Op_Accumulator:
return 1;
case OP_TYPE::Op_Immediate:
case OP_TYPE::Op_ZeroPage:
case OP_TYPE::Op_ZeroPageX:
case OP_TYPE::Op_ZeroPageY:
case OP_TYPE::Op_IndirectX:
case OP_TYPE::Op_IndirectY:
case OP_TYPE::Op_Relative:
return 2;
case OP_TYPE::Op_Absolute:
case OP_TYPE::Op_AbsoluteX:
case OP_TYPE::Op_AbsoluteY:
case OP_TYPE::Op_Indirect:
case OP_TYPE::Op_ZeroPageRelative:
return 3;
default:
return 1;
}
}
/**
* @brief Runs multi-pass symbol resolution until convergence or max pass limit.
* @param statements AST statement stream.
* @throws std::runtime_error On convergence failure after max_passes.
*/
void MultiPassAssembler::Assemble(std::vector<std::unique_ptr<Statement>>& statements) {
pass = 1;
changed = true;
island_counter = 0;
stable = false;
loop_level = 0;
auto lastpasschanged = false;
std::vector<AnonymousLabel> anonymous_labels;
if (options.verbose) {
std::cout << "--- Starting Multi-Pass Symbol Resolution ---\n";
}
max_passes = options.max_pass;
for (auto&sym : options.traced_symbols) {
symbols_.Trace(sym);
vars_.Trace(sym);
}
for (auto&[sym, val] : options.defined_symbols) {
changed |= symbols_.Define(sym, static_cast<uint16_t>(val), {0, 0});
}
while ((changed || (wait_stable && !stable)) && pass <= max_passes) {
symbols_.reset_usage();
vars_.reset_usage();
lastpasschanged = changed;
stable = !lastpasschanged;
parent_scope="GLOBAL_";
changed = ResolutionPass(statements, anonymous_labels);
if (options.verbose) {
std::cout << "Pass " << pass << " complete. "
<< (changed ? "Symbols modified (needs another pass)." : "Symbols stable.") << "\n";
}
pass++;
if (wait_stable && stable) {
wait_stable = false;
}
}
if (pc >= 0xFFFF) {
throw std::runtime_error("Program counter exceeded $FFFF.");
}
if (changed) {
throw std::runtime_error("Symbol resolution failed to converge after " + std::to_string(max_passes) +" passes.");
}
parent_scope="GLOBAL_";
symbols_.reset_usage();
vars_.reset_usage();
EmitFinalPass(statements, anonymous_labels);
}
/**
* @brief Main AST worker node processor for multi-pass evaluation and branch relaxation.
* @param statements Original statement AST.
* @param new_statements Target statement queue for current pass.
* @param st_index Current instruction pointer within `statements`.
* @param anonymous_labels Anonymous label mapping.
*/
void MultiPassAssembler::ProcessStatement(std::vector<std::unique_ptr<Statement>>& statements, std::vector<std::unique_ptr<Statement>>&new_statements, size_t& st_index,
std::vector<AnonymousLabel>& anonymous_labels)
{
std::unique_ptr<Statement>&stmt = statements[st_index];
if (!stmt) {
st_index++;
return;
}
switch(stmt->stmt_type) {
case StmtType::Label: {
// Label Statement Handler
auto label_stmt = static_cast<const LabelStatement*>(stmt.get());
std::string name = label_stmt->name;
if (label_stmt->is_anon()) {
std::pair<int, size_t> stmt_key = { label_stmt->file, label_stmt->line };
auto it = anon_idmap.find(stmt_key);
if (it == anon_idmap.end()) {
anonymous_labels.push_back({
.type = name[0],
.address = pc,
.statement_id = stmt_key
});
anon_idmap[stmt_key] = anonymous_labels.size() - 1;
changed = true;
} else {
size_t index = it->second;
if (anonymous_labels[index].address != pc) {
anonymous_labels[index].address = pc;
changed = true;
}
}
new_statements.push_back(std::move(stmt));
} else {
if (label_stmt->is_local()) {
name = GetMangledSymbol(name, parent_scope);
} else {
// Global label sets the active parent scope for subsequent local labels
parent_scope = name;
}
// Ensure label doesn't conflict with an existing variable name
if (vars_.Lookup(name, { label_stmt->file, label_stmt->line })) {
throw std::runtime_error(
std::format("Symbol '{}' is already defined as a variable at ${:04X} File: {} Line: {}",
name, pc, src_mgr.GetFileName(label_stmt->file), label_stmt->line));
}
changed |= symbols_.Define(name, pc, { label_stmt->file, label_stmt->line });
new_statements.push_back(std::move(stmt));
}
break;
}
case StmtType::Org: {
// Origin (* = expr) Statement Handler
auto org_stmt = static_cast<const OrgStatement*>(stmt.get());
if (org_stmt->address_expr) {
auto val_expr = EvaluateExpr(org_stmt->address_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (val_expr.has_value()) {
int32_t raw_addr = val_expr.value();
if (raw_addr < 0 || raw_addr > 0xFFFF) {
throw std::runtime_error(
std::format("Origin address out of range (${:X}) at File: {} Line: {}",
raw_addr, src_mgr.GetFileName(org_stmt->file), org_stmt->line));
}
pc = static_cast<uint16_t>(raw_addr);
}
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Var: {
// Variable (.var / reassignment) Statement Handler
auto var_stmt = static_cast<const VarStatement*>(stmt.get());
for (const auto& [name, expr] : var_stmt->vars) {
int64_t initial_val = 0;
if (expr) {
auto val_expr = EvaluateExpr(expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (val_expr.has_value()) {
initial_val = val_expr.value();
} else {
throw std::runtime_error(
std::format("Invalid or unresolvable initializer expression for variable '{}' at File: {} Line: {}",
name, src_mgr.GetFileName(var_stmt->file), var_stmt->line));
}
}
// Unconditionally set/update variable value; do NOT mutate 'changed' flag
vars_.Define(name, static_cast<uint16_t>(initial_val), { var_stmt->file, var_stmt->line });
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Equ: {
// Equate (.equ / =) Constant Definition Handler
auto equ_stmt = static_cast<const EquStatement*>(stmt.get());
if (equ_stmt->value_expr) {
std::string name = equ_stmt->name;
if (equ_stmt->is_local()) {
name = GetMangledSymbol(name, parent_scope);
}
auto val_expr = EvaluateExpr(equ_stmt->value_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (val_expr.has_value()) {
// If the name is already defined as a variable (.var), update the variable table
if (vars_.Lookup(name, { equ_stmt->file, equ_stmt->line })) {
vars_.Define(name, static_cast<uint16_t>(val_expr.value()), { equ_stmt->file, equ_stmt->line });
} else {
// Otherwise, define it as an immutable symbol constant
changed |= symbols_.Define(name, static_cast<uint16_t>(val_expr.value()), { equ_stmt->file, equ_stmt->line });
}
}
} else {
throw std::runtime_error(
std::format("Missing expression in .equ directive at File: {} Line: {}",
src_mgr.GetFileName(equ_stmt->file), equ_stmt->line));
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Ds: {
// Define Storage (.ds) Statement Handler
auto ds_stmt = static_cast<const DsStatement*>(stmt.get());
if (ds_stmt->size_expr) {
auto val_expr = EvaluateExpr(ds_stmt->size_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (val_expr.has_value()) {
int32_t count = val_expr.value();
if (count < 0) {
throw std::runtime_error(
std::format("Negative allocation size ({}) in .ds at File: {} Line: {}",
count, src_mgr.GetFileName(ds_stmt->file), ds_stmt->line));
}
pc += static_cast<uint16_t>(count);
} else {
// Unresolved size expression during early pass; PC advance deferred to next pass
}
} else {
throw std::runtime_error(
std::format("Missing size expression in .ds directive at File: {} Line: {}",
src_mgr.GetFileName(ds_stmt->file), ds_stmt->line));
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Data: {
// Data (.byte, .word) Statement Handler
auto data_stmt = static_cast<const DataStatement*>(stmt.get());
uint16_t bytes_per_elem = (data_stmt->width == DataWidth::Byte) ? 1 : 2;
// Parser flattens string literals into individual NumberExpr nodes,
// making elements.size() exact for total byte/word count.
pc += static_cast<uint16_t>(data_stmt->elements.size() * bytes_per_elem);
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Fill: {
// Fill (.fill length, value) Statement Handler
auto fill_stmt = static_cast<const FillStatement*>(stmt.get());
if (fill_stmt->length_expr) {
auto len_expr = EvaluateExpr(fill_stmt->length_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (len_expr.has_value()) {
int32_t len_val = len_expr.value();
if (len_val < 0) {
throw std::runtime_error(
std::format("Negative length value ({}) in .fill directive at File: {} Line: {}",
len_val, src_mgr.GetFileName(fill_stmt->file), fill_stmt->line));
}
pc += static_cast<uint16_t>(len_val);
} else {
// Early pass handling if length expression contains forward references
}
} else {
throw std::runtime_error(
std::format("Missing length expression in .fill directive at File: {} Line: {}",
src_mgr.GetFileName(fill_stmt->file), fill_stmt->line));
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Break: {
// Loop Break (.break) Statement Handler
if (loop_level < 1) {
throw std::runtime_error(
std::format(".break used outside of a loop at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line)
);
}
loopControl = LoopControlKind::break_loop;
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Continue: {
// Loop Continue (.continue) Statement Handler
if (loop_level < 1) {
throw std::runtime_error(
std::format(".continue used outside of a loop at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line)
);
}
loopControl = LoopControlKind::continue_loop;
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Loop: {
// Loop Directive (.while / .repeat) Execution Engine
loop_level++;
auto loop_stmt = static_cast<LoopStatement*>(stmt.get());
if (!loop_stmt->condition_expr) {
throw std::runtime_error(
std::format("Loop condition expression must be defined at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(loop_stmt->file), loop_stmt->line));
}
// Helper lambda to check for loop boundaries
auto is_loop_start = [](const std::unique_ptr<Statement>& s) {
return s && s->stmt_type == StmtType::Loop;
};
auto is_loop_end = [](const std::unique_ptr<Statement>& s) {
return s && (s->stmt_type == StmtType::Wend || s->stmt_type == StmtType::Until);
};
// 1. Capture original loop body template ONCE on first pass (depth-aware)
if (loop_stmt->statements.empty()) {
size_t scan_idx = st_index + 1;
int depth = 1;
while (scan_idx < statements.size() && statements[scan_idx] && depth > 0) {
if (is_loop_start(statements[scan_idx])) {
depth++;
} else if (is_loop_end(statements[scan_idx])) {
depth--;
if (depth == 0) {
break; // Found matching outer closing keyword (.wend / .until)
}
}
loop_stmt->statements.push_back(statements[scan_idx]->clone());
scan_idx++;
}
}
loopControl = LoopControlKind::normal;
// 2. Unroll and execute loop iterations into new_statements for THIS pass
int iteration_count = 0;
const int MAX_ITERATIONS = 64000;
while (iteration_count < MAX_ITERATIONS) {
// Top-tested loop condition (.while)
if (loop_stmt->test_at_top) {
auto condition = EvaluateExpr(loop_stmt->condition_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (!condition.has_value()) {
throw std::runtime_error(
std::format("Loop expression could not be evaluated at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(loop_stmt->file), loop_stmt->line));
}
int32_t val = condition.value();
bool exit_loop = loop_stmt->reverse_logic ? (val != 0) : (val == 0);
if (exit_loop) {
break;
}
}
// Clone template statements for current iteration
std::vector<std::unique_ptr<Statement>> iteration_body;
iteration_body.reserve(loop_stmt->statements.size());
for (const auto& body_stmt : loop_stmt->statements) {
if (body_stmt) {
iteration_body.push_back(body_stmt->clone());
}
}
// Process iteration body statements
size_t inner_index = 0;
while (inner_index < iteration_body.size()) {
ProcessStatement(iteration_body, new_statements, inner_index, anonymous_labels);
if (loopControl == LoopControlKind::break_loop || loopControl == LoopControlKind::continue_loop) {
break;
}
}
// Handle .break exit
if (loopControl == LoopControlKind::break_loop) {
loopControl = LoopControlKind::normal;
break;
}
// Reset loop control flag for next iteration (.continue resets to normal)
loopControl = LoopControlKind::normal;
// Bottom-tested loop condition (.repeat ... .until)
if (!loop_stmt->test_at_top) {
auto condition = EvaluateExpr(loop_stmt->condition_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (!condition.has_value()) {
throw std::runtime_error(
std::format("Loop expression could not be evaluated at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(loop_stmt->file), loop_stmt->line));
}
int32_t val = condition.value();
bool exit_loop = loop_stmt->reverse_logic ? (val != 0) : (val == 0);
if (exit_loop) {
break;
}
}
iteration_count++;
}
if (iteration_count >= MAX_ITERATIONS) {
throw std::runtime_error(
std::format("Infinite loop iteration limit reached ({}) at ${:04X} File: {} Line: {}",
MAX_ITERATIONS, pc, src_mgr.GetFileName(loop_stmt->file), loop_stmt->line));
}
// 3. Advance main driver index past the matching outer end keyword
size_t skip_idx = st_index + 1;
size_t skip_depth = 1;
while (skip_idx < statements.size() && statements[skip_idx] && skip_depth > 0) {
if (is_loop_start(statements[skip_idx])) {
skip_depth++;
} else if (is_loop_end(statements[skip_idx])) {
skip_depth--;
if (skip_depth == 0) {
break;
}
}
skip_idx++;
}
if (skip_depth != 0) {
throw std::runtime_error(
std::format("Loop missing closing termination directive (.wend / .until) at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(loop_stmt->file), loop_stmt->line));
}
st_index = skip_idx;
loop_level--;
break;
}
case StmtType::IncBin: {
// Binary File Inclusion (.incbin) Statement Handler
auto incbin_stmt = static_cast<const IncBinStatement*>(stmt.get());
size_t bytes_to_read = incbin_stmt->filesize;
if (incbin_stmt->length_expr) {
auto length_expr = EvaluateExpr(incbin_stmt->length_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (length_expr.has_value()) {
int32_t length = length_expr.value();
if (length < 0) {
throw std::runtime_error(
std::format("Negative length ({}) in .incbin directive at File: {} Line: {}",
length, src_mgr.GetFileName(incbin_stmt->file), incbin_stmt->line));
}
if (length > 0) {
bytes_to_read = static_cast<size_t>(length);
}
} else {
// Unresolved length expression during early pass; defer length calculations
}
}
pc += static_cast<uint16_t>(bytes_to_read);
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Instruction: {
// 6502 / 65C02 Opcode Instruction Handler & Optimization Engine
auto inst_stmt = static_cast<InstructionStatement*>(stmt.get());
const OpCodeInfo* info = FindOpCodeInfo(inst_stmt->mnemonic);
if (!info) {
throw std::runtime_error(
std::format("Unknown opcode '{}' at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
// Guard: Validate CPU architecture requirements for 65C02-only instructions/modes
if (info->is_65c02 && options.cpu != CPU::_65C02) {
throw std::runtime_error(
std::format("Instruction '{}' requires 65C02 mode (CPU mode set to standard 6502) at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
// 1. Initial Addressing Mode Resolution & Fallback Lookup
auto mode_it = info->mode_to_opcode.find(inst_stmt->mode);
if (mode_it == info->mode_to_opcode.end()) {
switch (inst_stmt->mode) {
case OP_TYPE::Op_Implied:
mode_it = info->mode_to_opcode.find(OP_TYPE::Op_Accumulator);
break;
case OP_TYPE::Op_Absolute:
mode_it = info->mode_to_opcode.find(OP_TYPE::Op_ZeroPage);
break;
case OP_TYPE::Op_AbsoluteX:
mode_it = info->mode_to_opcode.find(OP_TYPE::Op_ZeroPageX);
break;
case OP_TYPE::Op_AbsoluteY:
mode_it = info->mode_to_opcode.find(OP_TYPE::Op_ZeroPageY);
break;
default:
break;
}
if (mode_it == info->mode_to_opcode.end()) {
throw std::runtime_error(
std::format("Unsupported addressing mode for opcode '{}' at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
}
// Guard: Validate opcode requirement (e.g. BRA, STZ, PHY, PLY, BBR, BBS, etc.)
if (info->is_65c02 && options.cpu != CPU::_65C02) {
throw std::runtime_error(
std::format("Instruction '{}' requires 65C02 mode at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
// Guard: Validate 65C02-specific operand addressing modes
if (inst_stmt->mode == OP_TYPE::Op_ZeroPageRelative && options.cpu != CPU::_65C02) {
throw std::runtime_error(
std::format("Addressing mode for '{}' requires 65C02 mode at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
// 2. Operand Evaluation & Mode Optimization / Relaxation
auto val_expr = EvaluateExpr(inst_stmt->operand.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (val_expr.has_value()) {
int64_t operand_value = val_expr.value();
if (inst_stmt->mode == OP_TYPE::Op_Relative) {
// Branch Distance Calculation
int64_t offset = operand_value - (static_cast<int64_t>(pc) + 2);
if (offset < -128 || offset > 127) {
wait_stable = true;
}
// Perform Long Branch Relaxation / Trampoline Island Insertion once pass state is stable
if (stable && (offset < -128 || offset > 127)) {
int64_t target = operand_value;
if (offset > 0) {
target += 3; // Account for inserted 3-byte JMP island
}
std::string skip_label = std::format("@__island{}", ++island_counter);
auto it = inverted_branches.find(inst_stmt->mnemonic);
if (it != inverted_branches.end()) {
if (options.warnings) {
std::cout << std::format(
"Warning: Branch out of range for '{}' target: ${:04X} [{}] at ${:04X} File: {} Line: {}\n",
inst_stmt->mnemonic, target, offset, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line);
}
std::pair<int, int> loc = { stmt->file, stmt->line };
// Create JMP target instruction using original operand
auto jmp_inst = std::make_unique<InstructionStatement>(
stmt->file, stmt->line, "jmp", OP_TYPE::Op_Absolute, std::move(inst_stmt->operand)
);
// Create inverted conditional branch jumping over the JMP
auto branch_inst = std::make_unique<InstructionStatement>(
stmt->file, stmt->line, it->second, OP_TYPE::Op_Relative,
std::make_unique<SymbolExpr>(skip_label, loc)
);
// Create landing label past the JMP instruction
auto label_inst = std::make_unique<LabelStatement>(
stmt->file, stmt->line, skip_label
);
// Update Program Counter for generated instructions
pc += GetInstructionSize(OP_TYPE::Op_Relative);
pc += GetInstructionSize(OP_TYPE::Op_Absolute);
// Emit relaxation sequence
new_statements.push_back(std::move(branch_inst));
new_statements.push_back(std::move(jmp_inst));
new_statements.push_back(std::move(label_inst));
break;
} else {
throw std::runtime_error(
std::format("Relative branch out of range for uninvertible mnemonic '{}' at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
}
} else {
// Absolute / Zero-Page Address Range Optimization
if (!options.ignore_size && (operand_value < 0 || operand_value > 0xFFFF)) {
throw std::runtime_error(
std::format("Operand address out of range (${:X}) for '{}' at ${:04X} File: {} Line: {}",
operand_value, inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
OP_TYPE want_mode = inst_stmt->mode;
if (operand_value <= 0xFF) {
// Demote Absolute -> ZeroPage when address fits in single byte
if (inst_stmt->mode == OP_TYPE::Op_Absolute) want_mode = OP_TYPE::Op_ZeroPage;
else if (inst_stmt->mode == OP_TYPE::Op_AbsoluteX) want_mode = OP_TYPE::Op_ZeroPageX;
else if (inst_stmt->mode == OP_TYPE::Op_AbsoluteY) want_mode = OP_TYPE::Op_ZeroPageY;
if (want_mode != inst_stmt->mode) {
if (info->mode_to_opcode.contains(want_mode)) {
inst_stmt->mode = want_mode;
}
}
} else {
// Promote ZeroPage -> Absolute when address exceeds single byte
if (inst_stmt->mode == OP_TYPE::Op_ZeroPage) want_mode = OP_TYPE::Op_Absolute;
else if (inst_stmt->mode == OP_TYPE::Op_ZeroPageX) want_mode = OP_TYPE::Op_AbsoluteX;
else if (inst_stmt->mode == OP_TYPE::Op_ZeroPageY) want_mode = OP_TYPE::Op_AbsoluteY;
if (want_mode != inst_stmt->mode) {
if (info->mode_to_opcode.contains(want_mode)) {
inst_stmt->mode = want_mode;
} else {
throw std::runtime_error(
std::format("Operand out of range for Zero-Page instruction '{}' at ${:04X} File: {} Line: {}",
inst_stmt->mnemonic, pc, src_mgr.GetFileName(inst_stmt->file), inst_stmt->line));
}
}
}
}
}
pc += GetInstructionSize(inst_stmt->mode);
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::Until:
case StmtType::Wend: {
// Loop Termination (.until / .wend) Statement Handler
if (loop_level < 1) {
throw std::runtime_error(
std::format("Loop termination directive used outside of a loop at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line));
}
new_statements.push_back(std::move(stmt));
break;
}
case StmtType::If: {
// Conditional Assembly (.if / .else / .endif) Handler
auto if_stmt = static_cast<IfStatement*>(stmt.get());
if (!if_stmt->condition_expr) {
throw std::runtime_error(
std::format("'if' condition expression missing at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(if_stmt->file), if_stmt->line));
}
// 1. Capture 'then' and 'else' statement bodies ONCE on first pass (depth-aware)
if (if_stmt->then_statements.empty() && if_stmt->else_statements.empty()) {
size_t scan_idx = st_index + 1;
int depth = 1;
bool in_else = false;
while (scan_idx < statements.size() && statements[scan_idx] && depth > 0) {
auto st_type = statements[scan_idx]->stmt_type;
if (st_type == StmtType::If) {
depth++;
} else if (st_type == StmtType::EndIf) {
depth--;
if (depth == 0) {
break; // Matched outer closing .endif
}
} else if (st_type == StmtType::Else && depth == 1) {
if (in_else) {
throw std::runtime_error(
std::format("Duplicate 'else' directive at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(statements[scan_idx]->file), statements[scan_idx]->line));
}
in_else = true;
scan_idx++;
continue;
}
if (in_else) {
if_stmt->else_statements.push_back(statements[scan_idx]->clone());
} else {
if_stmt->then_statements.push_back(statements[scan_idx]->clone());
}
scan_idx++;
}
if (depth != 0) {
throw std::runtime_error(
std::format("Unmatched 'if' directive missing 'endif' at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(if_stmt->file), if_stmt->line));
}
}
// 2. Evaluate condition expression for current pass
auto condition = EvaluateExpr(if_stmt->condition_expr.get(), anonymous_labels, symbols_, vars_, parent_scope, pc);
if (!condition.has_value()) {
throw std::runtime_error(
std::format("'if' condition could not be evaluated at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(if_stmt->file), if_stmt->line));
}
// 3. Process active branch statements into new_statements
const auto& active_branch = (condition.value() != 0) ? if_stmt->then_statements : if_stmt->else_statements;
std::vector<std::unique_ptr<Statement>> branch_body;
branch_body.reserve(active_branch.size());
for (const auto& body_stmt : active_branch) {
if (body_stmt) {
branch_body.push_back(body_stmt->clone());
}
}
size_t inner_index = 0;
while (inner_index < branch_body.size()) {
ProcessStatement(branch_body, new_statements, inner_index, anonymous_labels);
}
// 4. Advance driver index past the matching outer 'endif'
size_t skip_idx = st_index + 1;
int skip_depth = 1;
while (skip_idx < statements.size() && statements[skip_idx] && skip_depth > 0) {
auto st_type = statements[skip_idx]->stmt_type;
if (st_type == StmtType::If) {
skip_depth++;
} else if (st_type == StmtType::EndIf) {
skip_depth--;
if (skip_depth == 0) {
break;
}
}
skip_idx++;
}
st_index = skip_idx;
break;
}
case StmtType::Else: {
// Orphaned .else Directive Trap
throw std::runtime_error(
std::format("Unexpected 'else' directive without matching 'if' at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line));
}
case StmtType::EndIf: {
// Orphaned .endif Directive Trap
throw std::runtime_error(
std::format("Unexpected 'endif' directive without matching 'if' at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line));
}
case StmtType::Print: {
// Print (.print) Directive Handler
new_statements.push_back(std::move(stmt));
break;
}
default: {
// Unknown or Unhandled AST Node Catch-All
throw std::runtime_error(
std::format("Unknown statement type at ${:04X} File: {} Line: {}",
pc, src_mgr.GetFileName(stmt->file), stmt->line));
} }
st_index++;
}
/**
* @brief Driver loop for a single symbol resolution pass.
* @return True if state mutated during this pass, forcing another pass.
*/
bool MultiPassAssembler::ResolutionPass(std::vector<std::unique_ptr<Statement>>& statements, std::vector<AnonymousLabel>& anonymous_labels) {
vars_.clear();
loopControl = LoopControlKind::normal;
changed = false;
std::vector<std::unique_ptr<Statement>> new_statements;
new_statements.reserve(statements.size());
pc = start_pc_;
size_t st_index = 0;
while (st_index < statements.size()) {
ProcessStatement(statements, new_statements, st_index, anonymous_labels);
}
statements = std::move(new_statements);
return changed;
}
/**
* @brief Formats a 6502 operand into its standard assembly string representation.
*
* Takes a target addressing mode and an evaluated numerical value, returning a formatted
* syntax string matching standard 6502 assembly conventions (e.g., "#$FF", "$1234,X", "($00,X)").
*
* @param mode The addressing mode of the instruction operand (`OP_TYPE`).
* @param val The 64-bit evaluated numerical value or target address for the operand.
* @param val2 The 64-bit evaluated numerical value or target address for the ZeroPageRelative operand.
* @return A `std::string` containing the formatted operand representation, or an empty string
* for implied or unhandled modes.
*/
std::string MultiPassAssembler::FormatOperand(OP_TYPE mode, int64_t val, int64_t val2 = 0) {
uint16_t v = static_cast<uint16_t>(val);
uint16_t v2 = static_cast<uint16_t>(val2);
switch (mode) {
case OP_TYPE::Op_Immediate:
return std::format("#${:02X}", v & 0xFF);
case OP_TYPE::Op_ZeroPage:
return std::format("${:02X}", v & 0xFF);
case OP_TYPE::Op_ZeroPageX:
return std::format("${:02X},X", v & 0xFF);
case OP_TYPE::Op_ZeroPageY:
return std::format("${:02X},Y", v & 0xFF);
case OP_TYPE::Op_Absolute:
return std::format("${:04X}", v);
case OP_TYPE::Op_AbsoluteX:
return std::format("${:04X},X", v);
case OP_TYPE::Op_AbsoluteY:
return std::format("${:04X},Y", v);
case OP_TYPE::Op_Indirect:
return std::format("(${:04X})", v);
case OP_TYPE::Op_IndirectX:
return std::format("(${:02X},X)", v & 0xFF);
case OP_TYPE::Op_IndirectY:
return std::format("(${:02X}),Y", v & 0xFF);
case OP_TYPE::Op_Relative:
return std::format("${:04X}", v);
case OP_TYPE::Op_ZeroPageRelative:
return std::format("${:02X}, ${:04X}", v, v2);
case OP_TYPE::Op_Accumulator:
return "A";
case OP_TYPE::Op_Implied:
default:
return "";
}
}
/**
* @brief Performs the final pass of assembly, generating binary machine code and the assembly listing.
*
* Iterates through the AST statement collection to evaluate final symbol/variable expressions,
* compute relative branch offsets, emit machine code bytes into the target binary buffer,
* and assemble a formatted multi-column assembly listing output (`listing_file`).
*
* @param statements A vector of unique pointers to AST `Statement` objects representing the source.
* @param anonymous_labels Vector of resolved anonymous label references.
*
* @throws std::runtime_error If print stack underflows, unknown print directives are encountered,
* symbols/expressions fail to evaluate, relative branches exceed [-128, 127],
* operands exceed address size limits, or PC attempts to move backward.
*/
void MultiPassAssembler::EmitFinalPass(const std::vector<std::unique_ptr<Statement>>& statements,
const std::vector<AnonymousLabel>& anonymous_labels) {
vars_.clear();
loopControl = LoopControlKind::normal;
pc = start_pc_;
std::ostringstream listing;
listing << "\n========================================================================================================================\n";
listing << " ASSEMBLY LISTING\n";
listing << "========================================================================================================================\n";
listing << "LINE ADDR BYTES SIMPLIFIED LISTING ORIGINAL SOURCE\n";
listing << "------------------------------------------------------------------------------------------------------------------------\n";
std::stack<bool> pr_stack;
bool printstate = true;
std::map<int, int> file_last_printed_line;
int last_file = -1;
for (const auto& stmt : statements) {
if (!stmt) continue;
// 1. Process Print Control Directives FIRST
if (stmt->stmt_type == StmtType::Print) {
auto prn = static_cast<const PrintStatement*>(stmt.get());
switch (prn->cmd) {
case PrintCmd::on: printstate = true; break;
case PrintCmd::off: printstate = false; break;
case PrintCmd::push: pr_stack.push(printstate); break;
case PrintCmd::pop:
if (pr_stack.empty()) {
throw std::runtime_error(
std::format("Print stack underflow at File: {} Line: {}",
src_mgr.GetFileName(prn->file), prn->line));
}
printstate = pr_stack.top();
pr_stack.pop();
break;
default:
throw std::runtime_error(
std::format("Unknown print directive at File: {} Line: {}",
src_mgr.GetFileName(prn->file), prn->line));
}
file_last_printed_line[stmt->file] = stmt->line;
continue;
}
// Helper: Catch up unprinted source lines (comments, blank lines)
auto sync_file_and_line_catchup = [&](int target_line) {
if (stmt->file != last_file) {
listing << "Processing " << src_mgr.GetFileName(stmt->file) << "\n";
last_file = stmt->file;
}
int& last_printed = file_last_printed_line[stmt->file];
while (last_printed + 1 < target_line) {
last_printed++;
std::string src_text = src_mgr.GetLine(stmt->file, last_printed);
listing << std::format("{:5d}) {:7}{:14} {:30} {}\n", last_printed, "", "", "", src_text);
}
};
// Helper: Format and emit listing row
auto emit_listing_row = [&](uint16_t row_pc, const std::string& hex_bytes, const std::string& simplified_stmt) {
sync_file_and_line_catchup(stmt->line);
int& last_printed = file_last_printed_line[stmt->file];
if (last_printed < stmt->line) {
std::string src_text = src_mgr.GetLine(stmt->file, stmt->line);
listing << std::format("{:5d}) ${:04X} {:14} {:30} {}\n", stmt->line, row_pc, hex_bytes, simplified_stmt, src_text);
last_printed = stmt->line;
} else {
listing << std::format(" ${:04X} {:14} {:30}\n", row_pc, hex_bytes, simplified_stmt);
}
};
// Helper: Append emitted byte buffer to binary output image
auto emit_bytes = [&](const std::vector<uint8_t>& emitted_bytes) {
if (!load_address_set) {
load_address = pc;
load_address_set = true;
if (options.verbose) {
std::cout << std::format("Auto set load address to ${:04X}\n", pc);
}
}
size_t current_binary_size = binary_output.size();
if (current_binary_size + load_address < pc) {
size_t padding_bytes = pc - load_address - current_binary_size;
std::vector<uint8_t> ds_data(padding_bytes, 0x00);
if (options.verbose) {
std::cout << std::format("Warning: Inserting {} padding bytes before ${:04X}\n", padding_bytes, pc);
}
binary_output.insert(binary_output.end(), ds_data.begin(), ds_data.end());
} else if (current_binary_size + load_address > pc) {