uxn-tal 0.1.4

A Rust library for assembling TAL (Tal Assembly Language) files into UXN ROM files
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Main assembler implementation

use crate::devicemap::{parse_device_maps, Device, DeviceField};
use crate::error::{AssemblerError, Result};
use crate::lexer::{Lexer, TokenWithPos};
use crate::opcodes::Opcodes;
use crate::parser::{AstNode, Parser};
use crate::rom::Rom;
use std::collections::HashMap;
use std::fs;

/// Macro definition
#[derive(Debug, Clone)]
pub struct Macro {
    pub name: String,
    pub body: Vec<AstNode>,
}

/// Symbol table entry
#[derive(Debug, Clone)]
pub struct Symbol {
    pub address: u16,
    pub is_sublabel: bool,
    pub parent_label: Option<String>,
}

/// TAL assembler
pub struct Assembler {
    opcodes: Opcodes,
    symbols: HashMap<String, Symbol>,
    macros: HashMap<String, Macro>,
    current_label: Option<String>,
    references: Vec<Reference>,
    device_map: HashMap<String, Device>, // device name -> Device
    line_number: usize,
    position_in_line: usize,
    effective_length: usize, // Track effective length like uxnasm.c
    //lambda_counter: u16, // Add lambda counter as a field
    lambda_counter: usize,
    lambda_stack: Vec<usize>,
}

/// Represents a forward reference that needs to be resolved
#[derive(Debug, Clone)]
struct Reference {
    name: String,
    rune: char,
    address: u16,
    line: usize,
    path: String,
    scope: Option<String>, // Add scope context
    token: Option<TokenWithPos>,
}

impl Assembler {
    /// Generate symbol file content in binary format
    /// Format: [address:u16][name:null-terminated string] repeating
    pub fn generate_symbol_file(&self) -> Vec<u8> {
        let mut symbols: Vec<_> = self.symbols.iter().collect();
        symbols.sort_by_key(|(_, symbol)| symbol.address);
        let mut output = Vec::new();
        for (name, symbol) in symbols {
            // Write address as big-endian u16 (C code: hb first, then lb)
            output.push((symbol.address >> 8) as u8); // high byte
            output.push((symbol.address & 0xff) as u8); // low byte
                                                        // Write name as null-terminated string
            output.extend_from_slice(name.as_bytes());
            output.push(0); // null terminator
        }
        output
    }


    /// Generate symbol file content in binary format
    /// Format: [address:u16][name:null-terminated string] repeating
    pub fn generate_symbol_file_binary(&self) -> Vec<u8> {
        let mut symbols: Vec<_> = self.symbols.iter().collect();
        symbols.sort_by_key(|(_, symbol)| symbol.address);

        let mut output = Vec::new();
        for (name, symbol) in symbols {
            // Write address as little-endian u16
            output.extend_from_slice(&symbol.address.to_le_bytes());
            // Write name as null-terminated string
            output.extend_from_slice(name.as_bytes());
            output.push(0); // null terminator
        }
        output
    }

    /// Generate symbol file content in textual format (address and name per line)
    pub fn generate_symbol_file_txt(&self) -> String {
        let mut symbols: Vec<_> = self.symbols.iter().collect();
        symbols.sort_by_key(|(_, symbol)| symbol.address);
        let mut output = String::new();
        for (name, symbol) in symbols {
            output.push_str(&format!("{:04X} {}\n", symbol.address, name));
        }
        output
    }

    /// Create a new assembler instance
    pub fn new() -> Self {
        Self {
            opcodes: Opcodes::new(),
            symbols: HashMap::new(),
            macros: HashMap::new(),
            current_label: None,
            references: Vec::new(),
            device_map: HashMap::new(),
            line_number: 0,
            position_in_line: 0,
            effective_length: 0,
lambda_counter: 0,
lambda_stack: Vec::new(),
        }
    }

    /// Update effective length if current position has non-zero content
    fn update_effective_length(&mut self, rom: &Rom) {
        self.effective_length = self.effective_length.max(rom.position().into());
    }

