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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::fmt::{Debug, Display};
use std::num::{ParseFloatError, ParseIntError};
use std::ops::{Bound, RangeBounds};
use std::result;
use thiserror::Error;
use crate::lvm::Lvm;
use crate::objects::{Closure, Table, Value, ValueType};
use crate::opcode::OpCode;
use crate::token::{Token, TokenType};
use crate::utils::Join;
pub type Result<T> = result::Result<T, Error>;
#[derive(Error, Debug, Clone, PartialEq)]
pub enum Error {
#[error("syntax error: {0}")]
SyntaxError(#[from] SyntaxError),
#[error("runtime error: {0}")]
RuntimeError(#[from] RuntimeError),
}
#[derive(Error, Debug, Clone, PartialEq)]
pub enum SyntaxError {
#[error("parse int error ({0})")]
ParseIntError(#[from] ParseIntError),
#[error("parse float error ({0})")]
ParseFloatError(#[from] ParseFloatError),
#[error("number format error")]
NumberFormatError,
#[error("unterminated string error")]
UnterminatedStringError,
#[error("escape error ({0})")]
EscapeError(#[from] EscapeError),
#[error("unexpect token (expected {}, found {token})", .expected.iter().join(", "))]
UnexpectToken {
token: Box<Token>,
expected: Vec<TokenType>,
},
#[error("unexpect EOF")]
UnexpectEOF,
#[error("parse assign statement error")]
ParseAssignStmtError,
#[error("parse try expression error")]
ParseTryExprError,
#[error("illegal ast")]
IllegalAst,
#[error("break outside loop")]
BreakOutsideLoop,
#[error("continue outside loop")]
ContinueOutsideLoop,
#[error("global outside function")]
GlobalOutsideFunction,
#[error("return outside function")]
ReturnOutsideFunction,
#[error("throw outside function")]
ThrowOutsideFunction,
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum EscapeError {
InvalidEscape,
BareCarriageReturn,
TooShortHexEscape,
InvalidCharInHexEscape,
OutOfRangeHexEscape,
NoBraceInUnicodeEscape,
InvalidCharInUnicodeEscape,
EmptyUnicodeEscape,
UnclosedUnicodeEscape,
LeadingUnderscoreUnicodeEscape,
OverlongUnicodeEscape,
LoneSurrogateUnicodeEscape,
OutOfRangeUnicodeEscape,
}
impl Display for EscapeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(self, f)
}
}
#[derive(Error, Debug, Clone)]
#[error("{kind}")]
pub struct RuntimeError {
pub kind: RuntimeErrorKind,
pub traceback: Vec<TracebackFrame>,
}
impl PartialEq for RuntimeError {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
}
}
#[derive(Debug, Clone)]
pub struct TracebackFrame {
pub pc: usize,
pub operate_stack: Vec<Value>,
pub closure: Closure,
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum RuntimeErrorKind {
#[error("stack error")]
StackError,
#[error("program error: {0}")]
ProgramError(#[from] ProgramError),
#[error("throw error: throw illegal value ({0})")]
ThrowError(Value),
#[error("user panic: {0}")]
UserPanic(Value),
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum ProgramError {
#[error("module error: {0}")]
ModuleError(usize),
#[error("code index error: {0}")]
CodeIndexError(usize),
#[error("unexpect code: {0}")]
UnexpectCodeError(OpCode),
#[error("local name error: {0}")]
LocalNameError(usize),
#[error("global name error: {0}")]
GlobalNameError(usize),
#[error("const error: {0}")]
ConstError(usize),
#[error("upvalue error: {0}")]
UpvalueError(usize),
#[error("function list error: {0}")]
FuncListError(usize),
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum BuiltinError {
TypeError(#[from] TypeError),
ImportError(String),
}
impl BuiltinError {
pub fn error_type(&self) -> &'static str {
match self {
BuiltinError::TypeError(_) => "type_error",
BuiltinError::ImportError(_) => "import_error",
}
}
pub fn msg(&self) -> String {
match self {
BuiltinError::TypeError(v) => v.to_string(),
BuiltinError::ImportError(v) => v.clone(),
}
}
#[inline]
pub fn into_table(&self, lvm: &mut Lvm) -> Table {
let mut error_table = Table::new();
error_table.set(
&lvm.get_builtin_str("type"),
lvm.new_str_value(self.error_type().to_string()),
);
error_table.set(&lvm.get_builtin_str("msg"), lvm.new_str_value(self.msg()));
error_table
}
#[inline]
pub fn into_table_value(&self, lvm: &mut Lvm) -> Value {
let t = self.into_table(lvm);
lvm.new_table_value(t)
}
}
impl Display for BuiltinError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.error_type(), self.msg())
}
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum TypeError {
#[error("convert error (from {from} to {to})")]
ConvertError { from: ValueType, to: ValueType },
#[error("unexpect type error (expected {}, found {value_type})", .expected.iter().join(", "))]
UnexpectTypeError {
value_type: ValueType,
expected: Vec<ValueType>,
},
#[error("operator error (unsupported operand type(s) for {operator}: {operand})")]
UnOperatorError {
operator: OpCode,
operand: ValueType,
},
#[error("operator error (unsupported operand type(s) for {operator}: {} and {})", .operand.0, .operand.1)]
BinOperatorError {
operator: OpCode,
operand: (ValueType, ValueType),
},
#[error("not callable error ({0} value is not callable)")]
NotCallableError(ValueType),
#[error("call arguments error (required {required} arguments, but {given} was given)")]
CallArgumentsError {
value: Option<Box<Closure>>,
required: CallArgumentsErrorKind,
given: usize,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallArgumentsErrorKind {
pub start: usize,
pub end: Option<usize>,
}
impl CallArgumentsErrorKind {
pub fn new(start: usize, end: Option<usize>) -> Self {
Self { start, end }
}
pub fn more_then(start: usize) -> Self {
Self { start, end: None }
}
}
impl From<usize> for CallArgumentsErrorKind {
fn from(value: usize) -> Self {
CallArgumentsErrorKind {
start: value,
end: Some(value),
}
}
}
impl From<(usize, usize)> for CallArgumentsErrorKind {
fn from(value: (usize, usize)) -> Self {
CallArgumentsErrorKind {
start: value.0,
end: Some(value.1),
}
}
}
impl From<(usize, Option<usize>)> for CallArgumentsErrorKind {
fn from(value: (usize, Option<usize>)) -> Self {
CallArgumentsErrorKind {
start: value.0,
end: value.1,
}
}
}
impl RangeBounds<usize> for CallArgumentsErrorKind {
fn start_bound(&self) -> Bound<&usize> {
Bound::Included(&self.start)
}
fn end_bound(&self) -> Bound<&usize> {
if let Some(end) = &self.end {
Bound::Included(end)
} else {
Bound::Unbounded
}
}
}
impl CallArgumentsErrorKind {
pub fn contains(&self, item: &usize) -> bool {
<Self as RangeBounds<usize>>::contains(self, item)
}
}
impl Display for CallArgumentsErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(end) = self.end {
if self.start == end {
write!(f, "{}", end)
} else {
write!(f, "[{}, {}]", self.start, end)
}
} else {
write!(f, "at least {}", self.start)
}
}
}
#[macro_export]
macro_rules! unexpect_type_error {
($value_type:expr, $expected:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::UnexpectTypeError {
value_type: $value_type,
expected: $expected,
})
};
}
#[macro_export]
macro_rules! operator_error {
($operator:expr, $arg1:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::UnOperatorError {
operator: $operator,
operand: $arg1.value_type(),
})
};
($operator:expr, $arg1:expr, $arg2:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::BinOperatorError {
operator: $operator,
operand: ($arg1.value_type(), $arg2.value_type()),
})
};
}
#[macro_export]
macro_rules! type_convert_error {
($from:expr, $to:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::ConvertError {
from: $from,
to: $to,
})
};
}
#[macro_export]
macro_rules! not_callable_error {
($value:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::NotCallableError(
$value.value_type(),
))
};
}
#[macro_export]
macro_rules! call_arguments_error {
($value:expr, $require:expr, $give:expr) => {
$crate::errors::BuiltinError::TypeError($crate::errors::TypeError::CallArgumentsError {
value: $value,
required: $crate::errors::CallArgumentsErrorKind::from($require),
given: $give,
})
};
}