luau 0.732.0

Safe lifetime-bound Rust embedding API for the Luau runtime
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
use core::fmt;
use std::error::Error as StdError;
use std::rc::Rc;
use std::result::Result as StdResult;

use luau_compiler::CompilerError;
use luau_vm::Thread as VmThread;
use luau_vm::internal::userdata::{TypedUserdataAccess, TypedUserdataError};
use luau_vm::{VmControl, VmError, VmErrorResult, VmExit};

use crate::thread::Thread;
use crate::userdata::{MetaMethod, Userdata, UserdataFields, UserdataMethods};
use crate::value::{FromLua, IntoLua, Value};

type DynStdError = dyn StdError + 'static;

/// An error produced by the safe Luau embedding API.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
    /// Luau source could not be compiled.
    SyntaxError {
        /// The compiler diagnostic.
        message: String,
        /// Whether the diagnostic indicates that more input may complete the source.
        incomplete_input: bool,
    },
    /// Luau execution raised an error.
    RuntimeError(String),
    /// The VM could not allocate memory.
    MemoryError(String),
    /// An error occurred while handling another error.
    ErrorHandlerError(String),
    /// Execution was stopped by an interrupt.
    Interrupted,
    /// A coroutine could not be resumed from its current state.
    CoroutineUnresumable,
    /// A mutable Rust callback attempted to call itself recursively.
    RecursiveMutCallback,
    /// A scoped Rust callback was called after its scope ended.
    CallbackDestructed,
    /// The VM stack could not accommodate an operation.
    StackError,
    /// Too many arguments were supplied to [`crate::Function::bind`].
    BindError,
    /// A callback argument could not be converted.
    BadArgument {
        /// The function receiving the argument, when known.
        to: Option<String>,
        /// The one-based argument position.
        pos: usize,
        /// The argument name, when known.
        name: Option<String>,
        /// The conversion error.
        cause: Rc<Error>,
    },
    /// A Luau value could not be converted to a Rust type.
    FromLuaConversionError {
        /// The Luau source type.
        from: String,
        /// The requested Rust type.
        to: String,
        /// Additional conversion context.
        message: Option<String>,
    },
    /// A Rust value could not be converted to Luau.
    IntoLuaConversionError {
        /// The Rust source type.
        from: String,
        /// The requested Luau type.
        to: String,
        /// Additional conversion context.
        message: Option<String>,
    },
    /// A userdata value did not contain the requested Rust type.
    UserdataTypeMismatch,
    /// A userdata value has already been taken or destroyed.
    UserdataDestructed,
    /// A userdata value was already mutably borrowed.
    UserdataBorrowError,
    /// A userdata value was already borrowed.
    UserdataBorrowMutError,
    /// A restricted metamethod was accessed directly.
    MetaMethodRestricted(String),
    /// A registry key was used with a different [`crate::Lua`] state.
    MismatchedRegistryKey,
    /// A VM-owned handle was used with a different [`crate::Lua`] state.
    ForeignLuaHandle,
    /// A Rust callback returned an error.
    CallbackError {
        /// The Luau traceback captured at the callback boundary.
        traceback: String,
        /// The original callback error.
        cause: Rc<Error>,
    },
    /// An error produced by external Rust code.
    ExternalError(Rc<DynStdError>),
}

/// The result type returned by the safe Luau embedding API.
pub type Result<T> = StdResult<T, Error>;

impl Error {
    /// Creates a runtime error with the displayed message.
    pub fn runtime(message: impl fmt::Display) -> Self {
        Self::RuntimeError(message.to_string())
    }

    /// Wraps an external Rust error without wrapping an existing Luau error again.
    pub fn external(error: impl Into<Box<DynStdError>>) -> Self {
        let error = error.into();
        match error.downcast::<Self>() {
            Ok(error) => *error,
            Err(error) => Self::ExternalError(Rc::from(error)),
        }
    }

    /// Attempts to downcast a wrapped external error by reference.
    ///
    /// Nested [`Error::BadArgument`] and [`Error::CallbackError`] causes are
    /// followed recursively.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: StdError + 'static,
    {
        match self {
            Self::ExternalError(error) => error.downcast_ref(),
            Self::BadArgument { cause, .. } | Self::CallbackError { cause, .. } => {
                cause.downcast_ref()
            }
            _ => None,
        }
    }

    /// Iterates from this error through its nested Luau and external errors.
    ///
    /// A bare [`Error::ExternalError`] wrapper is skipped because it adds no
    /// context of its own. The wrapped external error's own [`StdError::source`]
    /// chain is not followed.
    pub fn chain(&self) -> impl Iterator<Item = &(dyn StdError + 'static)> {
        Chain {
            root: self,
            current: None,
        }
    }

    pub(crate) fn from_lua_conversion(from: &str, to: &str, message: Option<&str>) -> Self {
        Self::FromLuaConversionError {
            from: from.to_string(),
            to: to.to_string(),
            message: message.map(str::to_string),
        }
    }