    /// Assemble TAL source code into a ROM
    pub fn assemble(&mut self, source: &str, path: Option<String>) -> Result<Vec<u8>> {
        // Clear previous state
        self.symbols.clear();
        self.current_label = None;
        self.references.clear();
        self.device_map.clear();
        self.line_number = 0;
        self.position_in_line = 0;
        self.effective_length = 0; // Reset effective length
        self.lambda_counter = 0; // Reset lambda counter

        // Tokenize
        let mut lexer = Lexer::new(source.to_string(), path.clone());
        let tokens = lexer.tokenize()?;

        // Parse
        // Use "(input)" as the default path if none is provided
        let mut parser =
            Parser::new_with_source(tokens, path.clone().unwrap_or_default(), source.to_string());
        let ast = parser.parse()?;

        // First pass: collect labels and generate code
        let mut rom = Rom::new();
        rom.set_source(Some(source.to_string()));
        rom.set_path(path.clone());
        self.first_pass(&ast, &mut rom)?;

        // Only print collected labels and references if a label resolution fails (see second_pass)

        // Second pass: resolve references
        self.second_pass(&mut rom)?;
        println!("DEBUG: Resolved {} references", self.references.len());

        // Get the final ROM data using effective length (like uxnasm.c)
        let rom_data = rom.data();

        // Count ALL labels like uxnasm.c does (don't filter out device fields)
        let total_label_count = self.symbols.len();

        // If the ROM has content starting at 0x0100 or later, exclude the first 256 bytes
        // This matches the behavior of ruxnasm and uxnasm.c
        let rom_len = rom.len();
        if rom_len > 0 {
            let has_zero_page_data = rom.has_zero_page_data();
            if !has_zero_page_data {
                println!(
                    "Assembled {} in {} bytes({:.2}% used), {} labels, {} macros.",
                    path.clone().unwrap_or_else(|| "(input)".to_string()),
                    rom_len,
                    rom_len as f64 / 652.80,
                    total_label_count,
                    self.macros.len()
                );
                // Output the ROM data starting at 0x0100, length rom_len
                return Ok(rom.data().to_vec());
            }
        }
        Ok(rom_data[..rom_len.min(rom_data.len())].to_vec())
    }

    fn first_pass(&mut self, ast: &[AstNode], rom: &mut Rom) -> Result<()> {
        let mut i = 0;
        while i < ast.len() {
            // Remove special handling for SublabelDef here
            self.process_node(&ast[i], rom)?;
            i += 1;
        }
        Ok(())
    }

