vb6parse 1.0.1

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
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
//! Module containing the error types used in the VB6 parser.
//!
//! This module is organized by the layer or file type that produces the error:
//! - [`resource`] - Form resource file (FRX) parsing errors
//! - [`class`] - Class file (CLS) specific errors
//! - [`module`] - Module file (BAS) specific errors
//! - [`project`] - Project file (VBP) specific errors
//! - [`form`] - Form file (FRM) specific errors
//! - [`lexer`] - Lexing errors
//! - [`source`] - Source file decoding errors
//!
//! The [`ErrorDetails`] type is the central error container that wraps any of these
//! error kinds along with source location information for diagnostic reporting.

use ariadne::{Label, Report, ReportKind, Source};
use core::convert::From;
use std::error::Error;
use std::fmt::{Debug, Display};

// Layer-specific error kind modules
pub mod class;
pub mod form;
pub mod lexer;
pub mod module;
pub mod project;
pub mod resource;
pub mod source;

// Re-export all error types for convenience
pub use class::ClassError;
pub use form::FormError;
pub use lexer::LexerError;
pub use module::ModuleError;
pub use project::ProjectError;
pub use resource::ResourceError;
pub use source::SourceFileError;

/// Hierarchical error kind enum that wraps layer-specific error types.
///
/// This enum organizes parsing errors by the layer that produces them,
/// providing better organization and clearer error categorization.
/// Each variant wraps a layer-specific error enum:
///
/// - `Lexer` - Tokenization and lexical analysis errors  
/// - `Class` - Class file (.cls) specific parsing errors
/// - `Module` - Module file (.bas) specific parsing errors
/// - `Form` - Form file (.frm) validation and parsing errors
/// - `Project` - Project file (.vbp) parsing errors
/// - `Resource` - Resource file (.frx) binary data errors
/// - `SourceFile` - File encoding and decoding errors
///
/// # Ergonomic Conversions
///
/// All layer-specific error types implement `From` conversion to `ErrorKind`,
/// allowing automatic conversion. The [`ParserContext`] and [`ErrorDetails::basic()`]
/// accept any type that implements `Into<ErrorKind>`, so you can pass layer-specific
/// errors directly without wrapping:
///
/// ```rust
/// use vb6parse::io::SourceStream;
/// use vb6parse::errors::{ParserContext, ErrorKind, LexerError, ModuleError};
///
/// let stream = SourceStream::new("test.bas", "Dim x");
/// let mut ctx = ParserContext::new(stream.file_name(), stream.contents);
///
/// // Automatic conversion from layer-specific errors:
/// ctx.error(stream.span_here(), LexerError::UnknownToken {
///     token: "???".to_string()
/// });
///
/// // Works with all layer-specific error types:
/// ctx.error(stream.span_here(), ModuleError::AttributeKeywordMissing);
/// ```
///
/// [`ParserContext`]: crate::errors::ParserContext
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
    /// Lexer and tokenization errors.
    #[error(transparent)]
    Lexer(#[from] LexerError),

    /// Class file parsing errors.
    #[error(transparent)]
    Class(#[from] ClassError),

    /// Module file parsing errors.
    #[error(transparent)]
    Module(#[from] ModuleError),

    /// Form file parsing and validation errors.
    #[error(transparent)]
    Form(#[from] FormError),

    /// Project file parsing errors.
    #[error(transparent)]
    Project(#[from] ProjectError),

    /// Resource file parsing errors.
    #[error(transparent)]
    Resource(#[from] ResourceError),

    /// Source file decoding errors.
    #[error(transparent)]
    SourceFile(#[from] SourceFileError),
}

/// Represents the severity level of a parsing diagnostic.
///
/// This enum is used to distinguish between different types of issues
/// encountered during parsing, from informational notes to fatal errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum Severity {
    /// Informational message, not a problem.
    Note,
    /// Potential issue that should be addressed but doesn't prevent usage.
    Warning,
    /// Fatal error that prevents successful parsing or usage.
    #[default]
    Error,
}

impl Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Note => write!(f, "note"),
            Severity::Warning => write!(f, "warning"),
            Severity::Error => write!(f, "error"),
        }
    }
}

/// Represents a span of source code, typically associated with an error or diagnostic.
///
/// A span identifies a region in the source code by offset, line numbers, and length.
/// This is used to highlight the exact location of errors in diagnostic messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Span {
    /// The byte offset into the source content where this span starts.
    pub offset: u32,
    /// The starting line number (1-based).
    pub line_start: u32,
    /// The ending line number (1-based).
    pub line_end: u32,
    /// The length of this span in bytes.
    pub length: u32,
}

impl Span {
    /// Creates a new span.
    #[must_use]
    pub fn new(offset: u32, line_start: u32, line_end: u32, length: u32) -> Self {
        Self {
            offset,
            line_start,
            line_end,
            length,
        }
    }

    /// Creates a zero-length span at offset 0.
    #[must_use]
    pub fn zero() -> Self {
        Self {
            offset: 0,
            line_start: 0,
            line_end: 0,
            length: 0,
        }
    }

    /// Creates a span of length 1 at the given offset and line.
    #[must_use]
    pub fn at(offset: u32, line: u32) -> Self {
        Self {
            offset,
            line_start: line,
            line_end: line,
            length: 1,
        }
    }
}

/// Represents a labeled span in a multi-span diagnostic.
///
/// Labels are used to annotate multiple locations in the source code
/// within a single error message, providing context for complex errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticLabel {
    /// The span this label refers to.
    pub span: Span,
    /// The message to display for this label.
    pub message: String,
}

