llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
//! LLVM Diagnostics — error/warning/remark infrastructure.
//! Phase 9 — LLVM.DIAG.1 Court.

use std::collections::HashMap;
use std::fmt;

/// Severity levels for diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Remark,
    Warning,
    Error,
    Fatal,
}

/// A diagnostic message with location and severity.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub severity: Severity,
    pub message: String,
    pub file: Option<String>,
    pub line: Option<u32>,
    pub column: Option<u32>,
}

impl Diagnostic {
    pub fn error(msg: impl Into<String>) -> Self {
        Self {
            severity: Severity::Error,
            message: msg.into(),
            file: None,
            line: None,
            column: None,
        }
    }
    pub fn warning(msg: impl Into<String>) -> Self {
        Self {
            severity: Severity::Warning,
            message: msg.into(),
            file: None,
            line: None,
            column: None,
        }
    }
    pub fn remark(msg: impl Into<String>) -> Self {
        Self {
            severity: Severity::Remark,
            message: msg.into(),
            file: None,
            line: None,
            column: None,
        }
    }
    pub fn with_location(mut self, file: &str, line: u32, col: u32) -> Self {
        self.file = Some(file.into());
        self.line = Some(line);
        self.column = Some(col);
        self
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sev = match self.severity {
            Severity::Remark => "remark",
            Severity::Warning => "warning",
            Severity::Error => "error",
            Severity::Fatal => "fatal error",
        };
        if let (Some(file), Some(line), Some(col)) = (&self.file, self.line, self.column) {
            write!(f, "{}:{}:{}: {}: {}", file, line, col, sev, self.message)
        } else {
            write!(f, "{}: {}", sev, self.message)
        }
    }
}

/// Collects and manages diagnostics during compilation.
#[derive(Debug, Clone)]
pub struct DiagnosticManager {
    pub diagnostics: Vec<Diagnostic>,
    pub error_count: usize,
    pub warning_count: usize,
}

impl DiagnosticManager {
    pub fn new() -> Self {
        Self {
            diagnostics: Vec::new(),
            error_count: 0,
            warning_count: 0,
        }
    }

    pub fn emit(&mut self, diag: Diagnostic) {
        match diag.severity {
            Severity::Error | Severity::Fatal => self.error_count += 1,
            Severity::Warning => self.warning_count += 1,
            _ => {}
        }
        self.diagnostics.push(diag);
    }

    pub fn has_errors(&self) -> bool {
        self.error_count > 0
    }
    pub fn has_warnings(&self) -> bool {
        self.warning_count > 0
    }

    /// Print all diagnostics to stderr.
    pub fn print_all(&self) {
        for diag in &self.diagnostics {
            eprintln!("{}", diag);
        }
    }
}

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

// ============================================================================
// Enhanced Diagnostic Infrastructure — production diagnostic engine
// ============================================================================

/// Diagnostic severity level (parallel to Severity, used by DiagnosticEngine).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiagLevel {
    /// Informational note — does not indicate a problem
    Note,
    /// Warning — potential issue that should be reviewed
    Warning,
    /// Error — definite problem; compilation may continue
    Error,
    /// Fatal error — compilation cannot continue
    Fatal,
}

impl DiagLevel {
    /// Convert a DiagLevel to a human-readable label.
    pub fn as_str(&self) -> &'static str {
        match self {
            DiagLevel::Note => "note",
            DiagLevel::Warning => "warning",
            DiagLevel::Error => "error",
            DiagLevel::Fatal => "fatal error",
        }
    }

    /// Returns true if this level indicates an error.
    pub fn is_error(&self) -> bool {
        matches!(self, DiagLevel::Error | DiagLevel::Fatal)
    }

    /// Returns true if this level is fatal.
    pub fn is_fatal(&self) -> bool {
        matches!(self, DiagLevel::Fatal)
    }
}

impl fmt::Display for DiagLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A location in a source file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceLocation {
    /// The filename (or "<stdin>" for standard input)
    pub filename: String,
    /// 1-based line number
    pub line: u32,
    /// 1-based column number
    pub column: u32,
    /// The full text of the source line, if available
    pub line_text: Option<String>,
}

impl SourceLocation {
    /// Create a new source location.
    pub fn new(filename: &str, line: u32, column: u32) -> Self {
        Self {
            filename: filename.to_string(),
            line,
            column,
            line_text: None,
        }
    }

    /// Create a location with the source line text included.
    pub fn with_line_text(mut self, text: &str) -> Self {
        self.line_text = Some(text.to_string());
        self
    }

    /// Format as "file:line:col" (GCC/Clang style).
    pub fn format_short(&self) -> String {
        format!("{}:{}:{}", self.filename, self.line, self.column)
    }
}

