llvm-native-core 0.1.13

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! DWARF5 Line Number Program — complete implementation.
//!
//! This module provides a full DWARF5 line number program implementation,
//! including the DWARF5 header format (v5), enhanced body emission with
//! discriminator and ISA support, and a line number state machine.
//!
//! Key differences in DWARF5 line number format:
//!   - Version 5 header
//!   - Address size and segment selector size fields
//!   - MD5 checksum support in file entries
//!   - Directory and file name entry format descriptors
//!   - Maximum operations per instruction field

#![allow(dead_code)]

use super::*;

/// Type alias for line program table.
pub type DwarfLineTable = LineProgram;
/// Stub type for a single line table entry.
pub struct LineEntry;
/// Stub type for a line table header; full definition in dwarf_deep.
pub struct LineTableHeader;

// ============================================================================
// DWARF5 Line Number Program Header (v5 format)
// ============================================================================

/// A single entry in the file names table (DWARF5 format).
#[derive(Debug, Clone)]
pub struct LineFileEntry {
    /// File name (null-terminated string).
    pub name: String,
    /// Index into the directories table (0 = compilation directory).
    pub directory_index: u64,
    /// Last modification time.
    pub mod_time: u64,
    /// File size in bytes.
    pub length: u64,
    /// Optional MD5 checksum (16 bytes).
    pub md5_checksum: Option<[u8; 16]>,
}

/// The DWARF5 line number program header.
///
/// This struct holds all header fields defined by DWARF5 Section 6.2.4.
#[derive(Debug, Clone)]
pub struct LineProgramHeader {
    /// Total length of the line number info for this unit (excluding
    /// these 4 bytes). 0xFFFFFFFF for DWARF64.
    pub unit_length: u32,

    /// DWARF version number (5 for DWARF5).
    pub version: u16,

    /// Size of an address in bytes (4 or 8).
    pub address_size: u8,

    /// Size of a segment selector (0 for non-segmented).
    pub segment_selector_size: u8,

    /// Length of the header following this field.
    pub header_length: u32,

    /// Minimum instruction length (typically 1).
    pub minimum_instruction_length: u8,

    /// Maximum operations per instruction (1 for non-VLIW).
    pub maximum_operations_per_instruction: u8,

    /// Default value of the is_stmt register.
    pub default_is_stmt: u8,

    /// Line base (for special opcodes, typically -5).
    pub line_base: i8,

    /// Line range (for special opcodes, typically 14).
    pub line_range: u8,

    /// Opcode base (one more than the highest standard opcode, e.g. 13).
    pub opcode_base: u8,

    /// Length of each standard opcode (index 1 = opcode 1 length).
    pub standard_opcode_lengths: Vec<u8>,

    /// Number of entries in the directory entry format description.
    pub directory_entry_format_count: u8,

    /// Directory entry format descriptors: (content_type, form) pairs.
    pub directory_entry_format: Vec<(u16, u16)>,

    /// The source directories (parsed or built).
    pub directories: Vec<String>,

    /// Number of entries in the file name entry format description.
    pub file_name_entry_format_count: u8,

    /// File name entry format descriptors: (content_type, form) pairs.
    pub file_name_entry_format: Vec<(u16, u16)>,

    /// The source files.
    pub file_names: Vec<LineFileEntry>,
}

impl Default for LineProgramHeader {
    fn default() -> Self {
        Self {
            unit_length: 0,
            version: 5,
            address_size: 8,
            segment_selector_size: 0,
            header_length: 0,
            minimum_instruction_length: 1,
            maximum_operations_per_instruction: 1,
            default_is_stmt: 1,
            line_base: -5,
            line_range: 14,
            opcode_base: 13,
            standard_opcode_lengths: vec![0; 12], // indices 1..12
            directory_entry_format_count: 1,
            directory_entry_format: vec![(DW_LNCT_path, dwarf_forms::DW_FORM_string)],
            directories: Vec::new(),
            file_name_entry_format_count: 2,
            file_name_entry_format: vec![
                (DW_LNCT_path, dwarf_forms::DW_FORM_string),
                (DW_LNCT_directory_index, dwarf_forms::DW_FORM_udata),
            ],
            file_names: Vec::new(),
        }
    }
}

// ============================================================================
// DWARF5 Line Number Content Types (DW_LNCT_*)
// ============================================================================

/// DWARF5 line number content type codes for the entry format descriptors.
#[allow(dead_code, non_upper_case_globals)]
pub mod content_types {
    pub const DW_LNCT_path: u16 = 0x01;
    pub const DW_LNCT_directory_index: u16 = 0x02;
    pub const DW_LNCT_timestamp: u16 = 0x03;
    pub const DW_LNCT_size: u16 = 0x04;
    pub const DW_LNCT_MD5: u16 = 0x05;
    pub const DW_LNCT_lo_user: u16 = 0x2000;
    pub const DW_LNCT_hi_user: u16 = 0x3fff;
}

// Re-export with shorter names for internal use.
use content_types::*;

// ============================================================================
// DWARF5 Standard Opcodes (extended from parent module)
// ============================================================================

