1use crate::SourceSpan;
4use std::fmt;
5
6#[derive(Clone, Debug, Eq, PartialEq)]
8#[non_exhaustive]
9pub enum SourceError {
10 Lex(LexError),
12 Parse(ParseError),
14}
15
16#[derive(Clone, Debug, Eq, PartialEq)]
18#[non_exhaustive]
19pub struct LexError {
20 pub span: SourceSpan,
22 pub message: String,
24}
25
26#[derive(Clone, Debug, Eq, PartialEq)]
28#[non_exhaustive]
29pub struct ParseError {
30 pub unclosed_block: Option<Box<UnclosedBlock>>,
32 pub span: SourceSpan,
34 pub message: String,
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub struct UnclosedBlock {
42 pub start: usize,
44 pub expected: &'static str,
46}
47
48#[derive(Clone, Debug, Eq, PartialEq)]
50#[non_exhaustive]
51pub struct CompileError {
52 pub span: Option<SourceSpan>,
54 pub message: String,
56}
57
58impl SourceError {
59 pub(crate) fn from_core(error: rustia_parser::SourceError) -> Self {
60 match error {
61 rustia_parser::SourceError::Lex(error) => Self::Lex(LexError {
62 span: SourceSpan::from_lexer(error.span),
63 message: error.message,
64 }),
65 rustia_parser::SourceError::Parse(error) => Self::Parse(ParseError {
66 unclosed_block: error.unclosed_block.map(|block| {
67 Box::new(UnclosedBlock {
68 start: block.start,
69 expected: block.expected,
70 })
71 }),
72 span: SourceSpan::from_lexer(error.span),
73 message: error.message,
74 }),
75 }
76 }
77}
78
79impl CompileError {
80 pub(crate) fn from_core(error: rustia_compiler::CompileError) -> Self {
81 Self {
82 span: error.span.map(SourceSpan::from_lexer),
83 message: error.message,
84 }
85 }
86}
87
88impl fmt::Display for SourceError {
89 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90 match self {
91 Self::Lex(error) => error.fmt(formatter),
92 Self::Parse(error) => error.fmt(formatter),
93 }
94 }
95}
96
97impl fmt::Display for LexError {
98 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(
100 formatter,
101 "lex error at {}..{}: {}",
102 self.span.start, self.span.end, self.message
103 )
104 }
105}
106
107impl fmt::Display for ParseError {
108 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(
110 formatter,
111 "parse error at {}..{}: {}",
112 self.span.start, self.span.end, self.message
113 )
114 }
115}
116
117impl fmt::Display for CompileError {
118 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119 if let Some(span) = self.span {
120 write!(
121 formatter,
122 "compile error at {}..{}: {}",
123 span.start, span.end, self.message
124 )
125 } else {
126 write!(formatter, "compile error: {}", self.message)
127 }
128 }
129}
130
131impl std::error::Error for SourceError {}
132impl std::error::Error for LexError {}
133impl std::error::Error for ParseError {}
134impl std::error::Error for CompileError {}