tsz-core 0.1.9

Core TypeScript compiler and type checker library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Diagnostic Infrastructure
//!
//! This module provides infrastructure for collecting and formatting compilation
//! errors and warnings. It is designed to work with AST nodes and spans rather
//! than raw string positions.
//!
//! # Components
//!
//! - `Diagnostic` - A single diagnostic message with location and severity
//! - `DiagnosticBag` - A collection of diagnostics for a compilation phase
//! - `DiagnosticSeverity` - Error, Warning, Info, or Hint
//! - `DiagnosticCode` - TypeScript-compatible error codes
//!
//! # Example
//!
//! ```ignore
//! let mut bag = DiagnosticBag::new();
//! bag.error(span, "Cannot find name 'foo'", 2304);
//! bag.warning(span, "Unused variable", 6133);
//!
//! for diag in bag.iter() {
//!     println!("{}", diag.format(&source));
//! }
//! ```

use crate::lsp::position::Range;
use crate::source_file::SourceFile;
use crate::span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

// =============================================================================
// Diagnostic Severity
// =============================================================================

/// The severity level of a diagnostic.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum DiagnosticSeverity {
    /// A hint (lowest severity)
    Hint = 4,
    /// Informational message
    Info = 3,
    /// A warning
    Warning = 2,
    /// An error (highest severity)
    #[default]
    Error = 1,
}

impl DiagnosticSeverity {
    /// Get the severity name for display.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Info => "info",
            Self::Hint => "hint",
        }
    }

    /// Check if this is an error.
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Error)
    }

    /// Check if this is a warning.
    pub const fn is_warning(&self) -> bool {
        matches!(self, Self::Warning)
    }
}

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

// =============================================================================
// Related Information
// =============================================================================

/// Additional information related to a diagnostic.
///
/// This is used to provide "see also" locations, such as where a type
/// was declared when reporting a type mismatch.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DiagnosticRelatedInfo {
    /// File containing the related information
    pub file_name: String,
    /// Location span
    pub span: Span,
    /// Message explaining the relationship
    pub message: String,
}

impl DiagnosticRelatedInfo {
    /// Create new related information.
    pub fn new(file_name: impl Into<String>, span: Span, message: impl Into<String>) -> Self {
        Self {
            file_name: file_name.into(),
            span,
            message: message.into(),
        }
    }
}

// =============================================================================
// Diagnostic
// =============================================================================

/// The domain or origin of a diagnostic.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum DiagnosticDomain {
    /// Standard TypeScript diagnostic (`TSxxxx`)
    #[default]
    TypeScript,
    /// Sound Mode diagnostic (`TSZxxxx`)
    Sound,
}

impl DiagnosticDomain {
    /// Get the prefix for the diagnostic code.
    pub const fn prefix(&self) -> &'static str {
        match self {
            Self::TypeScript => "TS",
            Self::Sound => "TSZ",
        }
    }

    /// Check if this is the default TypeScript domain.
    pub const fn is_typescript(&self) -> bool {
        matches!(self, Self::TypeScript)
    }
}

/// A diagnostic message with location, severity, and error code.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Diagnostic {
    /// The file containing the diagnostic
    pub file_name: String,
    /// The source span (byte offsets)
    pub span: Span,
    /// The diagnostic message
    pub message: String,
    /// The severity level
    pub severity: DiagnosticSeverity,
    /// The diagnostic code (e.g., TS2304)
    pub code: u32,
    /// The domain of the diagnostic (e.g., standard TS vs Sound Mode)
    #[serde(skip_serializing_if = "DiagnosticDomain::is_typescript", default)]
    pub domain: DiagnosticDomain,
    /// Optional related information
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub related: Vec<DiagnosticRelatedInfo>,
    /// Optional source string (e.g., "typescript")
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub source: Option<String>,
}

impl Diagnostic {
    /// Create a new diagnostic.
    pub fn new(
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        severity: DiagnosticSeverity,
        code: u32,
    ) -> Self {
        Self {
            file_name: file_name.into(),
            span,
            message: message.into(),
            severity,
            code,
            domain: DiagnosticDomain::TypeScript,
            related: Vec::new(),
            source: Some("typescript".to_string()),
        }
    }