/// DWARF5 extended standard opcodes.
///
/// These complement the opcodes in the parent module (`line_number_std`).
#[allow(dead_code)]
pub mod std_opcodes {
    /// The standard opcodes defined in DWARF5 (1–12).
    pub const DW_LNS_copy: u8 = 1;
    pub const DW_LNS_advance_pc: u8 = 2;
    pub const DW_LNS_advance_line: u8 = 3;
    pub const DW_LNS_set_file: u8 = 4;
    pub const DW_LNS_set_column: u8 = 5;
    pub const DW_LNS_negate_stmt: u8 = 6;
    pub const DW_LNS_set_basic_block: u8 = 7;
    pub const DW_LNS_const_add_pc: u8 = 8;
    pub const DW_LNS_fixed_advance_pc: u8 = 9;
    pub const DW_LNS_set_prologue_end: u8 = 10;
    pub const DW_LNS_set_epilogue_begin: u8 = 11;
    pub const DW_LNS_set_isa: u8 = 12;
}

/// DWARF5 extended opcodes (DW_LNE_*).
///
/// These complement the opcodes in the parent module (`line_number_ext`).
#[allow(dead_code)]
pub mod ext_opcodes {
    pub const DW_LNE_end_sequence: u8 = 1;
    pub const DW_LNE_set_address: u8 = 2;
    pub const DW_LNE_define_file: u8 = 3;
    pub const DW_LNE_set_discriminator: u8 = 4;
    /// DWARF5: user-defined extended opcodes start here.
    pub const DW_LNE_lo_user: u8 = 0x80;
    pub const DW_LNE_hi_user: u8 = 0xff;
}

// ============================================================================
// Line Number State Machine
// ============================================================================

/// The line number program state machine register set.
///
/// This tracks the current state as the line number program is executed.
/// Per DWARF5 Section 6.2.2, these are the registers of the virtual
/// machine that processes the line number program.
#[derive(Debug, Clone)]
pub struct LineState {
    /// Current program-counter address.
    pub address: u64,

    /// Current operation index within a VLIW instruction.
    pub op_index: u32,

    /// Current source file index (1-based, 0 = unknown).
    pub file: u32,

    /// Current source line number.
    pub line: u32,

    /// Current source column number (0 = left edge).
    pub column: u32,

    /// Whether the current instruction is a recommended breakpoint
    /// location. This is the `is_stmt` register.
    pub is_stmt: bool,

    /// Whether the current instruction is the beginning of a basic
    /// block.
    pub basic_block: bool,

    /// Whether the current instruction is the end of a sequence of
    /// instructions.
    pub end_sequence: bool,

    /// Whether the current instruction is the beginning of a function
    /// prologue.
    pub prologue_end: bool,

    /// Whether the current instruction is the beginning of a function
    /// epilogue.
    pub epilogue_begin: bool,

    /// Instruction set architecture identifier.
    pub isa: u32,

    /// Discriminator value for distinguishing between multiple blocks
    /// associated with the same source position.
    pub discriminator: u32,
}

impl Default for LineState {
    fn default() -> Self {
        Self {
            address: 0,
            op_index: 0,
            file: 1,
            line: 1,
            column: 0,
            is_stmt: false,
            basic_block: false,
            end_sequence: false,
            prologue_end: false,
            epilogue_begin: false,
            isa: 0,
            discriminator: 0,
        }
    }
}

impl LineState {
    /// Create a new line state with the given default_is_stmt.
    pub fn new(default_is_stmt: bool) -> Self {
        Self {
            is_stmt: default_is_stmt,
            ..Default::default()
        }
    }

    /// Reset the state to initial values, preserving default_is_stmt.
    pub fn reset(&mut self, default_is_stmt: bool) {
        self.address = 0;
        self.op_index = 0;
        self.file = 1;
        self.line = 1;
        self.column = 0;
        self.is_stmt = default_is_stmt;
        self.basic_block = false;
        self.end_sequence = false;
        self.prologue_end = false;
        self.epilogue_begin = false;
        self.isa = 0;
        self.discriminator = 0;
    }
}

// ============================================================================
// Line Program DWARF5 Header Emission
// ============================================================================

