Skip to main content

mlua/
thread.rs

1//! Lua thread (coroutine) handling.
2//!
3//! This module provides types for creating and working with Lua coroutines from Rust.
4//! Coroutines allow cooperative multitasking within a single Lua state by suspending and
5//! resuming execution at well-defined yield points.
6//!
7//! # Basic Usage
8//!
9//! Threads are created via [`Lua::create_thread`] and driven by calling [`Thread::resume`]:
10//!
11//! ```rust
12//! # use mlua::{Lua, Result, Thread};
13//! # fn main() -> Result<()> {
14//! let lua = Lua::new();
15//! let thread: Thread = lua.load(r#"
16//!     coroutine.create(function(a, b)
17//!         coroutine.yield(a + b)
18//!         return a * b
19//!     end)
20//! "#).eval()?;
21//!
22//! assert_eq!(thread.resume::<i32>((3, 4))?, 7);
23//! assert_eq!(thread.resume::<i32>(())?,    12);
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! # Async Support
29//!
30//! When the `async` feature is enabled, a [`Thread`] can be converted into an [`AsyncThread`]
31//! via [`Thread::into_async`], which implements both [`Future`] and [`Stream`].
32//! This integrates Lua coroutines naturally with Rust async runtimes such as Tokio.
33//!
34//! [`Lua::create_thread`]: crate::Lua::create_thread
35//! [`Future`]: std::future::Future
36//! [`Stream`]: futures_util::stream::Stream
37
38use std::fmt;
39use std::os::raw::{c_int, c_void};
40
41use crate::error::{Error, Result};
42use crate::function::Function;
43use crate::state::{RawLua, WeakLua};
44use crate::traits::{FromLuaMulti, IntoLuaMulti};
45use crate::types::{LuaType, ValueRef};
46use crate::util::{StackGuard, check_stack, error_traceback_thread, pop_error};
47
48#[cfg(not(feature = "luau"))]
49use crate::{
50    debug::{Debug, HookTriggers},
51    types::HookKind,
52};
53
54#[cfg(feature = "async")]
55use {
56    futures_util::stream::Stream,
57    std::{
58        future::Future,
59        marker::PhantomData,
60        pin::Pin,
61        ptr::NonNull,
62        task::{Context, Poll, Waker},
63    },
64};
65
66/// Controls which thread lifecycle events trigger the callback.
67#[derive(Clone, Copy, Debug, Default)]
68#[non_exhaustive]
69pub struct ThreadTriggers {
70    /// Trigger the callback when a new thread is created.
71    ///
72    /// On Luau this fires for every thread creation, on other Lua versions only for threads created
73    /// via [`Lua::create_thread`](crate::Lua::create_thread).
74    pub on_create: bool,
75    /// Trigger the callback before a thread is resumed via [`Thread::resume`] (or an async resume
76    /// driven by mlua). It does not fire for a `coroutine.resume` performed inside Lua code.
77    pub on_resume: bool,
78    /// Trigger the callback after a thread yields back to a [`Thread::resume`] driven by mlua.
79    /// It does not fire for a yield consumed by a `coroutine.resume` inside Lua code.
80    pub on_yield: bool,
81}
82
83impl ThreadTriggers {
84    /// An instance of [`ThreadTriggers`] with `on_create` trigger set.
85    pub const ON_CREATE: Self = Self::new().on_create();
86
87    /// An instance of [`ThreadTriggers`] with `on_resume` trigger set.
88    pub const ON_RESUME: Self = Self::new().on_resume();
89
90    /// An instance of [`ThreadTriggers`] with `on_yield` trigger set.
91    pub const ON_YIELD: Self = Self::new().on_yield();
92
93    /// Returns a new instance of `ThreadTriggers` with all triggers disabled.
94    pub const fn new() -> Self {
95        Self {
96            on_create: false,
97            on_resume: false,
98            on_yield: false,
99        }
100    }
101
102    /// Returns an instance of `ThreadTriggers` with `on_create` trigger set.
103    #[must_use]
104    pub const fn on_create(mut self) -> Self {
105        self.on_create = true;
106        self
107    }
108
109    /// Returns an instance of `ThreadTriggers` with `on_resume` trigger set.
110    #[must_use]
111    pub const fn on_resume(mut self) -> Self {
112        self.on_resume = true;
113        self
114    }
115
116    /// Returns an instance of `ThreadTriggers` with `on_yield` trigger set.
117    #[must_use]
118    pub const fn on_yield(mut self) -> Self {
119        self.on_yield = true;
120        self
121    }
122}
123
124impl std::ops::BitOr for ThreadTriggers {
125    type Output = Self;
126
127    fn bitor(mut self, rhs: Self) -> Self::Output {
128        self.on_create |= rhs.on_create;
129        self.on_resume |= rhs.on_resume;
130        self.on_yield |= rhs.on_yield;
131        self
132    }
133}
134
135impl std::ops::BitOrAssign for ThreadTriggers {
136    fn bitor_assign(&mut self, rhs: Self) {
137        *self = *self | rhs;
138    }
139}
140
141/// Represents a thread (coroutine) event.
142#[derive(Debug, Clone)]
143#[non_exhaustive]
144pub enum ThreadEvent {
145    /// A new thread was created.
146    Create(Thread),
147    /// A thread is about to be resumed via [`Thread::resume`].
148    Resume(Thread),
149    /// A thread has just yielded.
150    Yield(Thread),
151}
152
153/// Status of a Lua thread (coroutine).
154#[derive(Debug, Copy, Clone, Eq, PartialEq)]
155pub enum ThreadStatus {
156    /// The thread was just created or is suspended (yielded).
157    ///
158    /// If a thread is in this state, it can be resumed by calling [`Thread::resume`].
159    Resumable,
160    /// The thread is currently running.
161    Running,
162    /// The thread is active but not running.
163    ///
164    /// This is the case when the thread has resumed another thread (which has not yet
165    /// returned or yielded).
166    Normal,
167    /// The thread has finished executing.
168    Finished,
169    /// The thread has raised a Lua error during execution.
170    Error,
171}
172
173/// Internal representation of a Lua thread status.
174///
175/// The number in `New` and `Yielded` variants is the number of arguments pushed
176/// to the thread stack.
177#[derive(Clone, Copy)]
178enum ThreadStatusInner {
179    New(c_int),
180    Running,
181    Normal,
182    Yielded(c_int),
183    Finished,
184    Error,
185}
186
187impl ThreadStatusInner {
188    #[inline(always)]
189    fn is_yielded(self) -> bool {
190        matches!(self, ThreadStatusInner::Yielded(_))
191    }
192}
193
194/// Handle to an internal Lua thread (coroutine).
195#[derive(Clone, PartialEq)]
196pub struct Thread(pub(crate) ValueRef, pub(crate) *mut ffi::lua_State);
197
198#[cfg(feature = "send")]
199unsafe impl Send for Thread {}
200#[cfg(feature = "send")]
201unsafe impl Sync for Thread {}
202
203/// Thread (coroutine) representation as an async [`Future`] or [`Stream`].
204///
205/// [`Future`]: std::future::Future
206/// [`Stream`]: futures_util::stream::Stream
207#[cfg(feature = "async")]
208#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
209#[must_use = "futures do nothing unless you `.await` or poll them"]
210pub struct AsyncThread<R> {
211    thread: Thread,
212    ret: PhantomData<fn() -> R>,
213    recycle: bool,
214}
215
216pub(crate) struct ThreadEventGuard<'a> {
217    lua: &'a RawLua,
218    prev_state: *mut ffi::lua_State,
219}
220
221impl<'a> ThreadEventGuard<'a> {
222    #[inline]
223    pub(crate) unsafe fn new(lua: &'a RawLua, thread_state: *mut ffi::lua_State) -> Self {
224        let guard = ThreadEventGuard {
225            lua,
226            prev_state: lua.thread_event_state(),
227        };
228        lua.set_thread_event_state(thread_state);
229        guard
230    }
231}
232
233impl Drop for ThreadEventGuard<'_> {
234    #[inline]
235    fn drop(&mut self) {
236        unsafe { self.lua.set_thread_event_state(self.prev_state) };
237    }
238}
239
240#[inline]
241fn check_thread_reentrancy(thread_state: *mut ffi::lua_State, lua: &RawLua) -> Result<()> {
242    if thread_state == unsafe { lua.thread_event_state() } {
243        let err = "cannot resume or reset a thread from within its own event callback";
244        return Err(Error::runtime(err));
245    }
246    Ok(())
247}
248
249#[inline]
250unsafe fn exec_thread_event(
251    lua: &RawLua,
252    enabled: bool,
253    thread_state: *mut ffi::lua_State,
254    event: impl FnOnce() -> ThreadEvent,
255) -> Result<bool> {
256    if enabled
257        && lua.thread_event_state().is_null()
258        && let Some(cb) = lua.thread_event_callback()
259    {
260        let _guard = ThreadEventGuard::new(lua, thread_state);
261        cb(lua.lua(), event())?;
262        return Ok(true);
263    }
264    Ok(false)
265}
266
267impl Thread {
268    /// Returns the raw pointer to the Lua state that this thread is associated with.
269    ///
270    /// The pointer is valid only while this [`Thread`] is alive.
271    #[inline(always)]
272    pub fn state(&self) -> *mut ffi::lua_State {
273        self.1
274    }
275
276    /// Resumes execution of this thread.
277    ///
278    /// Equivalent to [`coroutine.resume`].
279    ///
280    /// Passes `args` as arguments to the thread. If the coroutine has called [`coroutine.yield`],
281    /// it will return these arguments. Otherwise, the coroutine wasn't yet started, so the
282    /// arguments are passed to its main function.
283    ///
284    /// If the thread is no longer resumable (meaning it has finished execution or encountered an
285    /// error), this will return [`Error::CoroutineUnresumable`], otherwise will return `Ok` as
286    /// follows:
287    ///
288    /// If the thread calls [`coroutine.yield`], returns the values passed to `yield`. If the thread
289    /// `return`s values from its main function, returns those.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// # use mlua::{Error, Lua, Result, Thread};
295    /// # fn main() -> Result<()> {
296    /// # let lua = Lua::new();
297    /// let thread: Thread = lua.load(r#"
298    ///     coroutine.create(function(arg)
299    ///         assert(arg == 42)
300    ///         local yieldarg = coroutine.yield(123)
301    ///         assert(yieldarg == 43)
302    ///         return 987
303    ///     end)
304    /// "#).eval()?;
305    ///
306    /// assert_eq!(thread.resume::<u32>(42)?, 123);
307    /// assert_eq!(thread.resume::<u32>(43)?, 987);
308    ///
309    /// // The coroutine has now returned, so `resume` will fail
310    /// match thread.resume::<u32>(()) {
311    ///     Err(Error::CoroutineUnresumable) => {},
312    ///     unexpected => panic!("unexpected result {:?}", unexpected),
313    /// }
314    /// # Ok(())
315    /// # }
316    /// ```
317    ///
318    /// [`coroutine.resume`]: https://www.lua.org/manual/5.4/manual.html#pdf-coroutine.resume
319    /// [`coroutine.yield`]: https://www.lua.org/manual/5.4/manual.html#pdf-coroutine.yield
320    pub fn resume<R>(&self, args: impl IntoLuaMulti) -> Result<R>
321    where
322        R: FromLuaMulti,
323    {
324        let lua = self.0.lua.lock();
325        check_thread_reentrancy(self.state(), &lua)?;
326        let (mut pushed_nargs, mut hook_yielded) = self.resumable_state(&lua)?;
327
328        let state = lua.state();
329        let thread_state = self.state();
330        unsafe {
331            let _sg = StackGuard::new(state);
332
333            // If the resume callback runs, it may touch this thread, so re-read the argument count
334            let on_resume = lua.thread_event_triggers().on_resume;
335            if exec_thread_event(&lua, on_resume, thread_state, || {
336                ThreadEvent::Resume(self.clone())
337            })? {
338                (pushed_nargs, hook_yielded) = self.resumable_state(&lua)?;
339            }
340
341            if !hook_yielded {
342                let nargs = args.push_into_stack_multi(&lua)?;
343                if nargs > 0 {
344                    check_stack(thread_state, nargs)?;
345                    ffi::lua_xmove(state, thread_state, nargs);
346                    pushed_nargs += nargs;
347                }
348            }
349
350            let mut thread_sg = StackGuard::with_top(thread_state, 0);
351            let (status, nresults) = self.resume_inner(&lua, pushed_nargs)?;
352            if status.is_yielded() && self.is_hook_yielded(&lua) {
353                debug_assert_eq!(nresults, 0);
354                thread_sg.keep(ffi::lua_gettop(thread_state));
355            }
356
357            check_stack(state, nresults + 1)?;
358            ffi::lua_xmove(thread_state, state, nresults);
359
360            // Exec thread yield callback
361            let on_yield = lua.thread_event_triggers().on_yield && status.is_yielded();
362            exec_thread_event(&lua, on_yield, thread_state, || ThreadEvent::Yield(self.clone()))?;
363
364            R::from_stack_multi(nresults, &lua)
365        }
366    }
367
368    /// Resumes execution of this thread, immediately raising an error.
369    ///
370    /// This is a Luau specific extension.
371    #[cfg(any(feature = "luau", doc))]
372    #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
373    pub fn resume_error<R>(&self, error: impl crate::IntoLua) -> Result<R>
374    where
375        R: FromLuaMulti,
376    {
377        let lua = self.0.lua.lock();
378        check_thread_reentrancy(self.state(), &lua)?;
379        match self.status_inner(&lua) {
380            ThreadStatusInner::New(_) | ThreadStatusInner::Yielded(_) => {}
381            _ => return Err(Error::CoroutineUnresumable),
382        };
383
384        let state = lua.state();
385        let thread_state = self.state();
386        unsafe {
387            let _sg = StackGuard::new(state);
388
389            // Exec thread resume callback
390            let on_resume = lua.thread_event_triggers().on_resume;
391            exec_thread_event(&lua, on_resume, thread_state, || {
392                ThreadEvent::Resume(self.clone())
393            })?;
394
395            check_stack(state, 1)?;
396            error.push_into_stack(&lua)?;
397            check_stack(thread_state, 1)?;
398            ffi::lua_xmove(state, thread_state, 1);
399
400            let _thread_sg = StackGuard::with_top(thread_state, 0);
401            let (status, nresults) = self.resume_inner(&lua, ffi::LUA_RESUMEERROR)?;
402
403            check_stack(state, nresults + 1)?;
404            ffi::lua_xmove(thread_state, state, nresults);
405
406            // Exec thread yield callback
407            let on_yield = lua.thread_event_triggers().on_yield && status.is_yielded();
408            exec_thread_event(&lua, on_yield, thread_state, || ThreadEvent::Yield(self.clone()))?;
409
410            R::from_stack_multi(nresults, &lua)
411        }
412    }
413
414    /// Resumes execution of this thread.
415    ///
416    /// It's similar to `resume()` but leaves `nresults` values on the thread stack.
417    unsafe fn resume_inner(&self, lua: &RawLua, nargs: c_int) -> Result<(ThreadStatusInner, c_int)> {
418        let state = lua.state();
419        let thread_state = self.state();
420        let mut nresults = 0;
421        #[cfg(not(feature = "luau"))]
422        let ret = ffi::lua_resume(thread_state, state, nargs, &mut nresults as *mut c_int);
423        #[cfg(feature = "luau")]
424        let ret = ffi::lua_resumex(thread_state, state, nargs, &mut nresults as *mut c_int);
425        match ret {
426            ffi::LUA_OK => Ok((ThreadStatusInner::Finished, nresults)),
427            ffi::LUA_YIELD => Ok((ThreadStatusInner::Yielded(0), nresults)),
428            ffi::LUA_ERRMEM => {
429                // Don't call error handler for memory errors
430                Err(pop_error(thread_state, ret))
431            }
432            _ => {
433                check_stack(state, 3)?;
434                protect_lua!(state, 0, 1, |state| error_traceback_thread(state, thread_state))?;
435                Err(pop_error(state, ret))
436            }
437        }
438    }
439
440    /// Gets the status of the thread.
441    pub fn status(&self) -> ThreadStatus {
442        match self.status_inner(&self.0.lua.lock()) {
443            ThreadStatusInner::New(_) | ThreadStatusInner::Yielded(_) => ThreadStatus::Resumable,
444            ThreadStatusInner::Running => ThreadStatus::Running,
445            ThreadStatusInner::Normal => ThreadStatus::Normal,
446            ThreadStatusInner::Finished => ThreadStatus::Finished,
447            ThreadStatusInner::Error => ThreadStatus::Error,
448        }
449    }
450
451    /// Gets the status of the thread (internal implementation).
452    fn status_inner(&self, lua: &RawLua) -> ThreadStatusInner {
453        let thread_state = self.state();
454        if thread_state == lua.state() {
455            // The thread is currently running
456            return ThreadStatusInner::Running;
457        }
458        let status = unsafe { ffi::lua_status(thread_state) };
459        let top = unsafe { ffi::lua_gettop(thread_state) };
460        match status {
461            ffi::LUA_YIELD => ThreadStatusInner::Yielded(top),
462            ffi::LUA_OK => {
463                // Active call frames mean this thread has resumed another (still-running) thread.
464                // Without frames it's new or finished.
465                let mut ar = const { unsafe { std::mem::zeroed::<ffi::lua_Debug>() } };
466                #[cfg(not(feature = "luau"))]
467                let has_frames = unsafe { ffi::lua_getstack(thread_state, 0, &mut ar) != 0 };
468                #[cfg(feature = "luau")]
469                let has_frames = unsafe { ffi::lua_getinfo(thread_state, 0, cstr!(""), &mut ar) != 0 };
470                if has_frames {
471                    ThreadStatusInner::Normal
472                } else if top > 0 {
473                    ThreadStatusInner::New(top - 1)
474                } else {
475                    ThreadStatusInner::Finished
476                }
477            }
478            _ => ThreadStatusInner::Error,
479        }
480    }
481
482    /// Returns the pending argument count and whether the thread was interrupted by a hook.
483    #[inline]
484    fn resumable_state(&self, lua: &RawLua) -> Result<(c_int, bool)> {
485        match self.status_inner(lua) {
486            ThreadStatusInner::New(nargs) => Ok((nargs, false)),
487            ThreadStatusInner::Yielded(nargs) => {
488                let hook_yielded = self.is_hook_yielded(lua);
489                Ok((if hook_yielded { 0 } else { nargs }, hook_yielded))
490            }
491            _ => Err(Error::CoroutineUnresumable),
492        }
493    }
494
495    /// Distinguishes a hook interruption from a normal yield.
496    fn is_hook_yielded(&self, lua: &RawLua) -> bool {
497        unsafe { lua.is_hook_yielded(self.state()) }
498    }
499
500    /// Returns `true` if this thread is resumable (meaning it can be resumed by calling
501    /// [`Thread::resume`]).
502    #[inline(always)]
503    pub fn is_resumable(&self) -> bool {
504        self.status() == ThreadStatus::Resumable
505    }
506
507    /// Returns `true` if this thread is currently running.
508    #[inline(always)]
509    pub fn is_running(&self) -> bool {
510        self.status() == ThreadStatus::Running
511    }
512
513    /// Returns `true` if this thread is active but not running.
514    ///
515    /// This is the case when the thread has resumed another thread that has not yet returned
516    /// or yielded.
517    #[inline(always)]
518    pub fn is_normal(&self) -> bool {
519        self.status() == ThreadStatus::Normal
520    }
521
522    /// Returns `true` if this thread has finished executing.
523    #[inline(always)]
524    pub fn is_finished(&self) -> bool {
525        self.status() == ThreadStatus::Finished
526    }
527
528    /// Returns `true` if this thread has raised a Lua error during execution.
529    #[inline(always)]
530    pub fn is_error(&self) -> bool {
531        self.status() == ThreadStatus::Error
532    }
533
534    /// Sets a hook function that will periodically be called as Lua code executes.
535    ///
536    /// This function is similar to [`Lua::set_hook`] except that it sets the hook for the thread.
537    /// You can have multiple hooks for different threads.
538    ///
539    /// To remove a hook call [`Thread::remove_hook`].
540    ///
541    /// [`Lua::set_hook`]: crate::Lua::set_hook
542    #[cfg(not(feature = "luau"))]
543    #[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
544    pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
545    where
546        F: Fn(&crate::Lua, &Debug) -> Result<crate::VmState> + crate::MaybeSend + 'static,
547    {
548        let lua = self.0.lua.lock();
549        unsafe {
550            lua.set_thread_hook(
551                self.state(),
552                HookKind::Thread(triggers, crate::types::XRc::new(callback)),
553            )
554        }
555    }
556
557    /// Removes any hook function from this thread.
558    #[cfg(not(feature = "luau"))]
559    #[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
560    pub fn remove_hook(&self) {
561        let lua = self.0.lua.lock();
562        unsafe {
563            lua.remove_thread_hook(self.state());
564        }
565    }
566
567    /// Resets a thread
568    ///
569    /// In [Lua 5.4]: cleans its call stack and closes all pending to-be-closed variables.
570    /// Returns an error in case of either the original error that stopped the thread or errors
571    /// in closing methods.
572    ///
573    /// In Luau: resets to the initial state of a newly created Lua thread.
574    /// Lua threads in arbitrary states (like yielded or errored) can be reset properly.
575    ///
576    /// Other Lua versions can reset only new or finished threads.
577    ///
578    /// Sets a Lua function for the thread afterwards.
579    ///
580    /// [Lua 5.4]: https://www.lua.org/manual/5.4/manual.html#lua_closethread
581    pub fn reset(&self, func: Function) -> Result<()> {
582        let lua = self.0.lua.lock();
583        assert!(
584            lua.weak() == &func.0.lua,
585            "Lua instance passed Value created from a different main Lua state"
586        );
587        check_thread_reentrancy(self.state(), &lua)?;
588        let thread_state = self.state();
589        unsafe {
590            let status = self.status_inner(&lua);
591            self.reset_inner(status)?;
592
593            // Push function to the top of the thread stack
594            ffi::lua_xpush(lua.ref_thread(), thread_state, func.0.index);
595
596            #[cfg(feature = "luau")]
597            {
598                // Inherit `LUA_GLOBALSINDEX` from the main thread
599                ffi::lua_xpush(lua.main_state(), thread_state, ffi::LUA_GLOBALSINDEX);
600                ffi::lua_replace(thread_state, ffi::LUA_GLOBALSINDEX);
601            }
602
603            Ok(())
604        }
605    }
606
607    unsafe fn reset_inner(&self, status: ThreadStatusInner) -> Result<()> {
608        match status {
609            ThreadStatusInner::New(_) | ThreadStatusInner::Finished => {
610                // Clear everything
611                ffi::lua_settop(self.state(), 0);
612                Ok(())
613            }
614            ThreadStatusInner::Running => Err(Error::runtime("cannot reset a running thread")),
615            ThreadStatusInner::Normal => Err(Error::runtime("cannot reset a normal thread")),
616            #[cfg(not(any(feature = "lua55", feature = "lua54", feature = "luau")))]
617            ThreadStatusInner::Yielded(_) | ThreadStatusInner::Error => {
618                Err(Error::runtime("cannot reset non-finished thread"))
619            }
620            #[cfg(any(feature = "lua55", feature = "lua54", feature = "luau"))]
621            ThreadStatusInner::Yielded(_) | ThreadStatusInner::Error => {
622                let thread_state = self.state();
623
624                #[cfg(all(feature = "lua54", not(feature = "vendored")))]
625                let status = ffi::lua_resetthread(thread_state);
626                #[cfg(any(feature = "lua55", all(feature = "lua54", feature = "vendored")))]
627                let status = {
628                    let lua = self.0.lua.lock();
629                    ffi::lua_closethread(thread_state, lua.state())
630                };
631                #[cfg(any(feature = "lua55", feature = "lua54"))]
632                if status != ffi::LUA_OK {
633                    return Err(pop_error(thread_state, status));
634                }
635                #[cfg(feature = "luau")]
636                ffi::lua_resetthread(thread_state);
637
638                Ok(())
639            }
640        }
641    }
642
643    /// Converts [`Thread`] to an [`AsyncThread`] which implements [`Future`] and [`Stream`] traits.
644    ///
645    /// Only resumable threads can be converted to [`AsyncThread`].
646    ///
647    /// `args` are pushed to the thread stack and will be used when the thread is resumed.
648    /// The object calls [`resume`] while polling and also allow to run Rust futures
649    /// to completion using an executor.
650    ///
651    /// Using [`AsyncThread`] as a [`Stream`] allow to iterate through [`coroutine.yield`]
652    /// values whereas [`Future`] version discards that values and poll until the final
653    /// one (returned from the thread function).
654    ///
655    /// [`Future`]: std::future::Future
656    /// [`Stream`]: futures_util::stream::Stream
657    /// [`resume`]: https://www.lua.org/manual/5.4/manual.html#lua_resume
658    /// [`coroutine.yield`]: https://www.lua.org/manual/5.4/manual.html#pdf-coroutine.yield
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// # use mlua::{Lua, Result, Thread};
664    /// use futures_util::stream::TryStreamExt;
665    /// # #[tokio::main]
666    /// # async fn main() -> Result<()> {
667    /// # let lua = Lua::new();
668    /// let thread: Thread = lua.load(r#"
669    ///     coroutine.create(function (sum)
670    ///         for i = 1,10 do
671    ///             sum = sum + i
672    ///             coroutine.yield(sum)
673    ///         end
674    ///         return sum
675    ///     end)
676    /// "#).eval()?;
677    ///
678    /// let mut stream = thread.into_async::<i64>(1)?;
679    /// let mut sum = 0;
680    /// while let Some(n) = stream.try_next().await? {
681    ///     sum += n;
682    /// }
683    ///
684    /// assert_eq!(sum, 286);
685    ///
686    /// # Ok(())
687    /// # }
688    /// ```
689    #[cfg(feature = "async")]
690    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
691    pub fn into_async<R>(self, args: impl IntoLuaMulti) -> Result<AsyncThread<R>>
692    where
693        R: FromLuaMulti,
694    {
695        let lua = self.0.lua.lock();
696        check_thread_reentrancy(self.state(), &lua)?;
697        let (_, hook_yielded) = self.resumable_state(&lua)?;
698
699        let state = lua.state();
700        let thread_state = self.state();
701        unsafe {
702            let _sg = StackGuard::new(state);
703
704            if !hook_yielded {
705                let nargs = args.push_into_stack_multi(&lua)?;
706                if nargs > 0 {
707                    check_stack(thread_state, nargs)?;
708                    ffi::lua_xmove(state, thread_state, nargs);
709                }
710            }
711
712            Ok(AsyncThread {
713                thread: self,
714                ret: PhantomData,
715                recycle: false,
716            })
717        }
718    }
719
720    /// Enables sandbox mode on this thread.
721    ///
722    /// Under the hood replaces the global environment table with a new table,
723    /// that performs writes locally and proxies reads to caller's global environment.
724    ///
725    /// This mode ideally should be used together with the global sandbox mode [`Lua::sandbox`].
726    ///
727    /// Please note that Luau links environment table with chunk when loading it into Lua state.
728    /// Therefore you need to load chunks into a thread to link with the thread environment.
729    ///
730    /// [`Lua::sandbox`]: crate::Lua::sandbox
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// # use mlua::{Lua, Result};
736    /// # #[cfg(feature = "luau")]
737    /// # fn main() -> Result<()> {
738    /// let lua = Lua::new();
739    /// let thread = lua.create_thread(lua.create_function(|lua2, ()| {
740    ///     lua2.load("var = 123").exec()?;
741    ///     assert_eq!(lua2.globals().get::<u32>("var")?, 123);
742    ///     Ok(())
743    /// })?)?;
744    /// thread.sandbox()?;
745    /// thread.resume::<()>(())?;
746    ///
747    /// // The global environment should be unchanged
748    /// assert_eq!(lua.globals().get::<Option<u32>>("var")?, None);
749    /// # Ok(())
750    /// # }
751    ///
752    /// # #[cfg(not(feature = "luau"))]
753    /// # fn main() { }
754    /// ```
755    #[cfg(any(feature = "luau", doc))]
756    #[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
757    pub fn sandbox(&self) -> Result<()> {
758        let lua = self.0.lua.lock();
759        let state = lua.state();
760        let thread_state = self.state();
761        unsafe {
762            check_stack(thread_state, 3)?;
763            check_stack(state, 3)?;
764            protect_lua!(state, 0, 0, |_| ffi::luaL_sandboxthread(thread_state))
765        }
766    }
767
768    /// Converts this thread to a generic C pointer.
769    ///
770    /// There is no way to convert the pointer back to its original value.
771    ///
772    /// Typically this function is used only for hashing and debug information.
773    #[inline]
774    pub fn to_pointer(&self) -> *const c_void {
775        self.0.to_pointer()
776    }
777
778    /// Returns a weak reference to the Lua instance owning this value.
779    #[doc(hidden)]
780    #[inline]
781    pub fn weak_lua(&self) -> &WeakLua {
782        &self.0.lua
783    }
784}
785
786impl fmt::Debug for Thread {
787    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
788        fmt.debug_tuple("Thread").field(&self.0).finish()
789    }
790}
791
792impl LuaType for Thread {
793    const TYPE_ID: c_int = ffi::LUA_TTHREAD;
794}
795
796#[cfg(feature = "async")]
797impl<R> AsyncThread<R> {
798    #[inline(always)]
799    pub(crate) fn set_recyclable(&mut self, recyclable: bool) {
800        self.recycle = recyclable;
801    }
802
803    #[inline(always)]
804    pub(crate) fn thread(&self) -> &Thread {
805        &self.thread
806    }
807}
808
809#[cfg(feature = "async")]
810impl<R> Drop for AsyncThread<R> {
811    fn drop(&mut self) {
812        if self.recycle
813            && let Some(lua) = self.thread.0.lua.try_lock()
814        {
815            unsafe {
816                #[cfg(feature = "luau")]
817                if lua.is_running_gc() {
818                    lua.update_thread_ownership(&self.thread, None);
819                    return;
820                }
821
822                let mut status = self.thread.status_inner(&lua);
823                if matches!(status, ThreadStatusInner::Yielded(0))
824                    && !self.thread.is_hook_yielded(&lua)
825                    && lua.is_async_wrapper_yield(self.thread.state())
826                {
827                    // The thread is dropped while yielded, resume it with the "terminate" signal
828                    ffi::lua_pushlightuserdata(self.thread.1, crate::Lua::poll_terminate().0);
829                    if let Ok((new_status, _)) = self.thread.resume_inner(&lua, 1) {
830                        // The coroutine can finish or yield again.
831                        status = new_status;
832                    }
833                }
834
835                // For Lua 5.4 this also closes all pending to-be-closed variables
836                if self.thread.reset_inner(status).is_ok() {
837                    lua.recycle_thread(&mut self.thread);
838                }
839                lua.update_thread_ownership(&self.thread, None);
840            }
841        }
842    }
843}
844
845#[cfg(feature = "async")]
846impl<R: FromLuaMulti> Stream for AsyncThread<R> {
847    type Item = Result<R>;
848
849    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
850        let lua = self.thread.0.lua.lock();
851        check_thread_reentrancy(self.thread.state(), &lua)?;
852        let mut nargs = match self.thread.resumable_state(&lua) {
853            Ok((nargs, _)) => nargs,
854            Err(_) => return Poll::Ready(None),
855        };
856
857        let state = lua.state();
858        let thread_state = self.thread.state();
859        unsafe {
860            let _sg = StackGuard::new(state);
861            let _wg = WakerGuard::new(&lua, cx.waker());
862
863            // If the resume callback runs, it may touch this thread, so re-read the argument count
864            let on_resume = lua.thread_event_triggers().on_resume;
865            if exec_thread_event(&lua, on_resume, thread_state, || {
866                ThreadEvent::Resume(self.thread.clone())
867            })? {
868                nargs = match self.thread.resumable_state(&lua) {
869                    Ok((nargs, _)) => nargs,
870                    Err(_) => return Poll::Ready(None),
871                };
872            }
873
874            let mut thread_sg = StackGuard::with_top(thread_state, 0);
875            let (status, nresults) = (self.thread).resume_inner(&lua, nargs)?;
876            let hook_yielded = status.is_yielded() && self.thread.is_hook_yielded(&lua);
877            if hook_yielded {
878                debug_assert_eq!(nresults, 0);
879                thread_sg.keep(ffi::lua_gettop(thread_state));
880            }
881
882            if status.is_yielded() && !hook_yielded && nresults == 1 && is_poll_pending(thread_state) {
883                // Exec thread yield callback
884                let on_yield = lua.thread_event_triggers().on_yield;
885                exec_thread_event(&lua, on_yield, thread_state, || {
886                    ThreadEvent::Yield(self.thread.clone())
887                })?;
888                return Poll::Pending;
889            }
890
891            check_stack(state, nresults + 1)?;
892            ffi::lua_xmove(thread_state, state, nresults);
893
894            if status.is_yielded() {
895                let on_yield = lua.thread_event_triggers().on_yield;
896                exec_thread_event(&lua, on_yield, thread_state, || {
897                    ThreadEvent::Yield(self.thread.clone())
898                })?;
899                // Continue polling
900                cx.waker().wake_by_ref();
901            }
902
903            Poll::Ready(Some(R::from_stack_multi(nresults, &lua)))
904        }
905    }
906}
907
908#[cfg(feature = "async")]
909impl<R: FromLuaMulti> Future for AsyncThread<R> {
910    type Output = Result<R>;
911
912    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
913        let lua = self.thread.0.lua.lock();
914        check_thread_reentrancy(self.thread.state(), &lua)?;
915        let (mut nargs, _) = self.thread.resumable_state(&lua)?;
916
917        let state = lua.state();
918        let thread_state = self.thread.state();
919        unsafe {
920            let _sg = StackGuard::new(state);
921            let _wg = WakerGuard::new(&lua, cx.waker());
922
923            // If the resume callback runs, it may touch this thread, so re-read the argument count
924            let on_resume = lua.thread_event_triggers().on_resume;
925            if exec_thread_event(&lua, on_resume, thread_state, || {
926                ThreadEvent::Resume(self.thread.clone())
927            })? {
928                (nargs, _) = self.thread.resumable_state(&lua)?;
929            }
930
931            let mut thread_sg = StackGuard::with_top(thread_state, 0);
932            let (status, nresults) = self.thread.resume_inner(&lua, nargs)?;
933            let hook_yielded = status.is_yielded() && self.thread.is_hook_yielded(&lua);
934            if hook_yielded {
935                debug_assert_eq!(nresults, 0);
936                thread_sg.keep(ffi::lua_gettop(thread_state));
937            }
938
939            if status.is_yielded() {
940                let pending = !hook_yielded && nresults == 1 && is_poll_pending(thread_state);
941
942                // Exec thread yield callback
943                let on_yield = lua.thread_event_triggers().on_yield;
944                exec_thread_event(&lua, on_yield, thread_state, || {
945                    ThreadEvent::Yield(self.thread.clone())
946                })?;
947
948                if !pending {
949                    // Ignore values returned via yield()
950                    cx.waker().wake_by_ref();
951                }
952                return Poll::Pending;
953            }
954
955            check_stack(state, nresults + 1)?;
956            ffi::lua_xmove(thread_state, state, nresults);
957
958            Poll::Ready(R::from_stack_multi(nresults, &lua))
959        }
960    }
961}
962
963#[cfg(feature = "async")]
964#[inline(always)]
965unsafe fn is_poll_pending(state: *mut ffi::lua_State) -> bool {
966    ffi::lua_tolightuserdata(state, -1) == crate::Lua::poll_pending().0
967}
968
969#[cfg(feature = "async")]
970struct WakerGuard<'lua, 'a> {
971    lua: &'lua RawLua,
972    prev: NonNull<Waker>,
973    _phantom: PhantomData<&'a ()>,
974}
975
976#[cfg(feature = "async")]
977impl<'lua, 'a> WakerGuard<'lua, 'a> {
978    #[inline]
979    pub fn new(lua: &'lua RawLua, waker: &'a Waker) -> Result<WakerGuard<'lua, 'a>> {
980        let prev = lua.set_waker(NonNull::from(waker));
981        Ok(WakerGuard {
982            lua,
983            prev,
984            _phantom: PhantomData,
985        })
986    }
987}
988
989#[cfg(feature = "async")]
990impl Drop for WakerGuard<'_, '_> {
991    fn drop(&mut self) {
992        self.lua.set_waker(self.prev);
993    }
994}
995
996#[cfg(test)]
997mod assertions {
998    use super::*;
999
1000    #[cfg(not(feature = "send"))]
1001    static_assertions::assert_not_impl_any!(Thread: Send);
1002    #[cfg(feature = "send")]
1003    static_assertions::assert_impl_all!(Thread: Send, Sync);
1004    #[cfg(all(feature = "async", not(feature = "send")))]
1005    static_assertions::assert_not_impl_any!(AsyncThread<()>: Send);
1006    #[cfg(all(feature = "async", feature = "send"))]
1007    static_assertions::assert_impl_all!(AsyncThread<()>: Send, Sync);
1008}