impl DiagnosticLabel {
    /// Creates a new label.
    pub fn new(span: Span, message: impl Into<String>) -> Self {
        Self {
            span,
            message: message.into(),
        }
    }
}

/// Contains detailed information about an error that occurred during parsing.
///
/// This struct contains the source name, source content, error offset,
/// line start and end positions, and the kind of error. All errors now use
/// the unified [`ErrorKind`] type.
///
/// Example usage:
/// ```rust
/// use vb6parse::errors::{ErrorDetails, ErrorKind, Severity, LexerError};
///
/// let error_details = ErrorDetails {
///     source_name: "example.cls".to_string().into_boxed_str(),
///     source_content: "Some VB6 code here...",
///     error_offset: 10,
///     line_start: 1,
///     line_end: 1,
///     kind: Box::new(ErrorKind::Lexer(LexerError::UnknownToken { token: "???".to_string() })),
///     severity: Severity::Error,
///     labels: vec![],
///     notes: vec![],
/// };
/// error_details.print();
/// ```
#[derive(Debug, Clone)]
pub struct ErrorDetails<'a> {
    /// The name of the source file where the error occurred.
    pub source_name: Box<str>,
    /// The content of the source file where the error occurred.
    pub source_content: &'a str,
    /// The offset in the source content where the error occurred.
    ///
    /// Note: This is a u32 to reflect VB6's 32-bit addressing limitations.
    pub error_offset: u32,
    /// The starting line number of the error.
    ///
    /// Note: This is a u32 to reflect VB6's 32-bit addressing limitations.
    pub line_start: u32,
    /// The ending line number of the error.
    ///
    /// Note: This is a u32 to reflect VB6's 32-bit addressing limitations.
    pub line_end: u32,
    /// The kind of error that occurred.
    /// Boxed to reduce the size of `Result<T, ErrorDetails>` on the stack.
    pub kind: Box<ErrorKind>,
    /// The severity of this diagnostic (`Error`, `Warning`, or `Note`).
    pub severity: Severity,
    /// Additional labeled spans for multi-span diagnostics.
    /// This allows annotating multiple locations in the source code
    /// within a single error message.
    pub labels: Vec<DiagnosticLabel>,
    /// Additional notes to provide context for this diagnostic.
    /// These are displayed after the main error message.
    pub notes: Vec<String>,
}