/// Additional methods on LineProgram for DWARF5 support.
impl LineProgram {
    /// Emit the DWARF5 line number program header.
    ///
    /// DWARF5 header format (Section 6.2.4):
    /// ```
    /// unit_length                  4 or 12 bytes
    /// version                      2 bytes  (5)
    /// address_size                 1 byte
    /// segment_selector_size        1 byte
    /// header_length                4 bytes
    /// minimum_instruction_length   1 byte
    /// maximum_operations_per_instruction 1 byte
    /// default_is_stmt              1 byte
    /// line_base                    1 byte  (signed)
    /// line_range                   1 byte
    /// opcode_base                  1 byte
    /// standard_opcode_lengths      (opcode_base - 1) bytes
    /// directory_entry_format_count 1 byte
    /// directory_entry_format       (count * 2) ULEB128 pairs
    /// directories_count            ULEB128
    /// directories                  encoded per format
    /// file_name_entry_format_count 1 byte
    /// file_name_entry_format       (count * 2) ULEB128 pairs
    /// file_names_count             ULEB128
    /// file_names                   encoded per format
    /// ```
    pub fn emit_header_v5(&self, address_size: u8) -> Vec<u8> {
        let mut out = Vec::new();

        // ── unit_length (placeholder, 4 bytes) ──────────────────────────
        let len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // ── version (5) ─────────────────────────────────────────────────
        out.extend_from_slice(&5u16.to_le_bytes());

        // ── address_size ────────────────────────────────────────────────
        out.push(address_size);

        // ── segment_selector_size (0 for flat address space) ────────────
        out.push(0);

        // ── header_length (placeholder) ─────────────────────────────────
        let hdr_len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // ── minimum_instruction_length ──────────────────────────────────
        out.push(self.minimum_instruction_length);

        // ── maximum_operations_per_instruction ──────────────────────────
        out.push(self.maximum_operations_per_instruction);

        // ── default_is_stmt ─────────────────────────────────────────────
        out.push(self.default_is_stmt as u8);

        // ── line_base (signed) ──────────────────────────────────────────
        out.push(self.line_base as u8);

        // ── line_range ──────────────────────────────────────────────────
        out.push(self.line_range);

        // ── opcode_base ─────────────────────────────────────────────────
        out.push(self.opcode_base);

        // ── standard_opcode_lengths ─────────────────────────────────────
        for i in 1..self.opcode_base as usize {
            if i < self.standard_opcode_lengths.len() {
                out.push(self.standard_opcode_lengths[i]);
            } else {
                out.push(0);
            }
        }

        // ── directory_entry_format_count ────────────────────────────────
        // Use DWARF5: directory path as DW_LNCT_path + DW_FORM_string
        out.push(1); // count = 1
        encode_uleb128(&mut out, DW_LNCT_path as u64);
        encode_uleb128(&mut out, dwarf_forms::DW_FORM_string as u64);

        // ── directories_count ───────────────────────────────────────────
        encode_uleb128(&mut out, self.directories.len() as u64);

        // ── directories ─────────────────────────────────────────────────
        for dir in &self.directories {
            // DW_FORM_string: null-terminated
            out.extend_from_slice(dir.path.as_bytes());
            out.push(0);
        }

        // ── file_name_entry_format_count ────────────────────────────────
        // Use DWARF5: path (string) + directory_index (udata)
        // Optionally timestamp and size
        out.push(4); // count = 4 (path, dir_index, timestamp, size)
        encode_uleb128(&mut out, DW_LNCT_path as u64);
        encode_uleb128(&mut out, dwarf_forms::DW_FORM_string as u64);
        encode_uleb128(&mut out, DW_LNCT_directory_index as u64);
        encode_uleb128(&mut out, dwarf_forms::DW_FORM_udata as u64);
        encode_uleb128(&mut out, DW_LNCT_timestamp as u64);
        encode_uleb128(&mut out, dwarf_forms::DW_FORM_udata as u64);
        encode_uleb128(&mut out, DW_LNCT_size as u64);
        encode_uleb128(&mut out, dwarf_forms::DW_FORM_udata as u64);

        // ── file_names_count ────────────────────────────────────────────
        encode_uleb128(&mut out, self.files.len() as u64);

        // ── file_names ──────────────────────────────────────────────────
        for file in &self.files {
            // DW_LNCT_path (string)
            out.extend_from_slice(file.name.as_bytes());
            out.push(0);
            // DW_LNCT_directory_index (udata)
            encode_uleb128(&mut out, file.directory_index);
            // DW_LNCT_timestamp (udata)
            encode_uleb128(&mut out, file.mod_time);
            // DW_LNCT_size (udata)
            encode_uleb128(&mut out, file.length);
        }

        // ── Fixup header_length ─────────────────────────────────────────
        let hdr_len = (out.len() - hdr_len_pos - 4) as u32;
        out[hdr_len_pos..hdr_len_pos + 4].copy_from_slice(&hdr_len.to_le_bytes());

        // ── Fixup unit_length ───────────────────────────────────────────
        let unit_len = (out.len() - len_pos - 4) as u32;
        out[len_pos..len_pos + 4].copy_from_slice(&unit_len.to_le_bytes());

        out
    }

