use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
pub code: &'static str,
pub message: String,
pub line: Option<usize>,
}
impl Error {
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
line: None,
}
}
#[must_use]
pub fn at(mut self, line: usize) -> Self {
self.line = Some(line);
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.code)?;
if let Some(line) = self.line {
write!(f, " at line {line}")?;
}
write!(f, ": {}", self.message)
}
}
impl std::error::Error for Error {}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::new("E_IO", value.to_string())
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
pub severity: Severity,
pub code: &'static str,
pub message: String,
pub line: Option<usize>,
}
impl From<Error> for Diagnostic {
fn from(error: Error) -> Self {
Self {
severity: Severity::Error,
code: error.code,
message: error.message,
line: error.line,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ValidationReport {
pub diagnostics: Vec<Diagnostic>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_display_carries_line() {
assert_eq!(
Error::new("E_TEST", "bad field").at(3).to_string(),
"E_TEST at line 3: bad field"
);
}
}