impl fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}:{}", self.filename, self.line, self.column)
    }
}

/// A range in source code (start to end).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceRange {
    /// Start of the range
    pub start: SourceLocation,
    /// End of the range
    pub end: SourceLocation,
}

impl SourceRange {
    /// Create a new source range.
    pub fn new(start: SourceLocation, end: SourceLocation) -> Self {
        Self { start, end }
    }

    /// Create a single-point range (start == end).
    pub fn point(loc: SourceLocation) -> Self {
        Self {
            start: loc.clone(),
            end: loc,
        }
    }

    /// Returns true if this range spans multiple lines.
    pub fn is_multiline(&self) -> bool {
        self.start.filename != self.end.filename || self.start.line != self.end.line
    }

    /// Format as "file:line:col-file:line:col".
    pub fn format_short(&self) -> String {
        if self.start.filename == self.end.filename {
            if self.start.line == self.end.line {
                format!(
                    "{}:{}:{}-{}",
                    self.start.filename, self.start.line, self.start.column, self.end.column
                )
            } else {
                format!(
                    "{}:{}:{}-{}:{}",
                    self.start.filename,
                    self.start.line,
                    self.start.column,
                    self.end.line,
                    self.end.column
                )
            }
        } else {
            format!("{}-{}", self.start.format_short(), self.end.format_short())
        }
    }
}

/// A fix-it hint suggesting a textual replacement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FixItHint {
    /// The source range to replace
    pub range: SourceRange,
    /// The replacement text (empty string means deletion)
    pub replacement: String,
}

impl FixItHint {
    /// Create a new fix-it hint.
    pub fn new(range: SourceRange, replacement: &str) -> Self {
        Self {
            range,
            replacement: replacement.to_string(),
        }
    }

    /// Create a fix-it that inserts text at a location.
    pub fn insertion(loc: &SourceLocation, text: &str) -> Self {
        Self {
            range: SourceRange::point(loc.clone()),
            replacement: text.to_string(),
        }
    }

    /// Create a fix-it that removes a range (replaces with nothing).
    pub fn removal(range: SourceRange) -> Self {
        Self {
            range,
            replacement: String::new(),
        }
    }

    /// Create a fix-it that replaces a range with given text.
    pub fn replacement(range: SourceRange, text: &str) -> Self {
        Self {
            range,
            replacement: text.to_string(),
        }
    }

    /// Format the fix-it hint in Clang style.
    pub fn format(&self) -> String {
        format!("{}: \"{}\"", self.range.format_short(), self.replacement)
    }
}

/// An enhanced diagnostic with notes, ranges, and fix-it hints.
#[derive(Debug, Clone)]
pub struct RichDiagnostic {
    /// Severity level
    pub level: DiagLevel,
    /// Primary diagnostic message
    pub message: String,
    /// Primary error location
    pub location: Option<SourceLocation>,
    /// Source ranges to highlight
    pub ranges: Vec<SourceRange>,
    /// Additional notes (each may have its own location)
    pub notes: Vec<DiagnosticNote>,
    /// Fix-it hints for automated correction
    pub fixit_hints: Vec<FixItHint>,
    /// Optional error/warning code (e.g., "-Wunused-variable")
    pub error_code: Option<String>,
}

/// A note attached to a diagnostic, optionally with a location.
#[derive(Debug, Clone)]
pub struct DiagnosticNote {
    /// Note message
    pub message: String,
    /// Location for this note
    pub location: Option<SourceLocation>,
}

impl DiagnosticNote {
    /// Create a new note with a message.
    pub fn new(message: &str) -> Self {
        Self {
            message: message.to_string(),
            location: None,
        }
    }

    /// Create a note at a specific location.
    pub fn at(message: &str, location: SourceLocation) -> Self {
        Self {
            message: message.to_string(),
            location: Some(location),
        }
    }
}

impl RichDiagnostic {
    /// Create a new rich diagnostic.
    pub fn new(level: DiagLevel, message: &str) -> Self {
        Self {
            level,
            message: message.to_string(),
            location: None,
            ranges: Vec::new(),
            notes: Vec::new(),
            fixit_hints: Vec::new(),
            error_code: None,
        }
    }

    /// Set the primary location.
    pub fn at(mut self, location: SourceLocation) -> Self {
        self.location = Some(location);
        self
    }

    /// Add a source range.
    pub fn add_range(mut self, range: SourceRange) -> Self {
        self.ranges.push(range);
        self
    }

    /// Add a note.
    pub fn add_note(mut self, note: DiagnosticNote) -> Self {
        self.notes.push(note);
        self
    }

