use crate::value::Value;
#[derive(Debug, Clone)]
pub enum InterpError {
Runtime(String),
SourceCode(String),
Return(Value),
Break(Option<String>),
Continue(Option<String>),
Throw(Value),
PatternMatch(String),
SyncYieldLimit,
Unimplemented(String),
AsyncSuspensionOutsideAsync,
Suspend,
}
impl InterpError {
pub fn runtime(msg: impl Into<String>) -> Self {
InterpError::Runtime(msg.into())
}
pub fn unimplemented(msg: impl Into<String>) -> Self {
InterpError::Unimplemented(msg.into())
}
pub fn throw_argument_error(message: impl Into<String>, invalid_value: Value) -> Self {
InterpError::Throw(crate::stdlib::helpers::wrap(
&crate::stdlib::helpers::class("ArgumentError"),
Value::List(std::rc::Rc::new(std::cell::RefCell::new(vec![
Value::str(message),
invalid_value,
]))),
))
}
pub fn throw_range_error(message: impl Into<String>, invalid_value: Value) -> Self {
InterpError::Throw(crate::stdlib::helpers::wrap(
&crate::stdlib::helpers::class("RangeError"),
Value::List(std::rc::Rc::new(std::cell::RefCell::new(vec![
Value::str(message),
invalid_value,
]))),
))
}
pub fn message(&self) -> Option<&str> {
match self {
InterpError::Runtime(m) | InterpError::SourceCode(m) | InterpError::PatternMatch(m) => {
Some(m)
}
_ => None,
}
}
}
impl std::fmt::Display for InterpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InterpError::Runtime(m) => write!(f, "Runtime Error: {m}"),
InterpError::SourceCode(m) => write!(f, "SourceCodeException: {m}"),
InterpError::Return(_) => write!(f, "ReturnException"),
InterpError::Break(l) => write!(f, "BreakException(label: {l:?})"),
InterpError::Continue(l) => write!(f, "ContinueException(label: {l:?})"),
InterpError::Throw(_) => write!(f, "InternalInterpreterException"),
InterpError::PatternMatch(m) => write!(f, "PatternMatchException: {m}"),
InterpError::SyncYieldLimit => write!(f, "SyncGeneratorYieldLimitReached"),
InterpError::Unimplemented(m) => write!(f, "UnimplementedError: {m}"),
InterpError::AsyncSuspensionOutsideAsync => {
write!(f, "StateError: suspension outside async context")
}
InterpError::Suspend => write!(f, "InternalAsyncSuspension"),
}
}
}
impl std::error::Error for InterpError {}
impl From<InterpError> for crate::value::Value {
fn from(_: InterpError) -> Self {
unreachable!()
}
}
pub fn is_control_flow(err: &InterpError) -> bool {
matches!(
err,
InterpError::Return(_)
| InterpError::Break(_)
| InterpError::Continue(_)
| InterpError::SyncYieldLimit
)
}