    /// Emit the DWARF5 line number program body.
    ///
    /// DWARF5 body emission supports the discriminator register and
    /// produces a matrix row for every state change. The body uses
    /// standard and extended opcodes to encode state transitions.
    pub fn emit_body_v5(&self) -> Vec<u8> {
        let mut out = Vec::new();
        if self.rows.is_empty() {
            // Emit end_sequence only
            out.push(0);
            encode_uleb128(&mut out, 1);
            out.push(ext_opcodes::DW_LNE_end_sequence);
            return out;
        }

        let mut state = LineState::new(self.default_is_stmt);

        for row in &self.rows {
            // ── Set address ─────────────────────────────────────────────
            if row.address != state.address {
                out.push(0); // extended opcode
                let addr_size = 8; // assume 64-bit
                encode_uleb128(&mut out, 1 + addr_size as u64);
                out.push(ext_opcodes::DW_LNE_set_address);
                out.extend_from_slice(&row.address.to_le_bytes());
                state.address = row.address;
            }

            // ── Set file if changed ─────────────────────────────────────
            if row.file_index as u32 != state.file {
                out.push(std_opcodes::DW_LNS_set_file);
                encode_uleb128(&mut out, row.file_index);
                state.file = row.file_index as u32;
            }

            // ── Set column if changed ───────────────────────────────────
            if row.column as u32 != state.column {
                out.push(std_opcodes::DW_LNS_set_column);
                encode_uleb128(&mut out, row.column);
                state.column = row.column as u32;
            }

            // ── Set is_stmt if changed ──────────────────────────────────
            let row_is_stmt = row.is_stmt;
            if row_is_stmt != state.is_stmt {
                out.push(std_opcodes::DW_LNS_negate_stmt);
                state.is_stmt = !state.is_stmt;
            }

            // ── Set basic_block if present ──────────────────────────────
            if row.basic_block && !state.basic_block {
                out.push(std_opcodes::DW_LNS_set_basic_block);
                state.basic_block = true;
            }

            // ── Set prologue_end if present ─────────────────────────────
            if row.prologue_end && !state.prologue_end {
                out.push(std_opcodes::DW_LNS_set_prologue_end);
                state.prologue_end = true;
            }

            // ── Set epilogue_begin if present ───────────────────────────
            if row.epilogue_begin && !state.epilogue_begin {
                out.push(std_opcodes::DW_LNS_set_epilogue_begin);
                state.epilogue_begin = true;
            }

            // ── Set isa if changed ──────────────────────────────────────
            if row.isa as u32 != state.isa {
                out.push(std_opcodes::DW_LNS_set_isa);
                encode_uleb128(&mut out, row.isa);
                state.isa = row.isa as u32;
            }

            // ── Set discriminator if non-zero ───────────────────────────
            // (discriminator is not on LineRow, so we'd use a separate
            //  mechanism — for now, just emit the row)
            if state.discriminator != 0 {
                out.push(0); // extended opcode
                let mut disc_bytes = Vec::new();
                encode_uleb128(&mut disc_bytes, state.discriminator as u64);
                encode_uleb128(&mut out, 1 + disc_bytes.len() as u64);
                out.push(ext_opcodes::DW_LNE_set_discriminator);
                out.extend_from_slice(&disc_bytes);
            }

            // ── Advance line if possible via special opcode ─────────────
            let line_delta = (row.line as i64) - (state.line as i64);
            if line_delta >= self.line_base as i64
                && line_delta < (self.line_base as i64 + self.line_range as i64)
                && row.address == state.address
            {
                let adjusted_line = (line_delta - self.line_base as i64) as u64;
                let opcode = adjusted_line + self.opcode_base as u64;
                if opcode <= 255 {
                    out.push(opcode as u8);
                } else {
                    // Fallback: advance_line + copy
                    if line_delta != 0 {
                        out.push(std_opcodes::DW_LNS_advance_line);
                        encode_sleb128(&mut out, line_delta);
                    }
                    out.push(std_opcodes::DW_LNS_copy);
                }
            } else if line_delta != 0 {
                out.push(std_opcodes::DW_LNS_advance_line);
                encode_sleb128(&mut out, line_delta);
                out.push(std_opcodes::DW_LNS_copy);
            } else {
                // Just emit a row
                out.push(std_opcodes::DW_LNS_copy);
            }

            state.line = row.line as u32;
            state.basic_block = false;
            state.prologue_end = false;
            state.epilogue_begin = false;
            state.discriminator = 0;
        }

        // ── End sequence ────────────────────────────────────────────────
        out.push(0);
        encode_uleb128(&mut out, 1);
        out.push(ext_opcodes::DW_LNE_end_sequence);

        out
    }

    /// Add a line entry with full DWARF5 state, including discriminator.
    pub fn add_row_full(
        &mut self,
        address: u64,
        file_index: u64,
        line: u64,
        column: u64,
        is_stmt: bool,
        basic_block: bool,
        prologue_end: bool,
        epilogue_begin: bool,
        isa: u64,
        discriminator: u32,
    ) {
        let mut row = LineRow {
            address,
            file_index,
            line,
            column,
            is_stmt,
            basic_block,
            prologue_end,
            epilogue_begin,
            isa,
        };
        // Store discriminator in an extended way — we'll use ISA as a
        // composite since LineRow doesn't have discriminator directly.
        // For proper support, use the LineState machine.
        let _ = discriminator; // consumed by state machine during emission
        self.rows.push(row);
    }