    pub(crate) fn into_lua_conversion(from: &str, to: &str, message: Option<&str>) -> Self {
        Self::IntoLuaConversionError {
            from: from.to_string(),
            to: to.to_string(),
            message: message.map(str::to_string),
        }
    }

    pub(crate) fn bad_argument(pos: usize, cause: Self) -> Self {
        Self::BadArgument {
            to: None,
            pos,
            name: None,
            cause: Rc::new(cause),
        }
    }

    pub(crate) const fn foreign_lua_handle() -> Self {
        Self::ForeignLuaHandle
    }

    pub(crate) const fn mismatched_registry_key() -> Self {
        Self::MismatchedRegistryKey
    }

    pub(crate) fn index_out_of_bounds() -> Self {
        Self::runtime("index out of bounds")
    }

    fn from_thread_error(thread: &VmThread, error: VmError) -> Self {
        if matches!(error, VmError::Memory) {
            return Self::MemoryError("not enough memory".to_string());
        }

        if matches!(error, VmError::Runtime)
            && let Some(error) = unsafe { Self::from_wrapped_stack(thread, -1) }
        {
            return error;
        }

        let message = unsafe { thread.to_string(-1) }
            .ok()
            .flatten()
            .map(ToString::to_string)
            .unwrap_or_else(|| "unknown error".to_string());

        Self::from_vm_error_message(error, message)
    }

    pub(crate) unsafe fn from_wrapped_stack(thread: &VmThread, index: i32) -> Option<Self> {
        let userdata = unsafe { thread.typed_userdata_at(index) }?;
        let cell = unsafe { userdata.cell_ptr::<WrappedError>() }?;
        let error = unsafe { &*cell }.try_borrow().ok()?;
        error.as_ref().map(|error| error.0.clone())
    }

    pub(crate) fn from_thread_exit(thread: impl AsRef<VmThread>, exit: impl Into<VmExit>) -> Self {
        let thread = thread.as_ref();
        match exit.into() {
            VmExit::Error(error) => Self::from_thread_error(thread, error),
            VmExit::Control(VmControl::Break) => Self::Interrupted,
            VmExit::Control(VmControl::Yield) => {
                Self::RuntimeError("operation yielded unexpectedly".to_string())
            }
        }
    }

    pub(crate) fn raise_error<T>(self, thread: &VmThread) -> VmErrorResult<T> {
        unsafe {
            let message = self.to_string();
            luau_vm::error!(thread, &message)
        }
    }

    fn from_vm_error_message(error: VmError, message: String) -> Self {
        match error {
            VmError::Runtime => Self::RuntimeError(message),
            VmError::Syntax => Self::SyntaxError {
                incomplete_input: message.ends_with("<eof>"),
                message,
            },
            VmError::Memory => Self::MemoryError(message),
            VmError::ErrorHandler => Self::ErrorHandlerError(message),
        }
    }

    pub(crate) fn from_typed_userdata(error: TypedUserdataError) -> Self {
        match error {
            TypedUserdataError::TypeMismatch => Self::UserdataTypeMismatch,
            TypedUserdataError::Destructed => Self::UserdataDestructed,
            TypedUserdataError::Borrowed => Self::UserdataBorrowMutError,
        }
    }
}