    /// Set the origin domain of this diagnostic.
    pub fn with_domain(mut self, domain: DiagnosticDomain) -> Self {
        self.domain = domain;
        if matches!(domain, DiagnosticDomain::Sound) {
            self.source = Some("tsz-sound".to_string());
        }
        self
    }

    /// Create an error diagnostic.
    pub fn error(
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) -> Self {
        Self::new(file_name, span, message, DiagnosticSeverity::Error, code)
    }

    /// Create a warning diagnostic.
    pub fn warning(
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) -> Self {
        Self::new(file_name, span, message, DiagnosticSeverity::Warning, code)
    }

    /// Create an info diagnostic.
    pub fn info(
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) -> Self {
        Self::new(file_name, span, message, DiagnosticSeverity::Info, code)
    }

    /// Create a hint diagnostic.
    pub fn hint(
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) -> Self {
        Self::new(file_name, span, message, DiagnosticSeverity::Hint, code)
    }

    /// Add related information.
    pub fn with_related(mut self, info: DiagnosticRelatedInfo) -> Self {
        self.related.push(info);
        self
    }

    /// Add multiple related information items.
    pub fn with_related_all(mut self, infos: Vec<DiagnosticRelatedInfo>) -> Self {
        self.related.extend(infos);
        self
    }

    /// Set the source identifier.
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// Check if this is an error.
    pub const fn is_error(&self) -> bool {
        self.severity.is_error()
    }

    /// Check if this is a warning.
    pub const fn is_warning(&self) -> bool {
        self.severity.is_warning()
    }

    /// Get the start position (byte offset).
    pub const fn start(&self) -> u32 {
        self.span.start
    }

    /// Get the length.
    pub const fn length(&self) -> u32 {
        self.span.len()
    }

    /// Format the diagnostic for display.
    ///
    /// Returns a string like: "file.ts(1,5): error TS2304: Cannot find name 'foo'."
    pub fn format(&self, source_file: &mut SourceFile) -> String {
        let pos = source_file.offset_to_position(self.span.start);
        format!(
            "{}({},{}): {} {}{}: {}",
            self.file_name,
            pos.line + 1,
            pos.character + 1,
            self.severity,
            self.domain.prefix(),
            self.code,
            self.message
        )
    }

    /// Format the diagnostic in a simple format.
    ///
    /// Returns a string like: "error[TS2304]: Cannot find name 'foo'"
    pub fn format_simple(&self) -> String {
        format!(
            "{}[{}{}]: {}",
            self.severity,
            self.domain.prefix(),
            self.code,
            self.message
        )
    }

    /// Convert to LSP Range (requires source file for position conversion).
    pub fn to_range(&self, source_file: &mut SourceFile) -> Range {
        source_file.span_to_range(self.span)
    }
}

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

// =============================================================================
// DiagnosticBag
// =============================================================================

/// A collection of diagnostics for a compilation phase.
///
/// `DiagnosticBag` provides a convenient interface for collecting diagnostics
/// during parsing, binding, or type checking. It tracks error counts and
/// provides filtering capabilities.
#[derive(Clone, Debug, Default)]
pub struct DiagnosticBag {
    /// The collected diagnostics
    diagnostics: Vec<Diagnostic>,
    /// The file name for diagnostics added without explicit file
    default_file: String,
    /// Error count
    error_count: usize,
    /// Warning count
    warning_count: usize,
}

impl DiagnosticBag {
    /// Create a new empty diagnostic bag.
    pub const fn new() -> Self {
        Self {
            diagnostics: Vec::new(),
            default_file: String::new(),
            error_count: 0,
            warning_count: 0,
        }
    }

    /// Create a new diagnostic bag with a default file name.
    pub fn with_file(file_name: impl Into<String>) -> Self {
        Self {
            diagnostics: Vec::new(),
            default_file: file_name.into(),
            error_count: 0,
            warning_count: 0,
        }
    }

    /// Set the default file name.
    pub fn set_default_file(&mut self, file_name: impl Into<String>) {
        self.default_file = file_name.into();
    }

    /// Get the default file name.
    pub fn default_file(&self) -> &str {
        &self.default_file
    }

    /// Add a diagnostic.
    pub fn add(&mut self, diagnostic: Diagnostic) {
        match diagnostic.severity {
            DiagnosticSeverity::Error => self.error_count += 1,
            DiagnosticSeverity::Warning => self.warning_count += 1,
            _ => {}
        }
        self.diagnostics.push(diagnostic);
    }

