use std::error::Error; use std::fmt; /// Half-open UTF-8 byte range in the original source, including trivia between /// the first and last syntax token. EOF has an empty range at source.len(). #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct Span { pub start: usize, pub end: usize, } impl Span { pub const fn new(start: usize, end: usize) -> Self { Self { start, end } } /// Safely read this range, rejecting reversed, out-of-bounds or split UTF-8 ranges. pub fn slice(self, source: &str) -> Option<&str> { source.get(self.start..self.end) } pub fn location(self, source: &str) -> Option { self.slice(source)?; Some(source_location(source, self.start)) } pub(crate) fn through(self, last: Self) -> Self { Self::new(self.start, last.end) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DiagnosticKind { Lexical, Syntax, Semantic, Compilation, } /// Lines and Unicode scalar columns are one-based. CRLF counts as one newline. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SourceLocation { pub line: usize, pub column: usize, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Diagnostic { pub kind: DiagnosticKind, pub span: Span, pub message: String, pub expected: Vec, } impl Diagnostic { pub(crate) fn lexical(span: Span, message: impl Into) -> Self { Self { kind: DiagnosticKind::Lexical, span, message: message.into(), expected: Vec::new(), } } pub fn location(&self, source: &str) -> SourceLocation { source_location(source, self.span.start) } } impl fmt::Display for Diagnostic { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!( formatter, "{} at bytes {}..{}", self.message, self.span.start, self.span.end ) } } impl Error for Diagnostic {} fn source_location(source: &str, position: usize) -> SourceLocation { let mut location = SourceLocation { line: 1, column: 1 }; let mut previous_cr = false; for (offset, character) in source.char_indices() { if offset >= position { break; } match character { '\r' => { location.line += 1; location.column = 1; } '\n' if previous_cr => {} '\n' => { location.line += 1; location.column = 1; } _ => location.column += 1, } previous_cr = character == '\r'; } location }