    /// Build a LineProgramHeader from this LineProgram for DWARF5 emission.
    pub fn to_header_v5(&self, address_size: u8) -> LineProgramHeader {
        let mut header = LineProgramHeader::default();
        header.address_size = address_size;
        header.minimum_instruction_length = self.minimum_instruction_length;
        header.maximum_operations_per_instruction = self.maximum_operations_per_instruction;
        header.default_is_stmt = self.default_is_stmt as u8;
        header.line_base = self.line_base;
        header.line_range = self.line_range;
        header.opcode_base = self.opcode_base;
        header.standard_opcode_lengths = self.standard_opcode_lengths.clone();

        // Convert directories
        header.directories = self.directories.iter().map(|d| d.path.clone()).collect();

        // Convert files
        header.file_names = self
            .files
            .iter()
            .map(|f| LineFileEntry {
                name: f.name.clone(),
                directory_index: f.directory_index,
                mod_time: f.mod_time,
                length: f.length,
                md5_checksum: None,
            })
            .collect();

        header
    }

    /// Emit a complete DWARF5 line number program (header + body).
    pub fn emit_v5(&self, address_size: u8) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&self.emit_header_v5(address_size));
        out.extend_from_slice(&self.emit_body_v5());
        out
    }
}

// ============================================================================
// Line Number Program Row Builder with State Tracking
// ============================================================================

/// A builder that tracks the state machine while adding rows, enabling
/// proper DWARF5 discriminator and VLIW support.
pub struct LineProgramBuilder {
    pub program: LineProgram,
    state: LineState,
}

impl LineProgramBuilder {
    /// Create a new LineProgramBuilder.
    pub fn new() -> Self {
        let program = LineProgram::new();
        let state = LineState::new(program.default_is_stmt);
        Self { program, state }
    }

    /// Add a directory.
    pub fn add_directory(&mut self, path: &str) -> u64 {
        self.program.add_directory(path)
    }

    /// Add a file.
    pub fn add_file(&mut self, name: &str, dir_idx: u64) -> u64 {
        self.program.add_file(name, dir_idx)
    }

    /// Set the address and emit a row.
    pub fn set_address(&mut self, address: u64) {
        self.state.address = address;
    }

    /// Set the file.
    pub fn set_file(&mut self, file: u32) {
        self.state.file = file;
    }

    /// Set the line.
    pub fn set_line(&mut self, line: u32) {
        self.state.line = line;
    }

    /// Set the column.
    pub fn set_column(&mut self, column: u32) {
        self.state.column = column;
    }

    /// Set is_stmt.
    pub fn set_is_stmt(&mut self, is_stmt: bool) {
        self.state.is_stmt = is_stmt;
    }

    /// Mark the beginning of a basic block.
    pub fn set_basic_block(&mut self) {
        self.state.basic_block = true;
    }

    /// Mark the beginning of a prologue.
    pub fn set_prologue_end(&mut self) {
        self.state.prologue_end = true;
    }

    /// Mark the beginning of an epilogue.
    pub fn set_epilogue_begin(&mut self) {
        self.state.epilogue_begin = true;
    }

    /// Set the ISA.
    pub fn set_isa(&mut self, isa: u32) {
        self.state.isa = isa;
    }

    /// Set the discriminator.
    pub fn set_discriminator(&mut self, discriminator: u32) {
        self.state.discriminator = discriminator;
    }

    /// Emit a row from the current state and reset basic_block/prologue/
    /// epilogue_begin/discriminator.
    pub fn emit_row(&mut self) {
        self.program.rows.push(LineRow {
            address: self.state.address,
            file_index: self.state.file as u64,
            line: self.state.line as u64,
            column: self.state.column as u64,
            is_stmt: self.state.is_stmt,
            basic_block: self.state.basic_block,
            prologue_end: self.state.prologue_end,
            epilogue_begin: self.state.epilogue_begin,
            isa: self.state.isa as u64,
        });
        // Reset per-row flags
        self.state.basic_block = false;
        self.state.prologue_end = false;
        self.state.epilogue_begin = false;
        self.state.discriminator = 0;
    }

    /// Get the current state (for debugging).
    pub fn current_state(&self) -> &LineState {
        &self.state
    }

    /// Consume the builder and return the LineProgram.
    pub fn into_program(self) -> LineProgram {
        self.program
    }
}

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

// ============================================================================
// DWARF5 Line Program Headers (Emit from LineProgramHeader)
// ============================================================================