    /// Add an error diagnostic.
    pub fn error(&mut self, span: Span, message: impl Into<String>, code: u32) {
        self.add(Diagnostic::error(&self.default_file, span, message, code));
    }

    /// Add a Sound Mode error diagnostic.
    pub fn sound_error(&mut self, span: Span, message: impl Into<String>, code: u32) {
        self.add(
            Diagnostic::error(&self.default_file, span, message, code)
                .with_domain(DiagnosticDomain::Sound),
        );
    }

    /// Add an error diagnostic with explicit file.
    pub fn error_in(
        &mut self,
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) {
        self.add(Diagnostic::error(file_name, span, message, code));
    }

    /// Add a Sound Mode error diagnostic with explicit file.
    pub fn sound_error_in(
        &mut self,
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) {
        self.add(
            Diagnostic::error(file_name, span, message, code).with_domain(DiagnosticDomain::Sound),
        );
    }

    /// Add a warning diagnostic.
    pub fn warning(&mut self, span: Span, message: impl Into<String>, code: u32) {
        self.add(Diagnostic::warning(&self.default_file, span, message, code));
    }

    /// Add a warning diagnostic with explicit file.
    pub fn warning_in(
        &mut self,
        file_name: impl Into<String>,
        span: Span,
        message: impl Into<String>,
        code: u32,
    ) {
        self.add(Diagnostic::warning(file_name, span, message, code));
    }

    /// Add an info diagnostic.
    pub fn info(&mut self, span: Span, message: impl Into<String>, code: u32) {
        self.add(Diagnostic::info(&self.default_file, span, message, code));
    }

    /// Add a hint diagnostic.
    pub fn hint(&mut self, span: Span, message: impl Into<String>, code: u32) {
        self.add(Diagnostic::hint(&self.default_file, span, message, code));
    }

    /// Check if there are any diagnostics.
    pub const fn has_diagnostics(&self) -> bool {
        !self.diagnostics.is_empty()
    }

    /// Check if there are any errors.
    pub const fn has_errors(&self) -> bool {
        self.error_count > 0
    }

    /// Check if there are any warnings.
    pub const fn has_warnings(&self) -> bool {
        self.warning_count > 0
    }

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

    /// Check if the bag is empty.
    pub const fn is_empty(&self) -> bool {
        self.diagnostics.is_empty()
    }

    /// Get the error count.
    pub const fn error_count(&self) -> usize {
        self.error_count
    }

    /// Get the warning count.
    pub const fn warning_count(&self) -> usize {
        self.warning_count
    }

    /// Get all diagnostics as a slice.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Iterate over diagnostics.
    pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
        self.diagnostics.iter()
    }

    /// Get only errors.
    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == DiagnosticSeverity::Error)
    }

    /// Get only warnings.
    pub fn warnings(&self) -> impl Iterator<Item = &Diagnostic> {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == DiagnosticSeverity::Warning)
    }

    /// Filter diagnostics by file.
    pub fn for_file<'a>(&'a self, file_name: &'a str) -> impl Iterator<Item = &'a Diagnostic> {
        self.diagnostics
            .iter()
            .filter(move |d| d.file_name == file_name)
    }

    /// Filter diagnostics by code.
    pub fn by_code(&self, code: u32) -> impl Iterator<Item = &Diagnostic> {
        self.diagnostics.iter().filter(move |d| d.code == code)
    }

    /// Sort diagnostics by file, then by position.
    pub fn sort(&mut self) {
        self.diagnostics
            .sort_by(|a, b| match a.file_name.cmp(&b.file_name) {
                std::cmp::Ordering::Equal => a.span.start.cmp(&b.span.start),
                other => other,
            });
    }

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

    /// Take all diagnostics, leaving the bag empty.
    pub fn take(&mut self) -> Vec<Diagnostic> {
        self.error_count = 0;
        self.warning_count = 0;
        std::mem::take(&mut self.diagnostics)
    }

    /// Merge another `DiagnosticBag` into this one.
    pub fn merge(&mut self, other: Self) {
        for diag in other.diagnostics {
            self.add(diag);
        }
    }

    /// Get error codes as a vector (for testing).
    pub fn error_codes(&self) -> Vec<u32> {
        self.errors().map(|d| d.code).collect()
    }

    /// Format all diagnostics for display.
    pub fn format_all(&self, source_file: &mut SourceFile) -> String {
        let mut result = String::new();
        for diag in &self.diagnostics {
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(&diag.format(source_file));
        }
        result
    }
}

