sphinx/codegen/errors.rs
1use core::fmt;
2use std::error::Error;
3
4use crate::utils;
5use crate::debug::{DebugSymbol, SourceError};
6
7
8pub type CompileResult<T> = Result<T, CompileError>;
9
10#[derive(Debug)]
11pub struct CompileError {
12 message: String,
13 symbol: Option<DebugSymbol>,
14 cause: Option<Box<dyn Error>>,
15}
16
17impl CompileError {
18 pub fn new(message: &str) -> Self {
19 Self { message: message.to_string(), symbol: None, cause: None }
20 }
21
22 pub fn with_symbol(mut self, symbol: DebugSymbol) -> Self {
23 self.symbol.get_or_insert(symbol); self
24 }
25
26 pub fn caused_by(mut self, error: impl Error + 'static) -> Self {
27 self.cause.replace(Box::new(error)); self
28 }
29}
30
31impl<S> From<S> for CompileError where S: AsRef<str> {
32 fn from(message: S) -> Self {
33 Self::new(message.as_ref())
34 }
35}
36
37impl Error for CompileError {
38 fn source(&self) -> Option<&(dyn Error + 'static)> {
39 self.cause.as_ref().map(|o| o.as_ref())
40 }
41}
42
43impl SourceError for CompileError {
44 fn debug_symbol(&self) -> Option<&DebugSymbol> { self.symbol.as_ref() }
45}
46
47impl fmt::Display for CompileError {
48 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
49
50 // let message = match self.kind() {
51 // ErrorKind::CantAssignImmutable => "can't assign to immutable local variable",
52 // ErrorKind::CantAssignNonLocal => "can't assign to a non-local variable without the \"nonlocal\" keyword",
53 // ErrorKind::TupleLenMismatch => "can't assign tuples of different lengths",
54 // ErrorKind::CantUpdateAssignTuple => "can't use update-assigment when assigning to a tuple",
55
56 // ErrorKind::CantResolveBreak(label) =>
57 // if label.is_some() { "can't find loop or block with matching label for \"break\"" }
58 // else { "\"break\" outside of loop or block" },
59
60 // ErrorKind::CantResolveContinue(label) =>
61 // if label.is_some() { "can't find loop with matching label for \"continue;\"" }
62 // else { "\"continue\" outside of loop" },
63
64 // ErrorKind::InvalidBreakWithValue => "\"break\" with value outside of block expression",
65 // ErrorKind::InvalidLValueModifier => "assignment modifier is not allowed here",
66 // ErrorKind::InternalLimit(message) => message,
67 // };
68
69 let message =
70 if self.message.is_empty() { None }
71 else { Some(self.message.as_str()) };
72
73 utils::format_error(fmt, "Compile error", message, self.source())
74 }
75}