impl<'a> ErrorDetails<'a> {
    /// Creates a basic `ErrorDetails` with no labels or notes.
    ///
    /// This is a convenience constructor for the common case where
    /// only the basic error information is needed.
    ///
    /// Accepts any error type that can be converted to `ErrorKind`, including
    /// layer-specific errors like `LexerError`, `ModuleError`, `ProjectError`, etc.
    #[must_use]
    pub fn basic<E>(
        source_name: Box<str>,
        source_content: &'a str,
        error_offset: u32,
        line_start: u32,
        line_end: u32,
        kind: E,
        severity: Severity,
    ) -> ErrorDetails<'a>
    where
        E: Into<ErrorKind>,
    {
        ErrorDetails {
            source_name,
            source_content,
            error_offset,
            line_start,
            line_end,
            kind: Box::new(kind.into()),
            severity,
            labels: Vec::new(),
            notes: Vec::new(),
        }
    }

    /// Adds a labeled span to this error.
    #[must_use]
    pub fn with_label(mut self, label: DiagnosticLabel) -> Self {
        self.labels.push(label);
        self
    }

    /// Adds multiple labeled spans to this error.
    #[must_use]
    pub fn with_labels(mut self, labels: Vec<DiagnosticLabel>) -> Self {
        self.labels.extend(labels);
        self
    }

    /// Adds a note to this error.
    #[must_use]
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    /// Adds multiple notes to this error.
    #[must_use]
    pub fn with_notes(mut self, notes: Vec<String>) -> Self {
        self.notes.extend(notes);
        self
    }

    /// Emit this error by pushing it to the provided parser context.
    ///
    /// This is a terminal operation that consumes the error and adds it
    /// to the context's error collection.
    ///
    /// # Example
    /// ```rust
    /// use vb6parse::errors::{ParserContext, DiagnosticLabel, LexerError, Span};
    ///
    /// let mut ctx = ParserContext::new("test.bas", "Dim x");
    /// let span = Span::at(0, 1);
    /// let label_span = Span::at(4, 1);
    ///
    /// ctx.error_with(span, LexerError::UnknownToken { token: "x".to_string() })
    ///     .with_label(DiagnosticLabel::new(label_span, "here"))
    ///     .with_note("Consider using 'Integer' instead")
    ///     .emit(&mut ctx);
    /// ```
    pub fn emit(self, ctx: &mut ParserContext<'a>) {
        ctx.push_error(self);
    }
}

impl Display for ErrorDetails<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ErrorDetails {{ source_name: {}, error_offset: {}, line_start: {}, line_end: {}, kind: {:?} }}",
            self.source_name,
            self.error_offset,
            self.line_start,
            self.line_end,
            self.kind,
        )
    }
}