    fn process_node(&mut self, node: &AstNode, rom: &mut Rom) -> Result<()> {
        let path = rom.source_path().cloned().unwrap_or_default();
        let _start_address = rom.position();

        // --- Rune table for reference ---
        // rune '?' : conditional branch (0x20 + rel word)
        // rune '!' : exclamation branch (0x40 + rel word)
        // rune ' ' : JSR (unknown token, 0x60 + rel word)
        // rune '='/':'/';' : absolute word
        // rune '-' / '.' : absolute byte
        // rune '_' / ',' : relative byte (+ int8 range check)
        // (see uxnasm.c resolve() switch)
        match node {
            AstNode::ConditionalBlockStart(tok) => {
                // 1) new lambda id
                let id = self.lambda_counter;
                self.lambda_counter += 1;
                self.lambda_stack.push(id);

                // 2) its label name
                let name = format_lambda_label(id);

                // 3) record a reference at the first byte of the word (after opcode), rune '?'
                let ref_addr = rom.position() + 1; // <-- FIX: was rom.position()
                self.references.push(Reference {
                    name: name.clone(),
                    rune: '?',
                    address: ref_addr as u16,
                    line: tok.line,
                    path: String::new(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                // 4) emit JCN and 0xFFFF placeholder
                rom.write_byte(0x20)?;        // JCN
                rom.write_short(0xFFFF)?;     // placeholder for relative word
            }
            AstNode::ConditionalBlockEnd(tok) => {
                let id = match self.lambda_stack.pop() {
                    Some(id) => id,
                    None => {
                        return Err(AssemblerError::SyntaxError {
                            path: String::new(),
                            line: tok.line,
                            position: 0,
                            message: "Unmatched '}'".to_string(),
                            source_line: String::new(),
                        });
                    }
                };
                let name = format_lambda_label(id);

                // Define the label at current address WITHOUT changing scope/current label
                let addr = rom.position() as u16; // <-- Correct: no +1
                if self.symbols.contains_key(&name) {
                    return Err(AssemblerError::SyntaxError {
                        path: String::new(),
                        line: tok.line,
                        position: 0,
                        message: format!("Duplicate lambda label {}", name),
                        source_line: String::new(),
                    });
                }
                self.symbols.insert(name.clone(), Symbol {
                    address: addr,
                    is_sublabel: false,
                    parent_label: None
                });
            }
            AstNode::Padding(pad_addr) => {
                // If this is a |xxxx padding (not $xx skip), reset scope if at or above 0x0100
                if *pad_addr >= 0x0100 {
                    // Reset label scope after device header or |0100, like uxnasm
                    // But also allow sublabels to be defined at the start of a file (before any label)
                    if self.current_label.is_none() {
                        // Allow sublabels at the very start (e.g., device headers)
                        self.current_label = Some(String::new());
                    } else {
                        self.current_label = None;
                    }
                }
                rom.pad_to(*pad_addr)?;
            }
            AstNode::Byte(byte) => {
                rom.write_byte(*byte)?;
                if *byte != 0 {
                    self.update_effective_length(rom);
                }
            }
            AstNode::Short(short) => {
                rom.write_short(*short)?;
                if *short != 0 {
                    self.update_effective_length(rom);
                }
            }
            AstNode::LiteralByte(byte) => {
                // Only emit LIT for explicit byte literals (#xx)
                rom.write_byte(0x80)?; // LIT opcode (always non-zero)
                self.update_effective_length(rom);
                rom.write_byte(*byte)?;
                // Always update effective length for literal bytes, even if zero
                self.update_effective_length(rom);
            }
            AstNode::LiteralShort(short) => {
                // Only emit LIT2 for explicit short literals (#xxxx)
                rom.write_byte(0xa0)?; // LIT2 opcode (always non-zero)
                self.update_effective_length(rom);
                rom.write_short(*short)?;
                // Always update effective length for literal shorts, even if zero
                self.update_effective_length(rom);
            }
            AstNode::Instruction(inst) => {
                eprintln!(
                    "DEBUG: Processing instruction: '{}' at address {:04X}",
                    inst.opcode,
                    rom.position()
                );
                // Special-case BRK: always emit 0x00, matching uxnasm.c
                if inst.opcode.eq_ignore_ascii_case("BRK") {
                    rom.write_byte(0x00)?;
                    eprintln!(
                        "DEBUG: Wrote opcode 0x00 (BRK) at {:04X}",
                        rom.position() - 1
                    );
                    // Do not update effective_length for BRK (matches C)
                    return Ok(());
                }
                // Always emit a JSR reference for unknown instructions (not in opcode table)
                match self.opcodes.get_opcode(&inst.opcode) {
                    Ok(base_opcode) => {
                        let final_opcode = Opcodes::apply_modes(
                            base_opcode,
                            inst.short_mode,
                            inst.return_mode,
                            inst.keep_mode,
                        );
                        rom.write_byte(final_opcode)?;
                        eprintln!(
                            "DEBUG: Wrote opcode 0x{:02X} ({}) at {:04X}",
                            final_opcode,
                            inst.opcode,
                            rom.position() - 1
                        );
                        if final_opcode != 0 {
                            self.update_effective_length(rom);
                        }
                        // Only expand macro if found and handled as instruction
                        if let Some(macro_def) = self.macros.get(&inst.opcode).cloned() {
                            for macro_node in &macro_def.body {
                                self.process_node(macro_node, rom)?;
                            }
                        }
                    }
                    Err(_) => {
                        eprintln!(
                            "DEBUG: Creating JSR reference for unknown opcode: '{}'",
                            inst.opcode
                        );
                        self.references.push(Reference {
                            name: inst.opcode.clone(),
                            rune: ' ',
                            address: rom.position() + 1,
                            line: self.line_number,
                            path: path.clone(),
                            scope: self.current_label.clone(),
                            token: None,
                        });
                        rom.write_byte(0x60)?; // JSR opcode
                        eprintln!(
                            "DEBUG: Wrote JSR opcode 0x60 at {:04X}",
                            rom.position() - 1
                        );
                        self.update_effective_length(rom);
                        rom.write_short(0xffff)?; // Placeholder
                        eprintln!(
                            "DEBUG: Wrote JSR placeholder 0xFFFF at {:04X}-{:04X}",
                            rom.position() - 2,
                            rom.position() - 1
                        );
                        self.update_effective_length(rom);
                    }
                }
            }
                        AstNode::LabelRef(tok) => {
                // DEBUG: Log when a bare label reference is encountered
                println!(
                    "DEBUG: AstNode::LabelRef encountered at line {}, emitting JSR to label {:?} at address {:04X}",
                    tok.line,
                    tok.token,
                    rom.position()
                );
                // Always treat label references as JSR, never as BRK or nothing
                let label = if let crate::lexer::Token::LabelRef(s) = &tok.token {
                    s.clone()
                } else {
                    println!("DEBUG: Expected LabelRef, found {:?}", tok);
                    if let crate::lexer::Token::Newline = &tok.token {
                        // If it's a newline, just continue (ignore)
                        return Ok(());
                    }
                    return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: format!("Expected LabelRef, found {:?}", tok.token),
                        source_line: String::new(),
                    });
                };
                // FIX: Emit the reference at rom.position() + 1, not rom.position()
                self.references.push(Reference {
                    name: label,
                    rune: ' ',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                println!(
                    "DEBUG: Writing JSR opcode 0x60 and placeholder 0xFFFF for label {:?} at address {:04X}",
                    tok.token,
                    rom.position()
                );
                rom.write_byte(0x60)?; // JSR opcode for unknown token
                self.update_effective_length(rom);
                rom.write_short(0xffff)?; // Placeholder for relative address
                self.update_effective_length(rom);
            }
            AstNode::LabelDef(label) => {
                // NOTE: The label should be defined at the current ROM position,
                // which should be AFTER all code/data that precede it.
                // If this is the last label in the file, it should point to the address
                // after the last byte written (i.e., rom.position()).
                // If you emit the label before writing the last data, you may need to add 1.
                if !self.symbols.contains_key(label) {
                    let address = rom.position(); // <-- FIX: remove special case for "program"
                    self.symbols.insert(
                        label.clone(),
                        Symbol {
                            address,
                            is_sublabel: label.contains('/'),
                            parent_label: label.rsplitn(2, '/').nth(1).map(|s| s.to_string()),
                        },
                    );
                }
                self.current_label = Some(label.clone());
                eprintln!(
                    "DEBUG: Defined label '{}' at address {:04X}",
                    label,
                    rom.position()
                );
            }
            AstNode::SublabelDef(sublabel) => {
                // --- FIX: Always register sublabel as <main_label>/<sublabel> ---
                let full_name = if let Some(ref parent) = self.current_label {
                    // If current_label is empty or whitespace, treat as global sublabel (for device headers)
                    if parent.trim().is_empty() {
                        sublabel.clone()
                    } else {
                        // Use only the main label (before first '/')
                        let main_label = if let Some(slash) = parent.find('/') {
                            &parent[..slash]
                        } else {
                            parent.as_str()
                        };
                        format!("{}/{}", main_label, sublabel)
                    }
                } else {
                    // If no current_label, treat as global sublabel (for device headers)
                    sublabel.clone()
                };
                if !self.symbols.contains_key(&full_name) {
                    self.symbols.insert(
                        full_name.clone(),
                        Symbol {
                            address: rom.position(),
                            is_sublabel: true,
                            parent_label: if full_name.contains('/') {
                                Some(full_name[..full_name.rfind('/').unwrap()].to_string())
                            } else {
                                None
                            },
                        },
                    );
                }
                // Do NOT update current_label for sublabels (matches uxnasm setscope=0)
                eprintln!(
                    "DEBUG: Defined sublabel '{}' at address {:04X}",
                    full_name,
                    rom.position()
                );
            }
            AstNode::ExclamationRef(tok) => {
                // !label: opcode 0x40, rune '!', relative word placeholder (not JSR!)
                let label = match &tok.token {
                    crate::lexer::Token::ExclamationRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected ExclamationRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                let resolved_name = if label.starts_with('/') {
                    let clean_label = &label[1..];
                    if let Some(ref scope) = tok.scope {
                        let main_scope = if let Some(slash_pos) = scope.find('/') {
                            &scope[..slash_pos]
                        } else {
                            scope
                        };
                        format!("{}/{}", main_scope, clean_label)
                    } else {
                        clean_label.to_string()
                    }
                } else {
                    label
                };
                self.references.push(Reference {
                    name: resolved_name,
                    rune: '!',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x40)?; // !label: opcode 0x40 (not JSR)
                self.update_effective_length(rom);
                rom.write_short(0xffff)?; // relative word placeholder
                self.update_effective_length(rom);
            }

            AstNode::SublabelRef(tok) => {
                let sublabel = match &tok.token {
                    crate::lexer::Token::SublabelRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected SublabelRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                let full_name = if let Some(ref parent) = self.current_label {
                    format!("{}/{}", parent, sublabel)
                } else {
                    return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Sublabel reference outside of label scope".to_string(),
                        source_line: String::new(),
                    });
                };
                self.references.push(Reference {
                    name: full_name,
                    rune: '_',
                    address: rom.position(),
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0xff)?;
            }
            AstNode::RelativeRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::RelativeRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected RelativeRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '/',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x60)?;
                rom.write_short(0xffff)?;
            }
            AstNode::ConditionalRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::ConditionalRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected ConditionalRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '?',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x20)?;
                rom.write_short(0xffff)?;
            }
            AstNode::DotRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::DotRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected DotRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '.',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x80)?;
                self.update_effective_length(rom);
                rom.write_byte(0xff)?;
                self.update_effective_length(rom);
            }
            AstNode::SemicolonRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::SemicolonRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected SemicolonRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: ';',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0xa0)?;
                self.update_effective_length(rom);
                rom.write_short(0xffff)?;
                self.update_effective_length(rom);
            }
            AstNode::EqualsRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::EqualsRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected EqualsRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '=',
                    address: rom.position(),
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_short(0xffff)?;
                self.update_effective_length(rom);
            }
            AstNode::CommaRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::CommaRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected CommaRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: ',',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x80)?;
                self.update_effective_length(rom);
                rom.write_byte(0xff)?;
                self.update_effective_length(rom);
            }
            AstNode::UnderscoreRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::UnderscoreRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected UnderscoreRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '_',
                    address: rom.position(),
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0xff)?;
                self.update_effective_length(rom);
            }
            AstNode::QuestionRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::QuestionRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected QuestionRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '?',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x20)?;
                self.update_effective_length(rom);
                rom.write_short(0xffff)?;
                self.update_effective_length(rom);
            }
            AstNode::ExclamationRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::ExclamationRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected ExclamationRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                let resolved_name = if label.starts_with('/') {
                    let clean_label = &label[1..];
                    if let Some(ref scope) = tok.scope {
                        let main_scope = if let Some(slash_pos) = scope.find('/') {
                            &scope[..slash_pos]
                        } else {
                            scope
                        };
                        format!("{}/{}", main_scope, clean_label)
                    } else {
                        clean_label.to_string()
                    }
                } else {
                    label
                };
                self.references.push(Reference {
                    name: resolved_name,
                    rune: '!',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x40)?; // !label: opcode 0x40 (not JSR)
                self.update_effective_length(rom);
                rom.write_short(0xffff)?; // relative word placeholder
                self.update_effective_length(rom);
            }
            AstNode::RawAddressRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::RawAddressRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected RawAddressRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '=',
                    address: rom.position(),
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_short(0xffff)?;
            }
            AstNode::JSRRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::JSRRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected JSRRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '!',
                    address: rom.position() + 1,
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0x60)?;
                rom.write_short(0xffff)?;
            }
            AstNode::HyphenRef(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::HyphenRef(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected HyphenRef".to_string(),
                        source_line: String::new(),
                    }),
                };
                self.references.push(Reference {
                    name: label,
                    rune: '-',
                    address: rom.position(),
                    line: tok.line,
                    path: path.clone(),
                    scope: tok.scope.clone(),
                    token: Some(tok.clone()),
                });
                rom.write_byte(0xff)?;
            }
            AstNode::PaddingLabel(tok) => {
                let label = match &tok.token {
                    crate::lexer::Token::PaddingLabel(s) => s.clone(),
                    _ => return Err(AssemblerError::SyntaxError {
                        path: path.clone(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: "Expected PaddingLabel".to_string(),
                        source_line: String::new(),
                    }),
                };
                if let Some(symbol) = self.symbols.get(&label) {
                    rom.pad_to(symbol.address)?;
                } else {
                    return Err(AssemblerError::SyntaxError {
                        path: rom.source_path().cloned().unwrap_or_default(),
                        line: self.line_number,
                        position: self.position_in_line,
                        message: format!("Padding label '{}' not found", label),
                        source_line: rom
                            .source()
                            .map(|s| s.lines().nth(self.line_number).unwrap_or("").to_string())
                            .unwrap_or_default(),
                    });
                }
            }
            AstNode::Skip(count) => {
                for _ in 0..*count {
                    rom.write_byte(0)?;
                    // Don't update effective length for zero bytes
                }
            }
            AstNode::MacroDef(name, body) => {
                // Store macro definition
                self.macros.insert(
                    name.clone(),
                    Macro {
                        name: name.clone(),
                        body: body.clone(),
                    },
                );
            }
            AstNode::MacroCall(name, macro_line, macro_position) => {
                // Expand macro inline
                // If referencing '_', register <current_label>/_ as a sublabel if not already present
                if name == "_" {
                    if let Some(ref parent) = self.current_label {
                        let scoped = format!("{}/_", parent);
                        if !self.symbols.contains_key(&scoped) {
                            self.symbols.insert(
                                scoped.clone(),
                                Symbol {
                                    address: rom.position(),
                                    is_sublabel: true,
                                    parent_label: Some(parent.clone()),
                                },
                            );
                        }
                    }
                }
                if let Some(macro_def) = self.macros.get(name).cloned() {
                    for macro_node in &macro_def.body {
                        self.process_node(macro_node, rom)?;
                    }
                } else {
                    // If macro is not defined, treat as JSR reference (matches uxnasm for <pdec>)
                    self.references.push(Reference {
                        name: name.clone(),
                        rune: ' ',
                        address: rom.position() + 1,
                        line: self.line_number,
                        path: rom.source_path().cloned().unwrap_or_default(),
                        scope: self.current_label.clone(),
                        token: None,
                    });
                    rom.write_byte(0x60)?; // JSR opcode
                    self.update_effective_length(rom);
                    rom.write_short(0xffff)?; // Placeholder
                    self.update_effective_length(rom);
                }
            }
            AstNode::RawString(bytes) => {
                // Write string data byte by byte, updating effective length for each non-zero byte
                for &byte in bytes {
                    rom.write_byte(byte)?;
                    if byte != 0 {
                        self.update_effective_length(rom);
                    }
                }
            }
            AstNode::Include(path) => {
                // Save/restore current_label around includes
                let saved_label = self.current_label.clone();
                self.process_include(path, rom)?;
                self.current_label = saved_label;
            }
        }
        Ok(())
    }

    fn second_pass(&mut self, rom: &mut Rom) -> Result<()> {
        // Debug: print available symbols like WSL does
        if true { // Enable debug output
            println!("DEBUG: Available labels ({}):", self.symbols.len());
            let mut symbols: Vec<_> = self.symbols.iter().collect();
            symbols.sort_by_key(|(_, symbol)| symbol.address);
            for (i, (name, symbol)) in symbols.iter().enumerate() {
                println!("  [{}] '{}' -> 0x{:04X}", i, name, symbol.address);
            }
        }

        for reference in &self.references {
            // Handle '/' rune by resolving scope like uxnasm.c
            let resolved_name = if reference.rune == '/' {
                if let Some(ref scope) = reference.scope {
                    // Extract the main label part (before any '/')
                    let main_scope = if let Some(slash_pos) = scope.find('/') {
                        &scope[..slash_pos]
                    } else {
                        scope
                    };
                    // Preserve angle brackets and add scope - don't strip them
                    format!("{}/{}", main_scope, reference.name)
                } else {
                    reference.name.clone()
                }
            } else {
                reference.name.clone()
            };

            let symbol = self.find_symbol(&resolved_name, reference.scope.as_ref());
            println!("DEBUG: Processing reference: {:?}", reference);
            println!(
                "DEBUG: Resolving reference '{}' -> '{}' at {:04X} (scope: {:?})",
                reference.name, resolved_name, reference.address, reference.scope
            );
            println!("DEBUG: Found symbol: {:?}", symbol);

            // --- PATCH: skip error for instruction-like unresolved references ---
            let is_possible_instruction = {
                let mut base = resolved_name.as_str();
                while let Some(last) = base.chars().last() {
                    if last == 'k' || last == 'r' || last == '2' {
                        base = &base[..base.len() - 1];
                    } else {
                        break;
                    }
                }
                matches!(
                    base,
                    "ADD" | "SUB" | "MUL" | "DIV" | "AND" | "ORA" | "EOR" | "SFT"
                        | "LDZ" | "STZ" | "LDR" | "STR" | "LDA" | "STA" | "DEI" | "DEO"
                        | "INC" | "POP" | "NIP" | "SWP" | "ROT" | "DUP" | "OVR"
                        | "EQU" | "NEQ" | "GTH" | "LTH" | "JMP" | "JCN" | "JSR" | "STH"
                        | "BRK" | "LIT" | "LIT2" | "LITr" | "LIT2r"
                )
            };

            let symbol = if symbol.is_none() {
                if reference.rune == '_' || reference.rune == ',' {
                    // --- PATCH: uxnasm-style scope walk for _ and , runes, even if tokens don't store scope ---
                    // Try walking up the scope chain from the enclosing label scope
                    let mut found = None;
                    let mut scope = reference.scope.clone();
                    while let Some(ref s) = scope {
                        let candidate = format!("{}/{}", s, reference.name);
                        if let Some(sym) = self.symbols.get(&candidate) {
                            found = Some(sym);
                            break;
                        }
                        // Walk up to parent scope (remove last / segment)
                        if let Some(last_slash) = s.rfind('/') {
                            scope = Some(s[..last_slash].to_string());
                        } else {
                            scope = None;
                        }
                    }
                    // If not found, try just the name as a global label
                    if found.is_none() {
                        self.symbols.get(&reference.name)
                    } else {
                        found
                    }
                } else {
                    // For all other runes, only try the full name
                    self.symbols.get(&resolved_name)
                }
            } else {
                symbol
            };

            if symbol.is_none() {
                // If this is a reference for an instruction (not a label), skip error
                if reference.rune == ' ' && is_possible_instruction {
                    continue;
                }
                // Debug: print all available symbols when we can't find one
                eprintln!("Available symbols:");
                for (name, sym) in &self.symbols {
                    eprintln!("  {} -> {:04X}", name, sym.address);
                }
                eprintln!(
                    "Looking for: '{}' in scope: {:?}",
                    resolved_name, reference.scope
                );

                let source_line = rom
                    .source()
                    .and_then(|src| {
                        if reference.line > 0 {
                            src.lines().nth(reference.line - 1).map(|s| s.to_string())
                        } else {
                            None
                        }
                    })
                    .unwrap_or_default();

                let message = if is_possible_instruction {
                    format!(
                        "'{}' is not a label, but looks like an instruction. Did you mean to use it as an instruction?",
                        resolved_name
                    )
                } else {
                    format!("Label unknown: {}", resolved_name)
                };

                return Err(AssemblerError::SyntaxError {
                    path: reference.path.clone(),
                    line: reference.line,
                    position: 0,
                    message,
                    source_line,
                });
            }

            let symbol = symbol.unwrap();

            // PATCH: uxnasm's relative word calculation for '?' rune is: rel = l->addr - r->addr - 2
            // But the bug is here: for the '?' rune, uxnasm.c uses rel = l->addr - r->addr - 2,
            // but writes it as a signed 16-bit value, not as an unsigned.
            // The difference in your output is that you write rel as (symbol.address as i32 - reference.address as i32 - 2) as i16,
            // but uxnasm.c writes it as (symbol.address - reference.address - 2) as Sint16, then stores it as a little-endian word.

            match reference.rune {
                '_' | ',' => {
                    // case '_': case ',': *rom = rel = l->addr - r->addr - 2;
                    let rel = (symbol.address as i32 - reference.address as i32 - 2) as i8;
                    rom.write_byte_at(reference.address, rel as u8)?;
                    eprintln!("DEBUG: Resolved reference '{}' at {:04X}: wrote relative offset 0x{:02X} ({})", 
                             resolved_name, reference.address, rel as u8, rel);
                    // Update effective length if resolved value is non-zero
                    if rel as u8 != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 1);
                    }
                    // Range check like uxnasm.c: if((Sint8)data[r->addr] != rel)
                    if rel != (rel as u8 as i8) {
                        return Err(AssemblerError::SyntaxError {
                            path: reference.path.clone(),
                            line: reference.line,
                            position: 0,
                            message: "Reference too far".to_string(),
                            source_line: String::new(),
                        });
                    }
                }
                '-' | '.' => {
                    // case '-': case '.': *rom = l->addr;
                    rom.write_byte_at(reference.address, symbol.address as u8)?;
                    eprintln!(
                        "DEBUG: Resolved reference '{}' at {:04X}: wrote address 0x{:02X}",
                        reference.name, reference.address, symbol.address as u8
                    );
                    // Update effective length if resolved value is non-zero
                    if symbol.address as u8 != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 1);
                    }
                }
                ':' | '=' | ';' => {

                    //                     // Write absolute ROM address (uxnasm.c starts ROM at PAGE)
                    // let absolute_addr = symbol.address + 0x0100;
                    // rom.write_byte_at(reference.address, (absolute_addr >> 8) as u8)?;
                    // rom.write_byte_at(reference.address + 1, (absolute_addr & 0xff) as u8)?;
                    // eprintln!(
                    //     "DEBUG: Resolved reference '{}' at {:04X}: wrote address 0x{:04X} (absolute)",
                    //     reference.name, reference.address, absolute_addr
                    // );
                    // // Update effective length - address references are typically non-zero
                    // if absolute_addr != 0 {
                    //     self.effective_length =
                    //         self.effective_length.max(reference.address as usize + 2);
                    // }

                    // Write raw ROM address (no offset)
                    rom.write_byte_at(reference.address, (symbol.address >> 8) as u8)?;
                    rom.write_byte_at(reference.address + 1, (symbol.address & 0xff) as u8)?;
                    eprintln!(
                        "DEBUG: Resolved reference '{}' at {:04X}: wrote address 0x{:04X} (no offset)",
                        reference.name, reference.address, symbol.address
                    );
                    // Update effective length - address references are typically non-zero
                    if symbol.address != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 2);
                    }
                }
                '!' => {
                    // Fix: match uxnasm.c, use rel = target_addr - ref_addr - 2
                    let rel = (symbol.address as i32 - reference.address as i32 - 2) as i16;
                    // --- DEBUG PRINTS ---
                    println!(
                        "DEBUG: [second_pass] '!' rune: symbol.address=0x{:04X}, reference.address=0x{:04X}, rel={}(0x{:04X})",
                        symbol.address, reference.address, rel, rel as u16
                    );
                    // Write high byte first (matches uxnasm)
                    rom.write_short_at(reference.address, rel as u16)?;
                    eprintln!(
                        "DEBUG: Resolved reference '{}' at {:04X}: wrote relative address 0x{:04X} ({})",
                        reference.name, reference.address, rel as u16, rel
                    );
                    if rel != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 2);
                    }
                }
                '?' => {
                    // PATCH: uxnasm.c writes rel = l->addr - r->addr - 2 as a signed 16-bit value, little-endian
                    let rel = (symbol.address as i32 - reference.address as i32 - 2) as i16;
                    rom.write_short_at(reference.address, rel as u16)?;
                    // rom.write_byte_at(reference.address, (rel & 0xff) as u8)?;
                    // rom.write_byte_at(reference.address + 1, ((rel >> 8) & 0xff) as u8)?;
                    eprintln!(
                        "DEBUG: Resolved reference '{}' at {:04X}: wrote relative address 0x{:04X} ({})",
                        reference.name, reference.address, rel as u16, rel
                    );
                    if rel != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 2);
                    }
                }
                ' ' | '/' => {
                    // For conditional ('?'), space (' '), and slash ('/') runes:
                    // rel = target_addr - ref_addr - 2 (matches uxnasm for relative word references)
                    let rel = (symbol.address as i32 - reference.address as i32 - 2) as i16;
                    // --- DEBUG PRINTS ---
                    println!(
                        "DEBUG: [second_pass] '{}': symbol.address=0x{:04X}, reference.address=0x{:04X}, rel={}(0x{:04X})",
                        reference.rune, symbol.address, reference.address, rel, rel as u16
                    );
                    // Write as little-endian (low byte first)
                                      rom.write_short_at(reference.address, rel as u16)?;
                    // rom.write_byte_at(reference.address, (rel & 0xff) as u8)?;
                    // rom.write_byte_at(reference.address + 1, ((rel >> 8) & 0xff) as u8)?;
                    eprintln!("DEBUG: Resolved reference '{}' at {:04X}: wrote relative address 0x{:04X} ({})", 
                             reference.name, reference.address, rel as u16, rel);
                    if rel != 0 {
                        self.effective_length =
                            self.effective_length.max(reference.address as usize + 2);
                    }
                }
                _ => {
                    return Err(AssemblerError::SyntaxError {
                        path: reference.path.clone(),
                        line: reference.line,
                        position: 0,
                        message: format!("Unknown reference rune: {}", reference.rune),
                        source_line: String::new(),
                    });
                }
            }
        }
        Ok(())
    }

    fn find_symbol(&self, name: &str, reference_scope: Option<&String>) -> Option<&Symbol> {
        eprintln!(
            "DEBUG: find_symbol called with name='{}', reference_scope={:?}",
            name, reference_scope
        );
        eprintln!("DEBUG: current_label={:?}", self.current_label);

        // Handle sublabel references with & prefix
        if name.starts_with('&') {
            let sublabel_name = &name[1..];
            eprintln!("DEBUG: Looking for sublabel '{}'", sublabel_name);

            // First try with the reference's scope context
            if let Some(scope) = reference_scope {
                // Extract the main label part (before any '/')
                let main_scope = if let Some(slash_pos) = scope.find('/') {
                    &scope[..slash_pos]
                } else {
                    scope
                };
                let scoped = format!("{}/{}", main_scope, sublabel_name);
                eprintln!("DEBUG: Trying main scope lookup: '{}'", scoped);
                if let Some(symbol) = self.symbols.get(&scoped) {
                    eprintln!("DEBUG: Found main scope symbol: {:?}", symbol);
                    return Some(symbol);
                }
            }

            // Fallback to current label scope
            if let Some(ref current) = self.current_label {
                // Extract the main label part (before any '/')
                let main_current = if let Some(slash_pos) = current.find('/') {
                    &current[..slash_pos]
                } else {
                    current
                };
                let scoped = format!("{}/{}", main_current, sublabel_name);
                eprintln!("DEBUG: Trying current main scope lookup: '{}'", scoped);
                if let Some(symbol) = self.symbols.get(&scoped) {
                    eprintln!("DEBUG: Found current main scope symbol: {:?}", symbol);
                    return Some(symbol);
                }
            }

            // Try global scope (just the sublabel name without &)
            eprintln!("DEBUG: Trying global lookup: '{}'", sublabel_name);
            if let Some(symbol) = self.symbols.get(sublabel_name) {
                eprintln!("DEBUG: Found global symbol: {:?}", symbol);
                return Some(symbol);
            }
        }

        // --- FIX: Only walk up the scope chain for _ and , runes ---
        // This matches uxnasm's scope resolution for sublabels.
        // We need to know the rune type, so this logic should only be used for those runes.
        // Instead, move the scope-walk logic out of find_symbol and only use it in second_pass for _ and , runes.
        // Here, just do direct lookup.
        if let Some(symbol) = self.symbols.get(name) {
            return Some(symbol);
        }

        // Try with angle brackets for hierarchical lookups
        if !name.starts_with('<') && !name.ends_with('>') {
            let bracketed = format!("<{}>", name);
            if let Some(symbol) = self.symbols.get(&bracketed) {
                return Some(symbol);
            }
        }

        if name.starts_with('<') && name.ends_with('>') && name.len() > 2 {
            let unbracketed = &name[1..name.len() - 1];
            if let Some(symbol) = self.symbols.get(unbracketed) {
                return Some(symbol);
            }
        }

        None
    }

    /// Process an include directive by reading and assembling the included file
    fn process_include(&mut self, path: &str, rom: &mut Rom) -> Result<()> {
        // Read the included file
        let content = match fs::read_to_string(path) {
            Ok(content) => content,
            Err(e) => {
                return Err(AssemblerError::SyntaxError {
                    path: rom.source_path().cloned().unwrap_or_default(),
                    line: self.line_number,
                    position: self.position_in_line,
                    message: format!("Failed to read include file '{}': {}", path, e),
                    source_line: String::new(),
                });
            }
        };

        // Scan the included file for device headers and merge into device_map
        for line in content.lines() {
            let line = line.trim();
            if line.starts_with('|') {
                let mut parts = line.split_whitespace();
                let addr_part = parts.next();
                let label_part = parts.next();
                if let (Some(addr), Some(label)) = (addr_part, label_part) {
                    if label.starts_with('@') {
                        let mut device = label[1..].to_string();
                        if let Some(slash_pos) = device.find('/') {
                            device = device[..slash_pos].to_string();
                        }
                        let base_addr = u16::from_str_radix(&addr[1..], 16).unwrap_or(0);
                        let mut offset = 0u16;
                        let mut iter = parts;
                        // Register the device label itself
                        if !self.symbols.contains_key(&device) {
                            self.symbols.insert(
                                device.clone(),
                                Symbol {
                                    address: base_addr,
                                    is_sublabel: false,
                                    parent_label: None,
                                },
                            );
                        }
                        // Register each field as a sublabel with correct offset
                        while let Some(field_name) = iter.next() {
                            let size_str = iter.next();
                            let size = if let Some(size_str) = size_str {
                                if let Ok(sz) = size_str.parse::<u16>() {
                                    sz
                                } else {
                                    1
                                }
                            } else {
                                1
                            };
                            let sublabel = format!("{}/{}", device, field_name);
                            if !self.symbols.contains_key(&sublabel) {
                                self.symbols.insert(
                                    sublabel.clone(),
                                    Symbol {
                                        address: base_addr + offset,
                                        is_sublabel: true,
                                        parent_label: Some(device.clone()),
                                    },
                                );
                            }
                            offset += size;
                        }
                    }
                }
            }
        }

        // Lex the included file
        let mut lexer = Lexer::new(content.clone(), Some(path.to_string()));
        let tokens = lexer.tokenize()?;

        // Parse the included file
        let mut parser = Parser::new_with_source(tokens, path.to_string(), content);
        let ast = parser.parse()?;

        // Set the ROM path to the included file path for error context
        rom.set_path(Some(path.to_string()));

        // Process the included AST nodes in first pass
        for node in ast {
            self.process_node(&node, rom)?;
        }

        Ok(())
    }
}

// Helper to format lambda label (e.g., λ00, λ01, ...)
fn format_lambda_label(lambda_id: usize) -> String {
    format!("λ{:02x}", lambda_id)
}

impl Default for Assembler {
    fn default() -> Self {
        Self::new()

    }
}