vos_error/errors/report/
mod.rs

1use diagnostic::{
2    term::{
3        emit,
4        termcolor::{ColorChoice, StandardStream},
5        TerminalConfig,
6    },
7    Diagnostic, DiagnosticLevel, FileID, TextStorage,
8};
9
10use crate::{DuplicateDeclare, Validation, VosError, VosErrorKind, VosResult};
11
12impl VosError {
13    pub fn with_level(mut self, level: DiagnosticLevel) -> Self {
14        self.level = level;
15        self
16    }
17
18    pub fn info(&mut self) {
19        self.level = DiagnosticLevel::Info;
20    }
21    pub fn error(&mut self) {
22        self.level = DiagnosticLevel::Error;
23    }
24    pub fn warning(&mut self) {
25        self.level = DiagnosticLevel::Warning;
26    }
27    pub fn fatal(&mut self) {
28        self.level = DiagnosticLevel::Fatal;
29    }
30}
31
32pub fn eprint<T>(v: &Validation<T>, text: &TextStorage) -> VosResult {
33    let c = TerminalConfig::default();
34    let w: StandardStream = StandardStream::stderr(ColorChoice::Always);
35    for diagnostic in v.collect_diagnostics() {
36        emit(&mut w.lock(), &c, text, &diagnostic)?
37    }
38    Ok(())
39}
40
41impl From<&VosError> for Diagnostic {
42    fn from(value: &VosError) -> Self {
43        match value.kind() {
44            VosErrorKind::IOError(e) => {
45                Diagnostic::new(value.level).with_code("A0002").with_message(e).with_primary(&value.file, 0..0, "IOError")
46            }
47            VosErrorKind::ParseError(e) => {
48                Diagnostic::new(value.level).with_code("A0002").with_message(e).with_primary(&value.file, 0..0, "ParseError")
49            }
50            VosErrorKind::RuntimeError(e) => {
51                Diagnostic::new(value.level).with_code("A0002").with_message(e).with_primary(&value.file, 0..0, "RuntimeError")
52            }
53            VosErrorKind::DuplicateFields(e) => e.as_report(value.level, &value.file),
54            VosErrorKind::UnknownError => Diagnostic::new(value.level)
55                .with_code("A0002")
56                .with_message("UnknownError")
57                .with_primary(&value.file, 0..0, "DuplicateFields"),
58        }
59    }
60}
61
62impl DuplicateDeclare {
63    pub fn as_report(&self, level: DiagnosticLevel, file: &FileID) -> Diagnostic {
64        let message = format!("Duplicate {}", self.kind);
65        let primary = format!("{} first declared here", self.kind);
66        let secondary = format!("{} duplicate declared here again", self.kind);
67        Diagnostic::new(level) //
68            .with_message(message)
69            .with_primary(file, self.lhs.clone(), primary)
70            .with_secondary(file, self.rhs.clone(), secondary)
71    }
72}