impl ErrorDetails<'_> {
    /// Print the `ErrorDetails` using ariadne for formatting.
    ///
    /// Example usage:
    /// ```rust
    /// use vb6parse::errors::{ErrorDetails, ErrorKind, Severity, LexerError};
    ///
    /// let error_details = ErrorDetails {
    ///     source_name: "example.cls".to_string().into_boxed_str(),
    ///     source_content: "Some VB6 code here...",
    ///     error_offset: 10,
    ///     line_start: 1,
    ///     line_end: 1,
    ///     kind: Box::new(ErrorKind::Lexer(LexerError::UnknownToken { token: "???".to_string() })),
    ///     severity: Severity::Error,
    ///     labels: vec![],
    ///     notes: vec![],
    /// };
    /// error_details.print();
    /// ```
    pub fn print(&self) {
        let cache = (
            self.source_name.to_string(),
            Source::from(self.source_content),
        );

        let mut report = Report::build(
            ReportKind::Error,
            (
                self.source_name.to_string(),
                self.line_start as usize..=self.line_end as usize,
            ),
        )
        .with_message(self.kind.to_string());

        // Add custom labels if provided, otherwise add a default label
        if self.labels.is_empty() {
            let span_start = self.error_offset as usize;
            let span_end = self.error_offset as usize;

            report = report.with_label(
                Label::new((self.source_name.to_string(), span_start..=span_end))
                    .with_message("error here"),
            );
        } else {
            for label in &self.labels {
                let span_start = label.span.offset as usize;
                let span_end = (label.span.offset + label.span.length.max(1) - 1) as usize;

                report = report.with_label(
                    Label::new((self.source_name.to_string(), span_start..=span_end))
                        .with_message(&label.message),
                );
            }
        }

        // Add notes
        for note in &self.notes {
            report = report.with_note(note);
        }

        let result = report.finish().print(cache);

        if let Some(e) = result.err() {
            eprint!("Error attempting to build ErrorDetails print message {e:?}");
        }
    }

    /// Eprint the `ErrorDetails` using ariadne for formatting.
    ///
    /// Example usage:
    /// ```rust
    /// use vb6parse::errors::{ErrorDetails, ErrorKind, Severity, LexerError};
    ///
    /// let error_details = ErrorDetails {
    ///     source_name: "example.cls".to_string().into_boxed_str(),
    ///     source_content: "Some VB6 code here...",
    ///     error_offset: 10,
    ///     line_start: 1,
    ///     line_end: 1,
    ///     kind: Box::new(ErrorKind::Lexer(LexerError::UnknownToken {
    ///         token: "???".to_string(),
    ///     })),
    ///     severity: Severity::Error,
    ///     labels: vec![],
    ///     notes: vec![],
    /// };
    /// error_details.eprint();
    /// ```
    pub fn eprint(&self) {
        let cache = (
            self.source_name.to_string(),
            Source::from(self.source_content),
        );

        let mut report = Report::build(
            ReportKind::Error,
            (
                self.source_name.to_string(),
                self.line_start as usize..=self.line_end as usize,
            ),
        )
        .with_message(format!("{:?}", self.kind));

        // Add custom labels if provided, otherwise add a default label
        if self.labels.is_empty() {
            report = report.with_label(
                Label::new((
                    self.source_name.to_string(),
                    self.error_offset as usize..=self.error_offset as usize,
                ))
                .with_message("error here"),
            );
        } else {
            for label in &self.labels {
                report = report.with_label(
                    Label::new((
                        self.source_name.to_string(),
                        label.span.offset as usize
                            ..=(label.span.offset + label.span.length.max(1) - 1) as usize,
                    ))
                    .with_message(&label.message),
                );
            }
        }

        // Add notes
        for note in &self.notes {
            report = report.with_note(note);
        }

        let result = report.finish().eprint(cache);

        if let Some(e) = result.err() {
            eprint!("Error attempting to build ErrorDetails eprint message {e:?}");
        }
    }

    /// Convert the `ErrorDetails` into a string using ariadne for formatting
    ///
    /// # Errors
    /// This function will return an error if there is an issue converting the
    /// formatted report into a UTF-8 string.
    pub fn print_to_string(&self) -> Result<String, Box<dyn Error>> {
        let cache = (
            self.source_name.to_string(),
            Source::from(self.source_content),
        );

        let mut buf = Vec::new();

        let mut report = Report::build(
            ReportKind::Error,
            (
                self.source_name.to_string(),
                self.line_start as usize..=self.line_end as usize,
            ),
        )
        .with_message(self.kind.to_string());

        // Add custom labels if provided, otherwise add a default label
        if self.labels.is_empty() {
            report = report.with_label(
                Label::new((
                    self.source_name.to_string(),
                    self.error_offset as usize..=self.error_offset as usize,
                ))
                .with_message("error here"),
            );
        } else {
            for label in &self.labels {
                report = report.with_label(
                    Label::new((
                        self.source_name.to_string(),
                        label.span.offset as usize
                            ..=(label.span.offset + label.span.length.max(1) - 1) as usize,
                    ))
                    .with_message(&label.message),
                );
            }
        }

        let _ = report.finish().write(cache, &mut buf);

        let text = String::from_utf8(buf.clone())?;

        Ok(text)
    }
}

