1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use core::fmt;
use std::error::Error;
use crate::utils;
use crate::runtime::Variant;
use crate::runtime::function::Signature;
use crate::runtime::gc::GcTrace;
use crate::runtime::types::{Type, MethodTag};
use crate::runtime::strings::StringSymbol;
use crate::debug::traceback::{TraceSite, Traceback};
pub type ExecResult<T> = Result<T, Box<RuntimeError>>;
#[derive(Debug)]
pub enum ErrorKind {
InvalidUnaryOperand(Type),
InvalidBinaryOperand(Type, Type),
OverflowError,
DivideByZero,
NegativeShiftCount,
NameNotDefined(String),
CantAssignImmutable,
UnhashableValue(Variant),
MissingArguments { signature: Box<Signature>, nargs: usize },
TooManyArguments { signature: Box<Signature>, nargs: usize },
MethodNotSupported(Type, MethodTag),
AssertFailed,
StaticMessage(&'static str),
Message(String),
}
impl From<ErrorKind> for RuntimeError {
fn from(kind: ErrorKind) -> Self {
RuntimeError { kind, traceback: Vec::new(), cause: None }
}
}
impl From<ErrorKind> for Box<RuntimeError> {
fn from(kind: ErrorKind) -> Self {
Box::new(kind.into())
}
}
unsafe impl GcTrace for ErrorKind {
fn trace(&self) {
match self {
Self::UnhashableValue(value) => value.trace(),
_ => { },
}
}
fn size_hint(&self) -> usize {
match self {
Self::MissingArguments { .. } => core::mem::size_of::<Signature>(),
Self::TooManyArguments { .. } => core::mem::size_of::<Signature>(),
_ => 0,
}
}
}
#[derive(Debug)]
pub struct RuntimeError {
kind: ErrorKind,
traceback: Vec<TraceSite>,
cause: Option<Box<RuntimeError>>,
}
unsafe impl GcTrace for RuntimeError {
fn trace(&self) {
self.kind.trace();
for site in self.traceback.iter() {
site.trace();
}
if let Some(error) = self.cause.as_ref() {
error.trace();
}
}
}
impl RuntimeError {
pub fn caused_by(mut self: Box<Self>, cause: Box<RuntimeError>) -> Box<Self> {
self.cause.replace(cause); self
}
pub fn extend_trace(mut self: Box<Self>, trace: impl Iterator<Item=TraceSite>) -> Box<Self> {
self.traceback.extend(trace); self
}
pub fn push_frame(mut self: Box<Self>, site: TraceSite) -> Box<Self> {
self.traceback.push(site); self
}
pub fn kind(&self) -> &ErrorKind { &self.kind }
pub fn traceback(&self) -> Traceback<'_> {
Traceback::build(self.traceback.iter())
}
}
impl Error for RuntimeError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.cause.as_ref().map(
|error| &*error as &RuntimeError as &dyn Error
)
}
}
#[allow(clippy::useless_format)]
impl fmt::Display for RuntimeError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
let message = match self.kind() {
ErrorKind::InvalidUnaryOperand(operand) => format!("unsupported operand: '{}'", operand),
ErrorKind::InvalidBinaryOperand(lhs, rhs) => format!("unsupported operands: '{}' and '{}'", lhs, rhs),
ErrorKind::DivideByZero => format!("divide by zero"),
ErrorKind::OverflowError => format!("integer overflow"),
ErrorKind::NegativeShiftCount => format!("negative bitshift count"),
ErrorKind::NameNotDefined(name) => format!("undefined variable \"{}\"", name),
ErrorKind::CantAssignImmutable => format!("can't assign to an immutable variable"),
ErrorKind::UnhashableValue(value) => format!("{} is not hashable", value.echo()),
ErrorKind::AssertFailed => format!("assertion failed"),
ErrorKind::StaticMessage(message) => message.to_string(),
ErrorKind::Message(message) => message.to_string(),
ErrorKind::MethodNotSupported(receiver, method) => {
match method {
MethodTag::AsBits => format!("can't interpret '{}' as bitfield", receiver),
MethodTag::AsInt => format!("can't interpret '{}' as int", receiver),
MethodTag::AsFloat => format!("can't interpret '{}' as float", receiver),
MethodTag::Invoke => format!("type '{}' is not callable", receiver),
MethodTag::Next => format!("type '{}' is not an iterator", receiver),
MethodTag::Iter => format!("type '{}' is not iterable", receiver),
_ => format!("type '{}' does not support '__{}'", receiver, method),
}
}
ErrorKind::MissingArguments { signature, nargs } => {
let missing = signature.required().iter()
.skip(*nargs)
.map(|param| *param.name())
.collect::<Vec<StringSymbol>>();
let count = signature.min_arity() - nargs;
format!(
"{} missing {} required {}: {}",
signature.display_short(),
count,
if count == 1 { "argument" }
else { "arguments" },
utils::fmt_join(", ", &missing),
)
},
ErrorKind::TooManyArguments { signature, nargs } => {
format!(
"{} takes {} arguments but {} were given",
signature.display_short(),
signature.max_arity().unwrap(),
nargs,
)
},
};
utils::format_error(fmt, "Runtime error", Some(&message), self.source())
}
}