//! Stable diagnostic codes and source locations. use serde_json::Value; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Severity { Error, Warning, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Span { pub start: usize, pub end: usize, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Diagnostic { pub code: &'static str, pub severity: Severity, pub message: String, pub path: Option, pub anchor: Option, pub span: Option, } impl Diagnostic { pub fn error(code: &'static str, message: impl Into) -> Self { Self { code, severity: Severity::Error, message: message.into(), path: None, anchor: None, span: None, } } pub fn at(mut self, path: impl Into, span: Option<(usize, usize)>) -> Self { self.path = Some(path.into()); self.span = span.map(|(start, end)| Span { start, end }); self } pub fn with_anchor(mut self, anchor: impl Into) -> Self { self.anchor = Some(anchor.into()); self } } pub type Diagnostics = Vec; #[derive(Debug, Clone)] pub enum LoadError { /// The CLI/engine/protocol failed; hosts map this to exit code 2. Engine(Diagnostics), /// The author document violates the design contract; hosts map this to exit code 1. Design(Diagnostics), } impl From for LoadError { fn from(diagnostic: Diagnostic) -> Self { LoadError::Design(vec![diagnostic]) } } impl LoadError { pub fn diagnostics(&self) -> &Diagnostics { match self { Self::Engine(items) | Self::Design(items) => items, } } pub fn into_diagnostics(self) -> Diagnostics { match self { Self::Engine(items) | Self::Design(items) => items, } } } pub(crate) fn span_from(value: &Value) -> Option<(usize, usize)> { Some(( value.get("start")?.as_u64()? as usize, value.get("end")?.as_u64()? as usize, )) }