/// A context for creating errors during parsing.
///
/// `ParserContext` centralizes error creation and collection during parsing operations.
/// Instead of having error generation methods on `SourceStream`, parsers should use
/// `ParserContext` to create and accumulate errors and warnings.
///
/// # Example
/// ```rust
/// use vb6parse::errors::{ParserContext, LexerError};
/// use vb6parse::io::SourceStream;
///
/// let stream = SourceStream::new("test.bas", "Dim x As Integer");
/// let mut ctx = ParserContext::new(stream.file_name(), stream.contents);
///
/// // Create an error at a specific span
/// let span = stream.span_here();
/// ctx.error(span, LexerError::UnknownToken { token: "???".to_string() });
///
/// // Check if any errors occurred
/// if ctx.has_errors() {
///     println!("Found {} errors", ctx.error_count());
/// }
/// ```
#[derive(Debug)]
pub struct ParserContext<'a> {
    file_name: String,
    contents: &'a str,
    errors: Vec<ErrorDetails<'a>>,
}

impl<'a> ParserContext<'a> {
    /// Create a new parser context for the given file.
    ///
    /// # Arguments
    /// * `file_name` - The name of the source file being parsed
    /// * `contents` - The contents of the source file
    pub fn new<S: Into<String>>(file_name: S, contents: &'a str) -> Self {
        Self {
            file_name: file_name.into(),
            contents,
            errors: Vec::new(),
        }
    }

    /// Create an error at the given span with the specified error kind.
    ///
    /// Accepts any error type that can be converted to `ErrorKind`, including
    /// layer-specific errors like `LexerError`, `ModuleError`, `ProjectError`, etc.
    ///
    /// # Arguments
    /// * `span` - The location of the error in the source
    /// * `kind` - The error kind (automatically converted to `ErrorKind`)
    pub fn error<E>(&mut self, span: Span, kind: E)
    where
        E: Into<ErrorKind>,
    {
        let error = ErrorDetails {
            source_name: self.file_name.clone().into_boxed_str(),
            source_content: self.contents,
            error_offset: span.offset,
            line_start: span.line_start,
            line_end: span.line_end,
            kind: Box::new(kind.into()),
            severity: Severity::Error,
            labels: vec![],
            notes: vec![],
        };
        self.errors.push(error);
    }

    /// Create an error at the given span and return it for further customization.
    ///
    /// This allows adding labels, notes, or changing severity before the error
    /// is added to the context.
    ///
    /// # Arguments
    /// * `span` - The location of the error in the source
    /// * `kind` - The error kind (automatically converted to `ErrorKind`)
    ///
    /// # Returns
    /// An `ErrorDetails` that can be customized with `.with_label()`, `.with_note()`, etc.
    ///
    /// # Example
    /// ```rust
    /// use vb6parse::errors::{ParserContext, DiagnosticLabel, LexerError, Span};
    ///
    /// let mut ctx = ParserContext::new("test.bas", "Dim x");
    /// let span = Span::at(0, 1);
    /// let label_span = Span::at(4, 1);
    ///
    /// ctx.error_with(span, LexerError::UnknownToken { token: "x".to_string() })
    ///     .with_label(DiagnosticLabel::new(label_span, "here"))
    ///     .with_note("Consider using 'Integer' instead")
    ///     .emit(&mut ctx);
    /// ```
    pub fn error_with<E>(&self, span: Span, kind: E) -> ErrorDetails<'a>
    where
        E: Into<ErrorKind>,
    {
        ErrorDetails {
            source_name: self.file_name.clone().into_boxed_str(),
            source_content: self.contents,
            error_offset: span.offset,
            line_start: span.line_start,
            line_end: span.line_end,
            kind: Box::new(kind.into()),
            severity: Severity::Error,
            labels: vec![],
            notes: vec![],
        }
    }