impl IntoIterator for DiagnosticBag {
    type Item = Diagnostic;
    type IntoIter = std::vec::IntoIter<Diagnostic>;

    fn into_iter(self) -> Self::IntoIter {
        self.diagnostics.into_iter()
    }
}

impl<'a> IntoIterator for &'a DiagnosticBag {
    type Item = &'a Diagnostic;
    type IntoIter = std::slice::Iter<'a, Diagnostic>;

    fn into_iter(self) -> Self::IntoIter {
        self.diagnostics.iter()
    }
}

impl Extend<Diagnostic> for DiagnosticBag {
    fn extend<T: IntoIterator<Item = Diagnostic>>(&mut self, iter: T) {
        for diag in iter {
            self.add(diag);
        }
    }
}

// =============================================================================
// Diagnostic Formatting Utilities
// =============================================================================

/// Format a diagnostic message with placeholders.
///
/// Replaces {0}, {1}, etc. with the provided arguments.
///
/// # Example
/// ```ignore
/// let msg = format_message("Type '{0}' is not assignable to type '{1}'.", &["number", "string"]);
/// assert_eq!(msg, "Type 'number' is not assignable to type 'string'.");
/// ```
pub fn format_message(template: &str, args: &[&str]) -> String {
    let mut result = template.to_string();
    for (i, arg) in args.iter().enumerate() {
        result = result.replace(&format!("{{{i}}}"), arg);
    }
    result
}