    /// Add a fix-it hint.
    pub fn add_fixit(mut self, hint: FixItHint) -> Self {
        self.fixit_hints.push(hint);
        self
    }

    /// Set the error code.
    pub fn with_code(mut self, code: &str) -> Self {
        self.error_code = Some(code.to_string());
        self
    }
}

impl fmt::Display for RichDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Primary message
        if let Some(ref loc) = self.location {
            write!(f, "{}: {}: ", loc, self.level)?;
        } else {
            write!(f, "{}: ", self.level)?;
        }

        if let Some(ref code) = self.error_code {
            write!(f, "[{}] ", code)?;
        }

        writeln!(f, "{}", self.message)?;

        // Source line context
        if let Some(ref loc) = self.location {
            if let Some(ref line_text) = loc.line_text {
                writeln!(f, "  {} | {}", loc.line, line_text)?;
                // Caret pointing to column
                write!(f, "  {} | ", " ".repeat(loc.line.to_string().len()))?;
                for _ in 1..loc.column {
                    write!(f, " ")?;
                }
                // Underline the range if available
                if let Some(first_range) = self.ranges.first() {
                    let len = if first_range.start.line == first_range.end.line {
                        (first_range
                            .end
                            .column
                            .saturating_sub(first_range.start.column)
                            + 1) as usize
                    } else {
                        1
                    };
                    for _ in 0..len {
                        write!(f, "~")?;
                    }
                } else {
                    write!(f, "^")?;
                }
                writeln!(f)?;
            }
        }

        // Notes
        for note in &self.notes {
            if let Some(ref loc) = note.location {
                writeln!(f, "{}: note: {}", loc, note.message)?;
            } else {
                writeln!(f, "note: {}", note.message)?;
            }
        }

        // Fix-it hints
        for fixit in &self.fixit_hints {
            writeln!(f, "  fixit: {}", fixit.format())?;
        }

        Ok(())
    }
}

// ============================================================================
// DiagnosticEngine — central diagnostic collector
// ============================================================================

/// The diagnostic engine collects, filters, and prints diagnostics.
///
/// Usage:
/// ```ignore
/// let mut engine = DiagnosticEngine::new();
/// engine.error("type mismatch")
///       .at(SourceLocation::new("file.ll", 10, 5))
///       .add_note(DiagnosticNote::new("expected i32, found i64"));
/// engine.print_all();
/// ```
#[derive(Debug, Clone)]
pub struct DiagnosticEngine {
    /// All emitted diagnostics
    pub diagnostics: Vec<RichDiagnostic>,
    /// Number of errors (including fatal)
    pub error_count: usize,
    /// Number of warnings
    pub warning_count: usize,
    /// Maximum errors before aborting (0 = unlimited)
    pub max_errors: usize,
    /// Treat warnings as errors
    pub warnings_as_errors: bool,
    /// Suppress all warnings
    pub ignore_warnings: bool,
    /// Currently building diagnostic (for the builder pattern)
    building: Option<RichDiagnostic>,
}

impl DiagnosticEngine {
    /// Create a new diagnostic engine.
    pub fn new() -> Self {
        Self {
            diagnostics: Vec::new(),
            error_count: 0,
            warning_count: 0,
            max_errors: 20,
            warnings_as_errors: false,
            ignore_warnings: false,
            building: None,
        }
    }

    /// Start building an error diagnostic. Call `.at()`, `.add_range()`,
    /// `.add_note()`, `.add_fixit()` on the returned builder, then the
    /// next call to `.error()`, `.warning()`, or `.note()` will finalize it.
    pub fn error(&mut self, msg: &str) -> &mut Self {
        self.finalize_building();
        self.building = Some(RichDiagnostic::new(DiagLevel::Error, msg));
        self
    }

    /// Start building a warning diagnostic.
    pub fn warning(&mut self, msg: &str) -> &mut Self {
        self.finalize_building();
        self.building = Some(RichDiagnostic::new(DiagLevel::Warning, msg));
        self
    }

    /// Start building a note diagnostic.
    pub fn note(&mut self, msg: &str) -> &mut Self {
        self.finalize_building();
        self.building = Some(RichDiagnostic::new(DiagLevel::Note, msg));
        self
    }

    /// Set the location on the currently-building diagnostic.
    pub fn at(&mut self, loc: SourceLocation) -> &mut Self {
        if let Some(ref mut diag) = self.building {
            diag.location = Some(loc);
        }
        self
    }

    /// Add a source range to the currently-building diagnostic.
    pub fn add_range(&mut self, range: SourceRange) -> &mut Self {
        if let Some(ref mut diag) = self.building {
            diag.ranges.push(range);
        }
        self
    }