impl From<CompilerError> for Error {
    fn from(error: CompilerError) -> Self {
        let message = error.to_string();
        Self::SyntaxError {
            incomplete_input: message.ends_with("<eof>"),
            message,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SyntaxError { message, .. } => write!(formatter, "syntax error: {message}"),
            Self::RuntimeError(message) => write!(formatter, "runtime error: {message}"),
            Self::MemoryError(message) => write!(formatter, "memory error: {message}"),
            Self::ErrorHandlerError(message) => {
                write!(formatter, "error handler error: {message}")
            }
            Self::Interrupted => formatter.write_str("execution interrupted"),
            Self::CoroutineUnresumable => formatter.write_str("coroutine is not resumable"),
            Self::RecursiveMutCallback => {
                formatter.write_str("mutable callback called recursively")
            }
            Self::CallbackDestructed => formatter.write_str("callback has been destructed"),
            Self::StackError => formatter.write_str(
                "out of Lua stack, too many arguments to a Lua function or too many return values from a callback",
            ),
            Self::BindError => formatter.write_str("too many arguments to Function::bind"),
            Self::BadArgument {
                to,
                pos,
                name,
                cause,
            } => {
                match name {
                    Some(name) => write!(formatter, "bad argument `{name}`")?,
                    None => write!(formatter, "bad argument #{pos}")?,
                }
                if let Some(to) = to {
                    write!(formatter, " to `{to}`")?;
                }
                write!(formatter, ": {cause}")
            }
            Self::FromLuaConversionError { from, to, message } => {
                write!(formatter, "error converting Lua {from} to {to}")?;
                if let Some(message) = message {
                    write!(formatter, " ({message})")?;
                }
                Ok(())
            }
            Self::IntoLuaConversionError { from, to, message } => {
                write!(formatter, "error converting {from} to Lua {to}")?;
                if let Some(message) = message {
                    write!(formatter, " ({message})")?;
                }
                Ok(())
            }
            Self::UserdataTypeMismatch => formatter.write_str("userdata is not expected type"),
            Self::UserdataDestructed => formatter.write_str("userdata has been destructed"),
            Self::UserdataBorrowError => formatter.write_str("error borrowing userdata"),
            Self::UserdataBorrowMutError => formatter.write_str("error mutably borrowing userdata"),
            Self::MetaMethodRestricted(name) => {
                write!(formatter, "metamethod {name} is restricted")
            }
            Self::MismatchedRegistryKey => {
                formatter.write_str("registry key belongs to a different Lua state")
            }
            Self::ForeignLuaHandle => formatter.write_str("value belongs to a different Lua state"),
            Self::CallbackError { traceback, cause } => {
                let (mut cause, mut full_traceback) = (cause, None);
                while let Self::CallbackError {
                    cause: nested_cause,
                    traceback: nested_traceback,
                } = &**cause
                {
                    cause = nested_cause;
                    full_traceback = Some(nested_traceback);
                }

                write!(formatter, "{cause}")?;
                let traceback = traceback.trim();
                if let Some(full_traceback) = full_traceback {
                    let full_traceback = full_traceback.trim();
                    if !full_traceback.is_empty() {
                        write!(formatter, "\nstack traceback:\n")?;
                        if !traceback.is_empty()
                            && let Some(position) = full_traceback.find(traceback)
                        {
                            write!(
                                formatter,
                                "{}>{}",
                                &full_traceback[..position],
                                &full_traceback[position..]
                            )?;
                        } else {
                            formatter.write_str(full_traceback)?;
                        }
                    }
                } else if !traceback.is_empty() {
                    write!(formatter, "\nstack traceback:\n{traceback}")?;
                }
                Ok(())
            }
            Self::ExternalError(error) => fmt::Display::fmt(error, formatter),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::ExternalError(error) => error.source(),
            _ => None,
        }
    }
}

struct WrappedError(Error);

impl Userdata for WrappedError {
    fn add_fields<F: UserdataFields<Self>>(fields: &mut F) {
        fields.add_meta_field(MetaMethod::Type, "error");
    }

    fn add_methods<M: UserdataMethods<Self>>(methods: &mut M) {
        methods.add_meta_method(MetaMethod::ToString, |_, error, arguments| {
            arguments.finish(error.0.to_string())
        });
    }
}

impl<'lua> IntoLua<'lua> for Error {
    fn into_lua(self, _: crate::LuaRef<'lua>) -> Result<Value<'lua>> {
        Ok(Value::Error(Box::new(self)))
    }

    unsafe fn push_into_stack(self, thread: &Thread<'lua>) -> Result<()> {
        thread.push_userdata(WrappedError(self))
    }
}

impl<'lua> FromLua<'lua> for Error {
    fn from_lua(value: Value<'lua>, _: crate::LuaRef<'lua>) -> Result<Self> {
        match value {
            Value::Error(error) => Ok(*error),
            value => Ok(Self::runtime(value.to_string()?)),
        }
    }
}

/// Converts an external Rust error into a Luau [`Error`].
pub trait ExternalError {
    /// Wraps this external error as a Luau error.
    fn into_lua_err(self) -> Error;
}

impl<E> ExternalError for E
where
    E: Into<Box<DynStdError>>,
{
    fn into_lua_err(self) -> Error {
        Error::external(self)
    }
}

/// Converts a Rust result with an external error into a Luau [`Result`].
pub trait ExternalResult<T> {
    /// Converts the error side of this result into a Luau error.
    fn into_lua_err(self) -> Result<T>;
}

impl<T, E> ExternalResult<T> for StdResult<T, E>
where
    E: ExternalError,
{
    fn into_lua_err(self) -> Result<T> {
        self.map_err(ExternalError::into_lua_err)
    }
}

struct Chain<'a> {
    root: &'a Error,
    current: Option<&'a (dyn StdError + 'static)>,
}

impl<'a> Iterator for Chain<'a> {
    type Item = &'a (dyn StdError + 'static);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let error: Option<&dyn StdError> = match self.current {
                None => {
                    self.current = Some(self.root);
                    self.current
                }
                Some(current) => match current.downcast_ref::<Error>()? {
                    Error::BadArgument { cause, .. } | Error::CallbackError { cause, .. } => {
                        self.current = Some(&**cause);
                        self.current
                    }
                    Error::ExternalError(error) => {
                        self.current = Some(&**error);
                        self.current
                    }
                    _ => None,
                },
            };

            if let Some(Error::ExternalError(_)) = error?.downcast_ref::<Error>() {
                continue;
            }

            return self.current;
        }
    }
}