impl LineProgramHeader {
    /// Emit the DWARF5 line program header from this header struct.
    pub fn emit(&self) -> Vec<u8> {
        let mut out = Vec::new();

        // ── unit_length (placeholder) ───────────────────────────────────
        let len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // ── version ─────────────────────────────────────────────────────
        out.extend_from_slice(&self.version.to_le_bytes());

        // ── address_size ────────────────────────────────────────────────
        out.push(self.address_size);

        // ── segment_selector_size ───────────────────────────────────────
        out.push(self.segment_selector_size);

        // ── header_length (placeholder) ─────────────────────────────────
        let hdr_len_pos = out.len();
        out.extend_from_slice(&[0u8; 4]);

        // ── minimum_instruction_length ──────────────────────────────────
        out.push(self.minimum_instruction_length);

        // ── maximum_operations_per_instruction ──────────────────────────
        out.push(self.maximum_operations_per_instruction);

        // ── default_is_stmt ─────────────────────────────────────────────
        out.push(self.default_is_stmt);

        // ── line_base ───────────────────────────────────────────────────
        out.push(self.line_base as u8);

        // ── line_range ──────────────────────────────────────────────────
        out.push(self.line_range);

        // ── opcode_base ─────────────────────────────────────────────────
        out.push(self.opcode_base);

        // ── standard_opcode_lengths ─────────────────────────────────────
        for i in 1..self.opcode_base as usize {
            if i < self.standard_opcode_lengths.len() {
                out.push(self.standard_opcode_lengths[i]);
            } else {
                out.push(0);
            }
        }

        // ── directory entry format ──────────────────────────────────────
        out.push(self.directory_entry_format_count);
        for &(content_type, form) in &self.directory_entry_format {
            encode_uleb128(&mut out, content_type as u64);
            encode_uleb128(&mut out, form as u64);
        }

        // ── directories ─────────────────────────────────────────────────
        encode_uleb128(&mut out, self.directories.len() as u64);
        for dir in &self.directories {
            // Encode per format descriptor (assumes DW_FORM_string)
            out.extend_from_slice(dir.as_bytes());
            out.push(0);
        }

        // ── file name entry format ──────────────────────────────────────
        out.push(self.file_name_entry_format_count);
        for &(content_type, form) in &self.file_name_entry_format {
            encode_uleb128(&mut out, content_type as u64);
            encode_uleb128(&mut out, form as u64);
        }

        // ── file names ──────────────────────────────────────────────────
        encode_uleb128(&mut out, self.file_names.len() as u64);
        for file in &self.file_names {
            // Encode per format descriptor
            // DW_LNCT_path (DW_FORM_string)
            out.extend_from_slice(file.name.as_bytes());
            out.push(0);
            // DW_LNCT_directory_index (DW_FORM_udata)
            encode_uleb128(&mut out, file.directory_index);
            // If more fields (timestamp, size, MD5):
            // DW_LNCT_timestamp (DW_FORM_udata)
            encode_uleb128(&mut out, file.mod_time);
            // DW_LNCT_size (DW_FORM_udata)
            encode_uleb128(&mut out, file.length);
        }

        // ── Fixup header_length ─────────────────────────────────────────
        let hdr_len = (out.len() - hdr_len_pos - 4) as u32;
        out[hdr_len_pos..hdr_len_pos + 4].copy_from_slice(&hdr_len.to_le_bytes());

        // ── Fixup unit_length ───────────────────────────────────────────
        let unit_len = (out.len() - len_pos - 4) as u32;
        out[len_pos..len_pos + 4].copy_from_slice(&unit_len.to_le_bytes());

        out
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ── Content type tests ─────────────────────────────────────────────────

    #[test]
    fn test_content_type_values() {
        assert_eq!(DW_LNCT_path, 0x01);
        assert_eq!(DW_LNCT_directory_index, 0x02);
        assert_eq!(DW_LNCT_timestamp, 0x03);
        assert_eq!(DW_LNCT_size, 0x04);
        assert_eq!(DW_LNCT_MD5, 0x05);
    }

    // ── Standard opcode tests ──────────────────────────────────────────────

    #[test]
    fn test_std_opcode_values() {
        assert_eq!(std_opcodes::DW_LNS_copy, 1);
        assert_eq!(std_opcodes::DW_LNS_set_prologue_end, 10);
        assert_eq!(std_opcodes::DW_LNS_set_epilogue_begin, 11);
        assert_eq!(std_opcodes::DW_LNS_set_isa, 12);
    }

    // ── Extended opcode tests ──────────────────────────────────────────────

    #[test]
    fn test_ext_opcode_values() {
        assert_eq!(ext_opcodes::DW_LNE_end_sequence, 1);
        assert_eq!(ext_opcodes::DW_LNE_set_address, 2);
        assert_eq!(ext_opcodes::DW_LNE_define_file, 3);
        assert_eq!(ext_opcodes::DW_LNE_set_discriminator, 4);
    }

    // ── LineState tests ────────────────────────────────────────────────────

    #[test]
    fn test_line_state_default() {
        let state = LineState::default();
        assert_eq!(state.address, 0);
        assert_eq!(state.file, 1);
        assert_eq!(state.line, 1);
        assert_eq!(state.column, 0);
        assert!(!state.is_stmt);
        assert!(!state.basic_block);
        assert!(!state.end_sequence);
        assert!(!state.prologue_end);
        assert!(!state.epilogue_begin);
        assert_eq!(state.isa, 0);
        assert_eq!(state.discriminator, 0);
    }

    #[test]
    fn test_line_state_new_with_stmt() {
        let state = LineState::new(true);
        assert!(state.is_stmt);
    }

    #[test]
    fn test_line_state_reset() {
        let mut state = LineState::default();
        state.address = 0x1000;
        state.file = 3;
        state.line = 42;
        state.reset(true);
        assert_eq!(state.address, 0);
        assert_eq!(state.file, 1);
        assert_eq!(state.line, 1);
        assert!(state.is_stmt);
    }

    // ── LineProgramHeader tests ────────────────────────────────────────────

    #[test]
    fn test_line_program_header_default() {
        let header = LineProgramHeader::default();
        assert_eq!(header.version, 5);
        assert_eq!(header.address_size, 8);
        assert_eq!(header.segment_selector_size, 0);
        assert_eq!(header.minimum_instruction_length, 1);
        assert_eq!(header.maximum_operations_per_instruction, 1);
        assert_eq!(header.default_is_stmt, 1);
        assert_eq!(header.line_base, -5);
        assert_eq!(header.line_range, 14);
        assert_eq!(header.opcode_base, 13);
    }

    #[test]
    fn test_emit_header_v5_produces_valid_output() {
        let lp = LineProgram::new();
        let data = lp.emit_header_v5(8);
        assert!(!data.is_empty());

        // Check unit_length is valid (first 4 bytes, little-endian)
        let unit_len = u32::from_le_bytes(data[0..4].try_into().unwrap());
        assert!(unit_len > 0);

        // Version should be 5 (bytes 4-5)
        let version = u16::from_le_bytes(data[4..6].try_into().unwrap());
        assert_eq!(version, 5);

        // Address size (byte 6)
        assert_eq!(data[6], 8);

        // Segment selector size (byte 7)
        assert_eq!(data[7], 0);
    }

    #[test]
    fn test_emit_header_v5_with_directories() {
        let mut lp = LineProgram::new();
        lp.add_directory("/usr/src");
        lp.add_directory("/usr/include");
        let data = lp.emit_header_v5(8);
        assert!(!data.is_empty());
        // Should contain directory strings
        let s = String::from_utf8_lossy(&data);
        assert!(s.contains("/usr/src"));
        assert!(s.contains("/usr/include"));
    }

    #[test]
    fn test_emit_header_v5_with_files() {
        let mut lp = LineProgram::new();
        lp.add_directory("/src");
        let idx = lp.add_file("main.c", 1);
        lp.add_line(0x1000, idx, 1, 0);
        let data = lp.emit_header_v5(8);
        let s = String::from_utf8_lossy(&data);
        assert!(s.contains("main.c"));
    }

    // ── Body v5 emission tests ─────────────────────────────────────────────

    #[test]
    fn test_emit_body_v5_empty() {
        let lp = LineProgram::new();
        let data = lp.emit_body_v5();
        assert!(!data.is_empty());
        // Should end with DW_LNE_end_sequence
        assert_eq!(data[data.len() - 1], ext_opcodes::DW_LNE_end_sequence);
    }

    #[test]
    fn test_emit_body_v5_single_row() {
        let mut lp = LineProgram::new();
        lp.add_line(0x1000, 1, 5, 0);
        let data = lp.emit_body_v5();
        assert!(!data.is_empty());
        assert_eq!(data[data.len() - 1], ext_opcodes::DW_LNE_end_sequence);
    }

    #[test]
    fn test_emit_body_v5_multiple_rows() {
        let mut lp = LineProgram::new();
        lp.add_line(0x1000, 1, 5, 0);
        lp.add_line(0x1010, 1, 6, 0);
        lp.add_line(0x1020, 1, 7, 0);
        let data = lp.emit_body_v5();
        assert!(!data.is_empty());
        assert_eq!(data[data.len() - 1], ext_opcodes::DW_LNE_end_sequence);
    }

    // ── LineProgramBuilder tests ───────────────────────────────────────────

    #[test]
    fn test_builder_new() {
        let builder = LineProgramBuilder::new();
        assert_eq!(builder.program.files.len(), 1);
        assert_eq!(builder.state.file, 1);
    }

    #[test]
    fn test_builder_add_directory_and_file() {
        let mut builder = LineProgramBuilder::new();
        let dir_idx = builder.add_directory("/src");
        let file_idx = builder.add_file("test.c", dir_idx);
        assert_eq!(dir_idx, 0);
        assert_eq!(file_idx, 1);
        assert_eq!(builder.program.files[1].name, "test.c");
    }

    #[test]
    fn test_builder_set_state() {
        let mut builder = LineProgramBuilder::new();
        builder.set_address(0x4000);
        builder.set_file(2);
        builder.set_line(10);
        builder.set_column(3);

        let state = builder.current_state();
        assert_eq!(state.address, 0x4000);
        assert_eq!(state.file, 2);
        assert_eq!(state.line, 10);
        assert_eq!(state.column, 3);
    }

    #[test]
    fn test_builder_set_flags() {
        let mut builder = LineProgramBuilder::new();
        builder.set_is_stmt(true);
        builder.set_basic_block();
        builder.set_prologue_end();
        builder.set_epilogue_begin();
        builder.set_isa(5);
        builder.set_discriminator(42);

        let state = builder.current_state();
        assert!(state.is_stmt);
        assert!(state.basic_block);
        assert!(state.prologue_end);
        assert!(state.epilogue_begin);
        assert_eq!(state.isa, 5);
        assert_eq!(state.discriminator, 42);
    }

    #[test]
    fn test_builder_emit_row() {
        let mut builder = LineProgramBuilder::new();
        builder.set_address(0x2000);
        builder.set_line(12);
        builder.set_basic_block();
        builder.emit_row();

        assert_eq!(builder.program.rows.len(), 1);
        let row = &builder.program.rows[0];
        assert_eq!(row.address, 0x2000);
        assert_eq!(row.line, 12);
        assert!(row.basic_block);

        // Flags should reset after emit
        let state = builder.current_state();
        assert!(!state.basic_block);
    }

    #[test]
    fn test_builder_into_program() {
        let mut builder = LineProgramBuilder::new();
        builder.set_address(0x1000);
        builder.set_line(5);
        builder.emit_row();
        builder.set_address(0x1010);
        builder.set_line(6);
        builder.emit_row();

        let program = builder.into_program();
        assert_eq!(program.rows.len(), 2);
        assert_eq!(program.rows[0].address, 0x1000);
        assert_eq!(program.rows[1].address, 0x1010);
    }

    // ── Full v5 emission tests ─────────────────────────────────────────────

    #[test]
    fn test_emit_v5_complete() {
        let mut lp = LineProgram::new();
        lp.add_directory("/tmp");
        let f_idx = lp.add_file("test.c", 1);
        lp.add_line(0x4000, f_idx, 10, 0);

        let data = lp.emit_v5(8);
        assert!(!data.is_empty());
        // Should have both header and body
        assert!(data.len() > 20);
    }

    #[test]
    fn test_emit_header_v5_address_size_4() {
        let lp = LineProgram::new();
        let data = lp.emit_header_v5(4);
        assert_eq!(data[6], 4); // address_size field
    }

    #[test]
    fn test_to_header_v5() {
        let mut lp = LineProgram::new();
        lp.add_directory("/proj");
        lp.add_file("main.rs", 1);

        let header = lp.to_header_v5(8);
        assert_eq!(header.version, 5);
        assert_eq!(header.address_size, 8);
        assert_eq!(header.directories.len(), 1);
        assert_eq!(header.file_names.len(), 2); // default "unknown" + "main.rs"
        assert_eq!(header.file_names[1].name, "main.rs");
    }

    // ── LineProgramHeader::emit tests ──────────────────────────────────────

    #[test]
    fn test_header_emit() {
        let mut header = LineProgramHeader::default();
        header.address_size = 8;
        header.directories.push("/src".to_string());
        header.file_names.push(LineFileEntry {
            name: "test.c".to_string(),
            directory_index: 1,
            mod_time: 0,
            length: 0,
            md5_checksum: None,
        });

        let data = header.emit();
        assert!(!data.is_empty());

        // Version = 5
        let version = u16::from_le_bytes(data[4..6].try_into().unwrap());
        assert_eq!(version, 5);

        // Should contain directory and file names
        let s = String::from_utf8_lossy(&data);
        assert!(s.contains("/src"));
        assert!(s.contains("test.c"));
    }

    // ── LineFileEntry tests ────────────────────────────────────────────────

    #[test]
    fn test_line_file_entry_default() {
        let entry = LineFileEntry {
            name: "test.rs".to_string(),
            directory_index: 0,
            mod_time: 12345,
            length: 67890,
            md5_checksum: Some([0xAB; 16]),
        };
        assert_eq!(entry.name, "test.rs");
        assert_eq!(entry.directory_index, 0);
        assert_eq!(entry.mod_time, 12345);
        assert_eq!(entry.length, 67890);
        assert!(entry.md5_checksum.is_some());
    }

    // ── Cross-version compatibility tests ──────────────────────────────────

    #[test]
    fn test_v5_header_roundtrip() {
        let mut lp = LineProgram::new();
        lp.add_directory("/proj");
        lp.add_file("hello.c", 1);
        lp.add_line(0x1000, 1, 1, 0);

        let v5_data = lp.emit_v5(8);
        let v4_header = lp.emit_header();
        let v4_body = lp.emit_body();
        let v4_data: Vec<u8> = v4_header.iter().chain(v4_body.iter()).copied().collect();

        // Both should be non-empty
        assert!(!v5_data.is_empty());
        assert!(!v4_data.is_empty());

        // v5 should have version = 5 in header
        let v5_version = u16::from_le_bytes(v5_data[4..6].try_into().unwrap());
        assert_eq!(v5_version, 5);

        // v4 should have version = 2 in header
        let v4_version = u16::from_le_bytes(v4_data[4..6].try_into().unwrap());
        assert_eq!(v4_version, 2);
    }

    #[test]
    fn test_add_row_full() {
        let mut lp = LineProgram::new();
        lp.add_row_full(0x5000, 1, 42, 8, true, true, false, false, 0, 3);
        assert_eq!(lp.rows.len(), 1);
        let row = &lp.rows[0];
        assert_eq!(row.address, 0x5000);
        assert_eq!(row.line, 42);
        assert_eq!(row.column, 8);
        assert!(row.is_stmt);
        assert!(row.basic_block);
        assert!(!row.prologue_end);
        assert!(!row.epilogue_begin);
    }
}