    /// Add a note to the currently-building diagnostic.
    pub fn add_note(&mut self, note: &str) -> &mut Self {
        if let Some(ref mut diag) = self.building {
            diag.notes.push(DiagnosticNote::new(note));
        }
        self
    }

    /// Add a fix-it hint to the currently-building diagnostic.
    pub fn add_fixit(&mut self, hint: FixItHint) -> &mut Self {
        if let Some(ref mut diag) = self.building {
            diag.fixit_hints.push(hint);
        }
        self
    }

    /// Set the error code on the currently-building diagnostic.
    pub fn with_code(&mut self, code: &str) -> &mut Self {
        if let Some(ref mut diag) = self.building {
            diag.error_code = Some(code.to_string());
        }
        self
    }

    /// Finalize the currently-building diagnostic and push it into the list.
    pub fn emit(&mut self) -> &mut Self {
        self.finalize_building();
        self
    }

    /// Emit a complete rich diagnostic directly.
    pub fn emit_diagnostic(&mut self, diag: RichDiagnostic) {
        self.record(&diag);
        self.diagnostics.push(diag);
    }

    /// Returns true if any errors have been emitted.
    pub fn has_errors(&self) -> bool {
        self.error_count > 0
    }

    /// Returns true if any warnings have been emitted.
    pub fn has_warnings(&self) -> bool {
        self.warning_count > 0
    }

    /// Returns true if the error limit has been reached.
    pub fn error_limit_reached(&self) -> bool {
        self.max_errors > 0 && self.error_count >= self.max_errors
    }

    /// Clear all stored diagnostics.
    pub fn clear(&mut self) {
        self.diagnostics.clear();
        self.error_count = 0;
        self.warning_count = 0;
        self.building = None;
    }

    /// Print all diagnostics to stderr in a GCC/Clang-compatible format.
    pub fn print_all(&self) {
        for diag in &self.diagnostics {
            self.print_diagnostic(diag);
        }
    }

    /// Print a single diagnostic to stderr.
    pub fn print_diagnostic(&self, diag: &RichDiagnostic) {
        eprintln!("{}", diag);
    }

    /// Print all diagnostics to a String.
    pub fn format_all(&self) -> String {
        let mut out = String::new();
        for diag in &self.diagnostics {
            out.push_str(&format!("{}\n", diag));
        }
        out
    }

    /// Return an iterator over all diagnostics.
    pub fn iter(&self) -> impl Iterator<Item = &RichDiagnostic> {
        self.diagnostics.iter()
    }

    /// Return the number of diagnostics.
    pub fn len(&self) -> usize {
        self.diagnostics.len()
    }

    /// Returns true if there are no diagnostics.
    pub fn is_empty(&self) -> bool {
        self.diagnostics.is_empty()
    }

    // Internal: finalize the building diagnostic and push it.
    fn finalize_building(&mut self) {
        if let Some(diag) = self.building.take() {
            self.record(&diag);
            self.diagnostics.push(diag);
        }
    }

    // Internal: update counters based on a diagnostic.
    fn record(&mut self, diag: &RichDiagnostic) {
        match diag.level {
            DiagLevel::Error | DiagLevel::Fatal => {
                self.error_count += 1;
            }
            DiagLevel::Warning => {
                if self.warnings_as_errors {
                    self.error_count += 1;
                } else if !self.ignore_warnings {
                    self.warning_count += 1;
                }
            }
            DiagLevel::Note => {}
        }
    }
}

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

impl Drop for DiagnosticEngine {
    fn drop(&mut self) {
        // Finalize any in-progress diagnostic on drop
        self.finalize_building();
    }
}

// ============================================================================
// SourceManager — source file tracking
// ============================================================================

/// Manages source file contents and provides line/column lookups.
#[derive(Debug, Clone)]
pub struct SourceManager {
    /// All loaded source files, keyed by filename.
    pub files: HashMap<String, SourceFile>,
}

/// A single source file loaded into the source manager.
#[derive(Debug, Clone)]
pub struct SourceFile {
    /// The filename (or identifier)
    pub filename: String,
    /// The complete file content
    pub content: String,
    /// Lines of the file (split by '\n', lines include the newline)
    pub lines: Vec<String>,
}

impl SourceFile {
    /// Create a new source file from content.
    pub fn new(filename: &str, content: &str) -> Self {
        let lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();
        Self {
            filename: filename.to_string(),
            content: content.to_string(),
            lines,
        }
    }

    /// Get the line at the given 1-based line number.
    pub fn get_line(&self, line: u32) -> Option<&str> {
        if line == 0 || line as usize > self.lines.len() {
            return None;
        }
        Some(&self.lines[line as usize - 1])
    }