    /// Manually push a pre-constructed error to the context.
    ///
    /// This is useful when you've built an error with additional labels or notes
    /// using `error_with()` or `ErrorDetails::basic()`.
    pub fn push_error(&mut self, error: ErrorDetails<'a>) {
        self.errors.push(error);
    }

    /// Extend the error list with multiple errors.
    pub fn extend_errors(&mut self, errors: impl IntoIterator<Item = ErrorDetails<'a>>) {
        self.errors.extend(errors);
    }

    /// Check if any errors have been recorded.
    #[must_use]
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Get the number of errors recorded.
    #[must_use]
    pub fn error_count(&self) -> usize {
        self.errors.len()
    }

    /// Get a reference to all errors.
    #[must_use]
    pub fn errors(&self) -> &[ErrorDetails<'a>] {
        &self.errors
    }

    /// Take all errors, leaving the context empty.
    ///
    /// This allows collecting errors without consuming the context.
    pub fn take_errors(&mut self) -> Vec<ErrorDetails<'a>> {
        std::mem::take(&mut self.errors)
    }

    /// Consume the context and return all errors.
    #[must_use]
    pub fn into_errors(self) -> Vec<ErrorDetails<'a>> {
        self.errors
    }

    /// Get the file name.
    #[must_use]
    pub fn file_name(&self) -> &str {
        &self.file_name
    }

    /// Get the contents.
    #[must_use]
    pub fn contents(&self) -> &'a str {
        self.contents
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::SourceStream;
    use assert_matches::assert_matches;

    #[test]
    fn test_automatic_error_conversion() {
        // Test that layer-specific errors can be automatically converted to ErrorKind
        // and used with ParserContext

        let stream = SourceStream::new("test.bas", "Dim x As Integer");
        let mut ctx = ParserContext::new(stream.file_name(), stream.contents);

        // Test with LexerError
        ctx.error(
            stream.span_here(),
            LexerError::UnknownToken {
                token: "???".to_string(),
            },
        );

        // Test with ModuleError
        ctx.error(stream.span_here(), ModuleError::AttributeKeywordMissing);

        // Test with ClassError
        ctx.error(stream.span_here(), ClassError::VersionKeywordMissing);

        // Test with ProjectError
        ctx.error(stream.span_here(), ProjectError::UnterminatedSectionHeader);

        // Test that ErrorDetails::basic also accepts layer-specific errors
        let _error5 = ErrorDetails::basic(
            "test.bas".to_string().into_boxed_str(),
            "Dim x",
            0,
            0,
            5,
            FormError::VersionKeywordMissing,
            Severity::Error,
        );

        // Verify errors were collected
        assert_eq!(ctx.error_count(), 4);
        assert!(ctx.has_errors());
    }

    #[test]
    fn test_error_kind_conversion() {
        // Test that Into<ErrorKind> works for all layer-specific error types
        let lexer_err: ErrorKind = LexerError::UnknownToken {
            token: "test".to_string(),
        }
        .into();
        assert_matches!(lexer_err, ErrorKind::Lexer(_));

        let module_err: ErrorKind = ModuleError::AttributeKeywordMissing.into();
        assert_matches!(module_err, ErrorKind::Module(_));

        let class_err: ErrorKind = ClassError::VersionKeywordMissing.into();
        assert_matches!(class_err, ErrorKind::Class(_));

        let project_err: ErrorKind = ProjectError::UnterminatedSectionHeader.into();
        assert_matches!(project_err, ErrorKind::Project(_));

        let form_err: ErrorKind = FormError::VersionKeywordMissing.into();
        assert_matches!(form_err, ErrorKind::Form(_));

        let resource_err: ErrorKind = ResourceError::OffsetOutOfBounds {
            offset: 0,
            file_length: 10,
        }
        .into();
        assert_matches!(resource_err, ErrorKind::Resource(_));

        let source_err: ErrorKind = SourceFileError::Malformed {
            message: "test".to_string(),
        }
        .into();
        assert_matches!(source_err, ErrorKind::SourceFile(_));
    }
}