/// Format a code snippet with a span underline.
///
/// Returns a string like:
/// ```text
/// const x = 1;
///       ^
/// ```
pub fn format_code_snippet(text: &str, span: Span, _context_lines: usize) -> String {
    let mut result = String::new();

    // Find line containing the span start
    let mut line_start = 0;
    for (i, ch) in text.char_indices() {
        if i >= span.start as usize {
            break;
        }
        if ch == '\n' {
            line_start = i + 1;
        }
    }

    // Find line end
    let line_end = text[line_start..]
        .find('\n')
        .map_or(text.len(), |i| line_start + i);

    // Get the line text
    let line_text = &text[line_start..line_end];
    result.push_str(line_text);
    result.push('\n');

    // Create underline
    let col = span.start as usize - line_start;
    let underline_len = (span.len() as usize)
        .min(line_end - span.start as usize)
        .max(1);
    result.push_str(&" ".repeat(col));
    result.push_str(&"^".repeat(underline_len));

    result
}

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

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

    #[test]
    fn test_diagnostic_severity() {
        assert_eq!(DiagnosticSeverity::Error.name(), "error");
        assert!(DiagnosticSeverity::Error.is_error());
        assert!(!DiagnosticSeverity::Warning.is_error());
        assert!(DiagnosticSeverity::Warning.is_warning());
    }

    #[test]
    fn test_diagnostic_creation() {
        let diag = Diagnostic::error("test.ts", Span::new(10, 20), "Test error", 2304);
        assert_eq!(diag.file_name, "test.ts");
        assert_eq!(diag.span, Span::new(10, 20));
        assert_eq!(diag.message, "Test error");
        assert_eq!(diag.code, 2304);
        assert!(diag.is_error());
    }

    #[test]
    fn test_diagnostic_with_related() {
        let diag =
            Diagnostic::error("test.ts", Span::new(10, 20), "Test error", 2304).with_related(
                DiagnosticRelatedInfo::new("other.ts", Span::new(5, 10), "See here"),
            );

        assert_eq!(diag.related.len(), 1);
        assert_eq!(diag.related[0].file_name, "other.ts");
    }

    #[test]
    fn test_diagnostic_format_simple() {
        let diag = Diagnostic::error("test.ts", Span::new(10, 20), "Cannot find name", 2304);
        assert_eq!(diag.format_simple(), "error[TS2304]: Cannot find name");
    }

    #[test]
    fn test_diagnostic_bag_basic() {
        let mut bag = DiagnosticBag::with_file("test.ts");
        assert!(bag.is_empty());
        assert!(!bag.has_errors());

        bag.error(Span::new(0, 5), "Error 1", 2304);
        bag.warning(Span::new(10, 15), "Warning 1", 6133);

        assert_eq!(bag.len(), 2);
        assert!(bag.has_errors());
        assert!(bag.has_warnings());
        assert_eq!(bag.error_count(), 1);
        assert_eq!(bag.warning_count(), 1);
    }

    #[test]
    fn test_diagnostic_bag_iteration() {
        let mut bag = DiagnosticBag::with_file("test.ts");
        bag.error(Span::new(0, 5), "Error 1", 2304);
        bag.error(Span::new(10, 15), "Error 2", 2322);
        bag.warning(Span::new(20, 25), "Warning 1", 6133);

        let errors: Vec<_> = bag.errors().collect();
        assert_eq!(errors.len(), 2);

        let warnings: Vec<_> = bag.warnings().collect();
        assert_eq!(warnings.len(), 1);
    }

    #[test]
    fn test_diagnostic_bag_filter_by_code() {
        let mut bag = DiagnosticBag::with_file("test.ts");
        bag.error(Span::new(0, 5), "Error 1", 2304);
        bag.error(Span::new(10, 15), "Error 2", 2322);
        bag.error(Span::new(20, 25), "Error 3", 2304);

        let code_2304: Vec<_> = bag.by_code(2304).collect();
        assert_eq!(code_2304.len(), 2);
    }

    #[test]
    fn test_diagnostic_bag_merge() {
        let mut bag1 = DiagnosticBag::with_file("test.ts");
        bag1.error(Span::new(0, 5), "Error 1", 2304);

        let mut bag2 = DiagnosticBag::with_file("other.ts");
        bag2.error(Span::new(10, 15), "Error 2", 2322);

        bag1.merge(bag2);

        assert_eq!(bag1.len(), 2);
        assert_eq!(bag1.error_count(), 2);
    }

    #[test]
    fn test_diagnostic_bag_take() {
        let mut bag = DiagnosticBag::with_file("test.ts");
        bag.error(Span::new(0, 5), "Error 1", 2304);

        let diagnostics = bag.take();
        assert_eq!(diagnostics.len(), 1);
        assert!(bag.is_empty());
        assert_eq!(bag.error_count(), 0);
    }

    #[test]
    fn test_diagnostic_bag_sort() {
        let mut bag = DiagnosticBag::new();
        bag.error_in("b.ts", Span::new(10, 15), "B error", 2304);
        bag.error_in("a.ts", Span::new(5, 10), "A error 2", 2322);
        bag.error_in("a.ts", Span::new(0, 5), "A error 1", 2304);

        bag.sort();

        let diagnostics: Vec<_> = bag.iter().collect();
        assert_eq!(diagnostics[0].file_name, "a.ts");
        assert_eq!(diagnostics[0].span.start, 0);
        assert_eq!(diagnostics[1].file_name, "a.ts");
        assert_eq!(diagnostics[1].span.start, 5);
        assert_eq!(diagnostics[2].file_name, "b.ts");
    }

    #[test]
    fn test_format_message() {
        let msg = format_message(
            "Type '{0}' is not assignable to type '{1}'.",
            &["number", "string"],
        );
        assert_eq!(msg, "Type 'number' is not assignable to type 'string'.");
    }

    #[test]
    fn test_format_code_snippet() {
        let text = "const x = 1;";
        let span = Span::new(6, 7); // "x"
        let snippet = format_code_snippet(text, span, 0);
        assert!(snippet.contains("const x = 1;"));
        assert!(snippet.contains("^"));
    }

    #[test]
    fn test_diagnostic_format_with_source() {
        let mut source = SourceFile::new("test.ts", "const x = 1;");
        let diag = Diagnostic::error("test.ts", Span::new(6, 7), "Cannot find name 'x'", 2304);
        let formatted = diag.format(&mut source);

        assert!(formatted.contains("test.ts(1,7)"));
        assert!(formatted.contains("error"));
        assert!(formatted.contains("TS2304"));
    }

    #[test]
    fn test_error_codes() {
        let mut bag = DiagnosticBag::with_file("test.ts");
        bag.error(Span::new(0, 5), "Error 1", 2304);
        bag.error(Span::new(10, 15), "Error 2", 2322);
        bag.warning(Span::new(20, 25), "Warning 1", 6133);

        let codes = bag.error_codes();
        assert_eq!(codes, vec![2304, 2322]);
    }
}