    /// Get the character at a specific byte offset.
    pub fn get_char(&self, offset: usize) -> Option<char> {
        self.content[offset..].chars().next()
    }

    /// Convert a byte offset to a (line, column) pair (both 1-based).
    pub fn offset_to_location(&self, offset: usize) -> Option<(u32, u32)> {
        if offset > self.content.len() {
            return None;
        }
        let prefix = &self.content[..offset];
        let line = prefix.chars().filter(|&c| c == '\n').count() as u32 + 1;
        let last_newline = prefix.rfind('\n').map(|i| i + 1).unwrap_or(0);
        let col = (offset - last_newline) + 1;
        Some((line, col as u32))
    }

    /// Convert a (line, column) pair to a byte offset.
    pub fn location_to_offset(&self, line: u32, column: u32) -> Option<usize> {
        if line == 0 || column == 0 {
            return None;
        }
        let mut current_line = 1u32;
        let mut offset = 0usize;
        for ch in self.content.chars() {
            if current_line == line {
                // On the target line; count columns
                let col_on_line = (offset
                    - self.content[..offset]
                        .rfind('\n')
                        .map(|i| i + 1)
                        .unwrap_or(0))
                    + 1;
                if col_on_line as u32 == column {
                    return Some(offset);
                }
            }
            if ch == '\n' {
                current_line += 1;
                if current_line > line {
                    break;
                }
            }
            offset += ch.len_utf8();
        }
        None
    }

    /// Get a SourceLocation for a byte offset in this file.
    pub fn get_location(&self, offset: usize) -> Option<SourceLocation> {
        let (line, col) = self.offset_to_location(offset)?;
        let line_text = self.get_line(line).map(|s| s.to_string());
        Some(SourceLocation {
            filename: self.filename.clone(),
            line,
            column: col,
            line_text,
        })
    }
}

impl SourceManager {
    /// Create a new empty source manager.
    pub fn new() -> Self {
        Self {
            files: HashMap::new(),
        }
    }

    /// Add a source file to the manager.
    pub fn add_file(&mut self, filename: &str, content: &str) {
        self.files
            .insert(filename.to_string(), SourceFile::new(filename, content));
    }

    /// Get a reference to a source file by name.
    pub fn get_file(&self, filename: &str) -> Option<&SourceFile> {
        self.files.get(filename)
    }

    /// Get a SourceLocation for a (filename, byte offset) pair.
    pub fn get_location(&self, filename: &str, offset: usize) -> Option<SourceLocation> {
        self.files.get(filename)?.get_location(offset)
    }

    /// Get the text of a specific line in a file.
    pub fn get_line(&self, filename: &str, line: u32) -> Option<&str> {
        self.files.get(filename)?.get_line(line)
    }

    /// Get a SourceLocation for a (filename, line, column) triple.
    pub fn get_location_at(&self, filename: &str, line: u32, column: u32) -> SourceLocation {
        let line_text = self.get_line(filename, line).map(|s| s.to_string());
        SourceLocation {
            filename: filename.to_string(),
            line,
            column,
            line_text,
        }
    }

    /// Returns true if a file with the given name has been loaded.
    pub fn has_file(&self, filename: &str) -> bool {
        self.files.contains_key(filename)
    }

    /// Remove a file from the manager.
    pub fn remove_file(&mut self, filename: &str) {
        self.files.remove(filename);
    }

    /// Iterate over all managed files.
    pub fn iter_files(&self) -> impl Iterator<Item = &SourceFile> {
        self.files.values()
    }

    /// Return the number of managed files.
    pub fn file_count(&self) -> usize {
        self.files.len()
    }
}

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

// ============================================================================
// Convenience functions
// ============================================================================

/// Emit an error diagnostic using the builder pattern.
pub fn emit_error(engine: &mut DiagnosticEngine, msg: &str) {
    engine.error(msg);
}

/// Emit a warning diagnostic using the builder pattern.
pub fn emit_warning(engine: &mut DiagnosticEngine, msg: &str) {
    engine.warning(msg);
}

/// Emit a note diagnostic using the builder pattern.
pub fn emit_note(engine: &mut DiagnosticEngine, msg: &str) {
    engine.note(msg);
}

/// Create an error rich diagnostic and emit it.
pub fn emit_error_at(
    engine: &mut DiagnosticEngine,
    msg: &str,
    filename: &str,
    line: u32,
    column: u32,
) {
    let loc = SourceLocation::new(filename, line, column);
    engine.error(msg).at(loc);
}

/// Create a warning rich diagnostic and emit it.
pub fn emit_warning_at(
    engine: &mut DiagnosticEngine,
    msg: &str,
    filename: &str,
    line: u32,
    column: u32,
) {
    let loc = SourceLocation::new(filename, line, column);
    engine.warning(msg).at(loc);
}

