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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use std::fmt;
use crate::LuaType;
// Types
/// A single frame in a stack trace.
#[derive(Debug, Clone)]
pub struct StackFrame {
/// Function name (if known).
pub function_name: Option<String>,
/// Source file or chunk name.
pub source: Option<String>,
/// Line number where the call occurred (1-indexed).
pub line: u32,
}
impl fmt::Display for StackFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let source = self.source.as_deref().unwrap_or("[C]");
let func_desc = match &self.function_name {
Some(name) => format!("function '{name}'"),
None => "main chunk".to_string(),
};
write!(f, "{}:{}: in {}", source, self.line, func_desc)
}
}
/// An error raised by the parser or VM. Carries an [`ErrorKind`], the source
/// location where it surfaced, and a stack trace.
#[derive(Debug)]
pub struct Error {
/// What went wrong.
pub kind: ErrorKind,
/// 1-based source line number where the error surfaced (0 if unknown).
pub line_num: usize,
/// 1-based source column (0 if unknown).
pub column: usize,
/// Stack trace at the point of error (innermost frame first).
pub stack_trace: Vec<StackFrame>,
}
/// Which source location an error renders as its `chunk:line:` prefix.
///
/// Set by `error(msg, level)`: level 1 (the default) blames the frame that
/// raised the error, level 0 suppresses the prefix, and level N blames N-1
/// frames further up the traceback.
#[derive(Debug, Clone, Copy)]
pub enum PrefixLocation {
/// Blame the frame where the error surfaced. The default.
Current,
/// Render no `chunk:line:` prefix at all, as `error(msg, 0)` does.
Suppressed,
/// Blame this index into the stack trace, counting from the innermost
/// frame. An index past the end renders no prefix.
///
/// `u32` rather than `usize` so `PrefixLocation` stays 8 bytes and
/// `ScriptError` stays within `ErrorKind`'s existing largest variant.
/// Widening `ErrorKind` widens every `Result<_, Error>` held across the
/// Lua call recursion, which runs 1000 frames deep and overflows the
/// debug-build stack - `call_depth_exceeded_error` catches exactly that.
TraceFrame(u32),
}
/// Top-level error categories. See the type-specific enums (e.g.
/// [`TypeError`], [`SyntaxError`], [`ArgError`]) for finer-grained variants.
#[derive(Debug)]
pub enum ErrorKind {
/// Operation applied to a value of the wrong Lua type.
TypeError(TypeError),
/// Wrong number or type of arguments to a builtin or host function.
ArgError(ArgError),
/// Parser rejected the source.
SyntaxError(SyntaxError),
/// Script exceeded its cost budget.
BudgetExceeded {
/// Total cost consumed when the budget was exceeded.
used: u64,
/// The budget that was set.
budget: i64,
},
/// Metamethod chain (`__index` / `__newindex`) exceeded maximum depth.
MetamethodDepthExceeded {
/// Recursion depth reached before bailing out.
depth: u32,
},
/// Invalid jump target (compiler bug or corrupt bytecode).
InvalidJump {
/// Bytecode index where the bad jump originated.
ip: usize,
/// Signed jump offset that pointed outside the chunk.
offset: isize,
},
/// Call stack depth exceeded (too much recursion).
CallDepthExceeded {
/// Depth reached at the failing call.
depth: u32,
},
/// Stack size exceeded (too many values on stack).
StackOverflow {
/// Stack size that triggered the overflow.
size: usize,
},
/// A Lua string exceeded the fixed resource limit.
StringSizeExceeded {
/// Size requested by the operation.
size: usize,
/// Maximum permitted string size.
limit: usize,
},
/// Invalid stack index passed to a host API.
InvalidStackIndex {
/// The bad index, as supplied by the caller.
index: isize,
},
/// Anchor handle is stale (released, generation mismatch) or belongs
/// to a different `State`. Operations that need a live value return
/// this rather than aliasing into the wrong slot.
InvalidAnchor,
/// Attempted to anchor `nil`. `nil` carries no GC weight and has no
/// use case for a stable handle; embedders that need an "absent" value
/// should use `Option<Anchor>`.
AnchorNil,
/// A runtime fault detected by the VM or by a library operation - a bad
/// pattern, too many results, an invalid `next` key and so on. Distinct
/// from [`ErrorKind::ScriptError`], which the script raised on purpose,
/// and from [`ErrorKind::InternalError`], which indicates a VM bug.
RuntimeError(String),
/// An error explicitly raised by script code through `error()`. Hosts can
/// use this to tell deliberate script termination from a VM-detected fault.
///
/// The prefix location lives here rather than on [`Error`] deliberately:
/// only `error()` can set it, and `Error` is returned by value through
/// every level of the Lua call recursion, so widening it costs stack on a
/// path that already runs to `MAX_CALL_DEPTH`. `ErrorKind` is sized by its
/// largest variant, which this is not.
ScriptError {
/// The message the script passed to `error()`.
message: String,
/// Which frame supplies the rendered `chunk:line:` prefix.
prefix: PrefixLocation,
},
/// Internal error (corrupt bytecode or VM bug). The string is a
/// human-readable description; report these as bugs.
InternalError(String),
}
/// Argument error raised by builtins or host functions.
#[derive(Debug)]
pub struct ArgError {
/// 1-based argument index that failed validation. Negative values count
/// from the end of the argument list.
pub arg_number: isize,
/// Name of the function the argument was passed to (if known).
pub func_name: Option<String>,
/// Expected Lua type for this argument.
pub expected: Option<LuaType>,
/// Lua type the caller actually supplied.
pub received: Option<LuaType>,
}
/// Syntax-level error categories raised by the parser.
#[derive(Debug)]
pub enum SyntaxError {
/// Numeric literal could not be parsed as a number.
BadNumber,
/// `break` used outside any enclosing loop.
BreakOutsideLoop,
/// Character not valid as part of any token.
InvalidCharacter(char),
/// Escape sequence is not supported by Lua string literals.
InvalidEscapeSequence,
/// A hexadecimal string escape did not contain two hexadecimal digits.
HexadecimalDigitExpected,
/// A decimal string escape exceeds the byte range.
DecimalEscapeTooLarge,
/// Long bracketed strings are deliberately unsupported.
LongStringUnsupported,
/// More expressions in a single source construct than the VM accepts.
TooManyExpressions,
/// Function body has more locals than the VM accepts.
TooManyLocals,
/// Function has more upvalues than the bytecode can encode.
TooManyUpvalues,
/// Source exceeds the parser's bounded syntax nesting depth.
TooManySyntaxLevels,
/// A fixed-arity call uses the dynamic-argument sentinel.
TooManyArguments,
/// A control-flow target cannot be represented by a jump instruction.
JumpTooFar,
/// Source nests function definitions deeper than the VM accepts.
TooManyNestedFunctions,
/// More numeric literals in a chunk than the literal pool accepts.
TooManyNumbers,
/// More string literals in a chunk than the literal pool accepts.
TooManyStrings,
/// More fields in a single table constructor than the VM accepts.
TooManyTableFields,
/// String literal not closed before EOF or end of line.
UnclosedString,
/// Source ended while a construct was still open.
UnexpectedEof,
/// Unexpected token. The String contains a description like
/// `"'...' outside vararg function"` or `"'<token>' near '<context>'"`.
UnexpectedTok(String),
/// A line started with an open parenthesis, which is ambiguous in Lua
/// (could continue the previous statement). dellingr rejects this rather
/// than guessing.
LParenLineStart,
}
/// Type errors raised by arithmetic, comparison, indexing, and concat.
#[derive(Debug)]
pub enum TypeError {
/// Arithmetic op applied to a non-numeric value of the given type.
Arithmetic(LuaType),
/// Comparison applied to incompatible types.
Comparison(LuaType, LuaType),
/// `..` (concat) applied to a non-string non-number of the given type.
Concat(LuaType),
/// Attempted to call a value that is not a function.
FunctionCall(LuaType),
/// `#` applied to a value that is neither a string nor a table.
Length(LuaType),
/// Indexed (`t[k]`, `t.k`, `t:m`) into a non-table value.
TableIndex(LuaType),
/// Used `NaN` as a table key.
TableKeyNan,
/// Used `nil` as a table key.
TableKeyNil,
}
// main impls
impl Error {
/// Construct an error with explicit source location.
pub fn new(kind: impl Into<ErrorKind>, line_num: usize, column: usize) -> Self {
Error {
kind: kind.into(),
line_num,
column,
stack_trace: Vec::new(),
}
}
/// Construct an error without source-location information. Used for
/// errors raised before any chunk has been parsed (e.g. host API misuse).
pub fn without_location(kind: ErrorKind) -> Self {
Error::new(kind, 0, 0)
}
/// Attach a stack trace to this error.
pub fn with_stack_trace(mut self, trace: Vec<StackFrame>) -> Self {
self.stack_trace = trace;
self
}
pub(crate) fn with_location(mut self, line_num: usize, column: usize) -> Self {
self.line_num = line_num;
self.column = column;
self
}
/// 1-based column number where the error surfaced (0 if unknown).
pub fn column(&self) -> usize {
self.column
}
/// 1-based line number where the error surfaced (0 if unknown).
pub fn line_num(&self) -> usize {
self.line_num
}
/// Whether the host can plausibly retry the operation after handling the
/// error. Currently only some [`SyntaxError`] variants are recoverable.
pub fn is_recoverable(&self) -> bool {
self.kind.is_recoverable()
}
}
impl ErrorKind {
/// Whether the underlying error category is recoverable - see
/// [`Error::is_recoverable`].
pub fn is_recoverable(&self) -> bool {
if let Self::SyntaxError(e) = self {
e.is_recoverable()
} else {
false
}
}
}
impl SyntaxError {
/// Returns true if this is a SyntaxError that can be fixed by appending
/// more text to the source code.
pub fn is_recoverable(&self) -> bool {
// matches!(self, Self::UnclosedString | Self::UnexpectedEof)
matches!(self, Self::UnexpectedEof)
}
}
// `Display` impls
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Take the source and the line from the SAME record. Reading the source
// from the innermost frame but the line from `self.line_num` can splice
// together two unrelated locations: a host `RustFunc` may return an
// `Error` carrying its own line, which says nothing about the Lua chunk
// whose name is about to be printed next to it.
let prefix_location = match &self.kind {
ErrorKind::ScriptError { prefix, .. } => *prefix,
_ => PrefixLocation::Current,
};
let prefix_frame = match prefix_location {
PrefixLocation::Current => self.stack_trace.first(),
PrefixLocation::Suppressed => None,
PrefixLocation::TraceFrame(index) => self.stack_trace.get(index as usize),
};
let suppress_prefix = matches!(prefix_location, PrefixLocation::Suppressed)
|| matches!(prefix_location, PrefixLocation::TraceFrame(_)) && prefix_frame.is_none();
// The line always comes from the selected frame, whether or not that
// frame knows its source name. Falling back to `self.line_num` when the
// source is absent would report the innermost line under an
// `error(msg, 2)` that deliberately selected a caller.
if suppress_prefix {
write!(f, "{}", self.kind)?;
} else {
match prefix_frame.filter(|frame| frame.line != 0) {
Some(frame) => match frame.source.as_deref() {
Some(source) => write!(f, "{source}:{}: {}", frame.line, self.kind)?,
None => write!(f, "{}:{}: {}", frame.line, self.column, self.kind)?,
},
None => write!(f, "{}:{}: {}", self.line_num, self.column, self.kind)?,
}
}
if !self.stack_trace.is_empty() {
writeln!(f)?;
writeln!(f, "stack traceback:")?;
for frame in &self.stack_trace {
writeln!(f, "\t{frame}")?;
}
}
Ok(())
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ErrorKind::*;
match self {
ArgError(e) => e.fmt(f),
SyntaxError(e) => e.fmt(f),
TypeError(e) => e.fmt(f),
BudgetExceeded { used, budget } => {
write!(
f,
"budget exceeded: used {used} cost with budget of {budget}"
)
}
MetamethodDepthExceeded { depth } => {
write!(f, "metamethod chain too deep (depth {depth})")
}
InvalidJump { ip, offset } => {
write!(
f,
"internal error: invalid jump (instruction {ip}, offset {offset})"
)
}
CallDepthExceeded { depth } => {
write!(f, "call stack overflow (depth {depth})")
}
StackOverflow { size } => {
write!(f, "stack overflow ({size} values)")
}
StringSizeExceeded { size, limit } => {
write!(f, "string size {size} exceeds limit {limit}")
}
InvalidStackIndex { index } => {
write!(f, "internal error: invalid stack index ({index})")
}
InvalidAnchor => {
write!(
f,
"invalid anchor (released, stale generation, or wrong State)"
)
}
AnchorNil => {
write!(f, "cannot anchor nil")
}
// A script's `error()` message and a library runtime error render
// identically, exactly as reference does. The variants are distinct
// so hosts can tell deliberate script termination from a VM-detected
// fault, which is not a rendering difference.
RuntimeError(msg) | ScriptError { message: msg, .. } => write!(f, "{msg}"),
InternalError(msg) => {
write!(f, "internal error: {msg}")
}
}
}
}
impl fmt::Display for ArgError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let func_name = match &self.func_name {
Some(s) => s.as_str(),
None => "<anonymous>",
};
let extra = match (&self.expected, &self.received) {
(Some(expected), Some(got)) => format!("{expected} expected, got {got}"),
(Some(expected), None) => format!("{expected} expected, got no value"),
(None, _) => "value expected".into(),
};
write!(
f,
"bad argument #{} to {} ({})",
self.arg_number, func_name, extra
)
}
}
impl fmt::Display for SyntaxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use SyntaxError::*;
match self {
BadNumber => write!(f, "malformed number"),
BreakOutsideLoop => write!(f, "<break> at line 1 not inside a loop"),
InvalidCharacter(c) => write!(f, "invalid character '{c}'"),
InvalidEscapeSequence => write!(f, "invalid escape sequence"),
HexadecimalDigitExpected => write!(f, "hexadecimal digit expected"),
DecimalEscapeTooLarge => write!(f, "decimal escape too large"),
LongStringUnsupported => write!(f, "long strings are not supported"),
TooManyExpressions => write!(f, "too many expressions in a single list (limit 255)"),
TooManyLocals => write!(f, "too many local variables"),
TooManyUpvalues => write!(f, "too many upvalues"),
TooManySyntaxLevels => write!(f, "chunk has too many syntax levels"),
TooManyArguments => write!(f, "too many arguments in a fixed call (limit 254)"),
JumpTooFar => write!(
f,
"control-flow jump is too far (exceeds signed 16-bit range)"
),
TooManyNestedFunctions => write!(f, "too many nested functions (limit 255)"),
TooManyNumbers => write!(f, "too many literal numbers"),
TooManyStrings => write!(f, "too many literal strings"),
TooManyTableFields => write!(f, "too many fields in table constructor"),
UnclosedString => write!(f, "unfinished string"),
UnexpectedEof => write!(f, "unexpected <eof>"),
UnexpectedTok(msg) => write!(f, "{msg}"),
LParenLineStart => write!(f, "ambiguous function call"),
}
}
}
impl fmt::Display for TypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use TypeError::*;
match self {
Arithmetic(typ) => write!(f, "attempt to perform arithmetic on a {typ} value"),
Comparison(type1, type2) if type1 == type2 => {
write!(f, "attempt to compare two {type1} values")
}
Comparison(type1, type2) => write!(f, "attempt to compare {type1} with {type2}"),
Concat(typ) => write!(f, "attempt to concatenate a {typ} value"),
FunctionCall(typ) => write!(f, "attempt to call a {typ} value"),
Length(typ) => write!(f, "attempt to get length of a {typ} value"),
TableIndex(typ) => write!(f, "attempt to index a {typ} value"),
TableKeyNan => write!(f, "table index was NaN"),
TableKeyNil => write!(f, "table index was nil"),
}
}
}
// `From` impls
impl From<ArgError> for ErrorKind {
fn from(e: ArgError) -> Self {
Self::ArgError(e)
}
}
impl From<SyntaxError> for ErrorKind {
fn from(e: SyntaxError) -> Self {
Self::SyntaxError(e)
}
}
impl From<TypeError> for ErrorKind {
fn from(e: TypeError) -> Self {
Self::TypeError(e)
}
}