/// Convert an old-style Diagnostic to a RichDiagnostic for the engine.
pub fn convert_diagnostic(diag: &Diagnostic) -> RichDiagnostic {
    let level = match diag.severity {
        Severity::Remark => DiagLevel::Note,
        Severity::Warning => DiagLevel::Warning,
        Severity::Error => DiagLevel::Error,
        Severity::Fatal => DiagLevel::Fatal,
    };
    let location = match (&diag.file, diag.line, diag.column) {
        (Some(file), Some(line), Some(col)) => Some(SourceLocation::new(file, line, col)),
        _ => None,
    };
    RichDiagnostic {
        level,
        message: diag.message.clone(),
        location,
        ranges: Vec::new(),
        notes: Vec::new(),
        fixit_hints: Vec::new(),
        error_code: None,
    }
}

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

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

    // --- Existing Diagnostic / DiagnosticManager tests (preserved) ---

    #[test]
    fn test_diagnostic_create() {
        let d = Diagnostic::error("something went wrong");
        assert_eq!(d.severity, Severity::Error);
        assert_eq!(d.message, "something went wrong");
    }

    #[test]
    fn test_diagnostic_with_location() {
        let d = Diagnostic::warning("unused variable").with_location("test.ll", 10, 5);
        assert_eq!(d.file, Some("test.ll".into()));
        assert_eq!(d.line, Some(10));
        assert_eq!(d.column, Some(5));
    }

    #[test]
    fn test_diagnostic_manager_emit() {
        let mut dm = DiagnosticManager::new();
        dm.emit(Diagnostic::error("e1"));
        dm.emit(Diagnostic::warning("w1"));
        dm.emit(Diagnostic::remark("r1"));
        assert_eq!(dm.error_count, 1);
        assert_eq!(dm.warning_count, 1);
        assert!(dm.has_errors());
        assert!(dm.has_warnings());
        assert_eq!(dm.diagnostics.len(), 3);
    }

    #[test]
    fn test_diagnostic_manager_no_errors() {
        let mut dm = DiagnosticManager::new();
        dm.emit(Diagnostic::remark("just a note"));
        assert!(!dm.has_errors());
        assert!(!dm.has_warnings());
    }

    // --- DiagLevel tests ---

    #[test]
    fn test_diaglevel_as_str() {
        assert_eq!(DiagLevel::Note.as_str(), "note");
        assert_eq!(DiagLevel::Warning.as_str(), "warning");
        assert_eq!(DiagLevel::Error.as_str(), "error");
        assert_eq!(DiagLevel::Fatal.as_str(), "fatal error");
    }

    #[test]
    fn test_diaglevel_is_error() {
        assert!(!DiagLevel::Note.is_error());
        assert!(!DiagLevel::Warning.is_error());
        assert!(DiagLevel::Error.is_error());
        assert!(DiagLevel::Fatal.is_error());
    }

    // --- SourceLocation tests ---

    #[test]
    fn test_source_location_new() {
        let loc = SourceLocation::new("test.ll", 5, 12);
        assert_eq!(loc.filename, "test.ll");
        assert_eq!(loc.line, 5);
        assert_eq!(loc.column, 12);
        assert!(loc.line_text.is_none());
    }

    #[test]
    fn test_source_location_with_line_text() {
        let loc = SourceLocation::new("test.ll", 3, 1).with_line_text("  ret void");
        assert_eq!(loc.line_text, Some("  ret void".to_string()));
    }

    #[test]
    fn test_source_location_format() {
        let loc = SourceLocation::new("file.ll", 10, 5);
        assert_eq!(loc.format_short(), "file.ll:10:5");
    }

    // --- SourceRange tests ---

    #[test]
    fn test_source_range_point() {
        let loc = SourceLocation::new("f.ll", 1, 1);
        let range = SourceRange::point(loc.clone());
        assert_eq!(range.start, range.end);
        assert!(!range.is_multiline());
    }

    #[test]
    fn test_source_range_multiline() {
        let start = SourceLocation::new("f.ll", 1, 1);
        let end = SourceLocation::new("f.ll", 3, 5);
        let range = SourceRange::new(start, end);
        assert!(range.is_multiline());
    }

    // --- FixItHint tests ---

    #[test]
    fn test_fixit_insertion() {
        let loc = SourceLocation::new("test.ll", 5, 1);
        let fixit = FixItHint::insertion(&loc, "  ");
        assert_eq!(fixit.replacement, "  ");
        assert_eq!(fixit.range.start, loc);
        assert_eq!(fixit.range.end, loc);
    }

    #[test]
    fn test_fixit_removal() {
        let start = SourceLocation::new("test.ll", 1, 1);
        let end = SourceLocation::new("test.ll", 1, 10);
        let range = SourceRange::new(start, end);
        let fixit = FixItHint::removal(range);
        assert_eq!(fixit.replacement, "");
    }

    #[test]
    fn test_fixit_format() {
        let start = SourceLocation::new("f.ll", 2, 3);
        let end = SourceLocation::new("f.ll", 2, 6);
        let hint = FixItHint::replacement(SourceRange::new(start, end), "foo");
        let formatted = hint.format();
        assert!(formatted.contains("f.ll"));
        assert!(formatted.contains("foo"));
    }

    // --- RichDiagnostic tests ---

    #[test]
    fn test_rich_diagnostic_new() {
        let diag = RichDiagnostic::new(DiagLevel::Error, "type mismatch");
        assert_eq!(diag.level, DiagLevel::Error);
        assert_eq!(diag.message, "type mismatch");
        assert!(diag.location.is_none());
        assert!(diag.ranges.is_empty());
        assert!(diag.notes.is_empty());
        assert!(diag.fixit_hints.is_empty());
    }

    #[test]
    fn test_rich_diagnostic_builder() {
        let loc = SourceLocation::new("test.ll", 10, 5);
        let diag = RichDiagnostic::new(DiagLevel::Warning, "unused variable")
            .at(loc.clone())
            .add_note(DiagnosticNote::new("declared here"))
            .with_code("Wunused");
        assert_eq!(diag.location, Some(loc));
        assert_eq!(diag.error_code, Some("Wunused".to_string()));
        assert_eq!(diag.notes.len(), 1);
    }

    // --- DiagnosticEngine tests ---

    #[test]
    fn test_engine_create() {
        let engine = DiagnosticEngine::new();
        assert!(!engine.has_errors());
        assert!(!engine.has_warnings());
        assert_eq!(engine.len(), 0);
        assert!(engine.is_empty());
    }

    #[test]
    fn test_engine_emit_error() {
        let mut engine = DiagnosticEngine::new();
        engine
            .error("test error")
            .at(SourceLocation::new("test.ll", 1, 1));
        assert!(engine.has_errors());
        assert!(!engine.has_warnings());
        assert_eq!(engine.error_count, 1);
        assert_eq!(engine.len(), 1);
    }

    #[test]
    fn test_engine_emit_warning() {
        let mut engine = DiagnosticEngine::new();
        engine
            .warning("test warning")
            .at(SourceLocation::new("test.ll", 2, 1));
        assert!(!engine.has_errors());
        assert!(engine.has_warnings());
        assert_eq!(engine.warning_count, 1);
    }

    #[test]
    fn test_engine_warnings_as_errors() {
        let mut engine = DiagnosticEngine::new();
        engine.warnings_as_errors = true;
        engine
            .warning("treated as error")
            .at(SourceLocation::new("test.ll", 1, 1));
        assert!(engine.has_errors());
        assert_eq!(engine.error_count, 1);
        assert_eq!(engine.warning_count, 0);
    }

    #[test]
    fn test_engine_ignore_warnings() {
        let mut engine = DiagnosticEngine::new();
        engine.ignore_warnings = true;
        engine
            .warning("ignored")
            .at(SourceLocation::new("test.ll", 1, 1));
        assert!(!engine.has_warnings());
        assert_eq!(engine.warning_count, 0);
        assert_eq!(engine.len(), 1); // still stored
    }

    #[test]
    fn test_engine_multiple_emits() {
        let mut engine = DiagnosticEngine::new();
        engine.error("e1").at(SourceLocation::new("test.ll", 1, 1));
        assert_eq!(engine.error_count, 1);
        engine.error("e2").at(SourceLocation::new("test.ll", 2, 1));
        assert_eq!(engine.error_count, 2);
        assert_eq!(engine.len(), 2);
    }

    #[test]
    fn test_engine_clear() {
        let mut engine = DiagnosticEngine::new();
        engine
            .error("test")
            .at(SourceLocation::new("test.ll", 1, 1));
        engine.clear();
        assert!(!engine.has_errors());
        assert_eq!(engine.len(), 0);
    }

    #[test]
    fn test_engine_builder_chaining() {
        let mut engine = DiagnosticEngine::new();
        let loc = SourceLocation::new("test.ll", 3, 10);
        let range = SourceRange::point(loc.clone());
        engine
            .error("syntax error")
            .at(loc.clone())
            .add_range(range)
            .add_note("expected ';'")
            .with_code("Esyntax");
        assert_eq!(engine.error_count, 1);
        assert_eq!(engine.len(), 1);
        let diag = &engine.diagnostics[0];
        assert_eq!(diag.ranges.len(), 1);
        assert_eq!(diag.notes.len(), 1);
        assert_eq!(diag.error_code, Some("Esyntax".to_string()));
    }

    #[test]
    fn test_engine_format_all() {
        let mut engine = DiagnosticEngine::new();
        engine
            .error("bad thing")
            .at(SourceLocation::new("test.ll", 1, 1));
        let text = engine.format_all();
        assert!(text.contains("error"));
        assert!(text.contains("bad thing"));
        assert!(text.contains("test.ll"));
    }

    // --- SourceFile tests ---

    #[test]
    fn test_source_file_new() {
        let sf = SourceFile::new("test.ll", "line1\nline2\nline3");
        assert_eq!(sf.filename, "test.ll");
        assert_eq!(sf.lines.len(), 3);
        assert_eq!(sf.get_line(1), Some("line1"));
        assert_eq!(sf.get_line(2), Some("line2"));
        assert_eq!(sf.get_line(3), Some("line3"));
        assert_eq!(sf.get_line(4), None);
    }

    #[test]
    fn test_source_file_offset_to_location() {
        let sf = SourceFile::new("test.ll", "abc\ndef\nghi");
        // 'a'=offset 0 -> (1, 1)
        assert_eq!(sf.offset_to_location(0), Some((1, 1)));
        // 'd'=offset 4 -> (2, 1)
        assert_eq!(sf.offset_to_location(4), Some((2, 1)));
        // 'h'=offset 8 -> (3, 1)
        assert_eq!(sf.offset_to_location(8), Some((3, 1)));
        // beyond end
        assert_eq!(sf.offset_to_location(100), None);
    }

    #[test]
    fn test_source_file_get_location() {
        let sf = SourceFile::new("test.ll", "first line\nsecond line");
        let loc = sf.get_location(6).unwrap(); // 'l' of "line" on line 1
        assert_eq!(loc.filename, "test.ll");
        assert_eq!(loc.line, 1);
        assert_eq!(loc.column, 7); // 0-based: f(0)i(1)r(2)s(3)t(4)' '(5)l(6)
    }

    // --- SourceManager tests ---

    #[test]
    fn test_source_manager_add_file() {
        let mut sm = SourceManager::new();
        sm.add_file("test.ll", "define void @main() {\n  ret void\n}");
        assert!(sm.has_file("test.ll"));
        assert_eq!(sm.file_count(), 1);
    }

    #[test]
    fn test_source_manager_get_line() {
        let mut sm = SourceManager::new();
        sm.add_file("test.ll", "line1\nline2\nline3");
        assert_eq!(sm.get_line("test.ll", 1), Some("line1"));
        assert_eq!(sm.get_line("test.ll", 3), Some("line3"));
        assert_eq!(sm.get_line("test.ll", 99), None);
        assert_eq!(sm.get_line("nonexistent.ll", 1), None);
    }

    #[test]
    fn test_source_manager_get_location() {
        let mut sm = SourceManager::new();
        sm.add_file("test.ll", "ab\ncd");
        let loc = sm.get_location("test.ll", 3).unwrap(); // 'c' at offset 3
        assert_eq!(loc.filename, "test.ll");
        assert_eq!(loc.line, 2);
        assert_eq!(loc.column, 1);
    }

    #[test]
    fn test_source_manager_remove_file() {
        let mut sm = SourceManager::new();
        sm.add_file("test.ll", "content");
        assert!(sm.has_file("test.ll"));
        sm.remove_file("test.ll");
        assert!(!sm.has_file("test.ll"));
    }

    // --- Convenience function tests ---

    #[test]
    fn test_emit_error_fn() {
        let mut engine = DiagnosticEngine::new();
        emit_error(&mut engine, "test error");
        assert!(engine.has_errors());
    }

    #[test]
    fn test_emit_warning_fn() {
        let mut engine = DiagnosticEngine::new();
        emit_warning(&mut engine, "test warning");
        assert!(engine.has_warnings());
    }

    #[test]
    fn test_emit_error_at_fn() {
        let mut engine = DiagnosticEngine::new();
        emit_error_at(&mut engine, "error", "file.ll", 5, 10);
        assert!(engine.has_errors());
        assert_eq!(engine.diagnostics[0].location.as_ref().unwrap().line, 5);
    }

    #[test]
    fn test_convert_diagnostic() {
        let old = Diagnostic::error("old error").with_location("file.ll", 3, 8);
        let rich = convert_diagnostic(&old);
        assert_eq!(rich.level, DiagLevel::Error);
        assert_eq!(rich.message, "old error");
        assert_eq!(rich.location.unwrap().line, 3);
    }
}