tsuki 0.4.8

Lua 5.4 ported to Rust
Documentation
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
pub use self::input::DynamicInputs;

pub(crate) use self::input::Inputs;
pub(crate) use self::output::Outputs;
pub(crate) use self::stack::*;

use crate::lapi::lua_checkstack;
use crate::ldo::luaD_call;
use crate::lfunc::luaF_closeupval;
use crate::lmem::luaM_free_;
use crate::lobject::{UpVal, luaO_arith};
use crate::lstate::CallInfo;
use crate::value::UnsafeValue;
use crate::vm::{luaV_finishget, luaV_finishset};
use crate::{
    CallError, Lua, LuaFn, NON_YIELDABLE_WAKER, Object, Ops, Ref, StackOverflow, Table, Value,
    YIELDABLE_WAKER, luaH_get,
};
use alloc::alloc::handle_alloc_error;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::alloc::Layout;
use core::cell::{Cell, RefCell, RefMut, UnsafeCell};
use core::error::Error;
use core::marker::PhantomPinned;
use core::mem::transmute;
use core::num::NonZero;
use core::pin::{Pin, pin};
use core::ptr::{addr_eq, addr_of_mut, null, null_mut};
use core::task::{Context, Poll, Waker};
use thiserror::Error;

mod input;
mod output;
mod stack;

/// Lua thread.
///
/// Use [Lua::create_thread()] or [Context::create_thread()](crate::Context::create_thread()) to
/// create the value of this type.
#[repr(C)]
pub struct Thread<A> {
    pub(crate) hdr: Object<A>,
    pub(crate) nci: Cell<u16>,
    pub(crate) top: StackPtr<A>,
    pub(crate) ci: Cell<*mut CallInfo>,
    pub(crate) stack_last: Cell<*mut StackValue<A>>,
    pub(crate) stack: Cell<*mut StackValue<A>>,
    pub(crate) openupval: Cell<*mut UpVal<A>>,
    pub(crate) tbclist: Cell<*mut StackValue<A>>,
    pub(crate) twups: Cell<*const Self>,
    pub(crate) base_ci: UnsafeCell<CallInfo>,
    pub(crate) yielding: Cell<Option<usize>>,
    pending: RefCell<Option<Pin<Box<dyn Future<Output = Result<(), Box<CallError>>>>>>>,
    phantom: PhantomPinned,
}

impl<A> Thread<A> {
    pub(crate) fn new(g: &Lua<A>) -> *const Self {
        // Create new thread.
        let layout = Layout::new::<Self>();
        let th = unsafe { g.gc.alloc(8, layout).cast::<Self>() };

        unsafe { addr_of_mut!((*th).stack).write(Cell::new(null_mut())) };
        unsafe { addr_of_mut!((*th).ci).write(Cell::new(null_mut())) };
        unsafe { addr_of_mut!((*th).nci).write(Cell::new(0)) };
        unsafe { addr_of_mut!((*th).twups).write(Cell::new(th)) };
        unsafe { addr_of_mut!((*th).openupval).write(Cell::new(null_mut())) };
        unsafe { addr_of_mut!((*th).yielding).write(Cell::new(None)) };
        unsafe { addr_of_mut!((*th).pending).write(RefCell::default()) };

        // Allocate stack.
        let layout = Layout::array::<StackValue<A>>(2 * 20 + 5).unwrap();
        let stack = unsafe { alloc::alloc::alloc(layout) as *mut StackValue<A> };

        if stack.is_null() {
            handle_alloc_error(layout);
        }

        for i in 0..(2 * 20 + 5) {
            unsafe { (*stack.offset(i)).tt_ = 0 | 0 << 4 };
        }

        unsafe { (*th).stack.set(stack) };
        unsafe { addr_of_mut!((*th).top).write(StackPtr::new((*th).stack.get())) };
        unsafe { addr_of_mut!((*th).stack_last).write(Cell::new((*th).stack.get().add(2 * 20))) };
        unsafe { addr_of_mut!((*th).tbclist).write(Cell::new((*th).stack.get())) };

        // Setup base CI.
        let ci = unsafe { (*th).base_ci.get() };

        unsafe { (*ci).previous = null_mut() };
        unsafe { (*ci).next = (*ci).previous };
        unsafe { (*ci).callstatus = 1 << 1 };
        unsafe { addr_of_mut!((*ci).func).write(0) };
        unsafe { addr_of_mut!((*ci).pc).write(0) };
        unsafe { (*ci).nresults = 0 };
        unsafe { (*th).top.write_nil() };
        unsafe { (*th).top.add(1) };
        unsafe { addr_of_mut!((*ci).top).write(NonZero::new(1).unwrap()) };
        unsafe { (*th).ci.set(ci) };

        th
    }

    /// Returns `true` if this thread has active calls.
    #[inline(always)]
    pub fn is_busy(&self) -> bool {
        self.ci.get() != self.base_ci.get()
    }

    /// Returns `true` if this thread is suspended.
    pub fn is_suspended(&self) -> bool {
        match self.pending.try_borrow() {
            Ok(v) => v.is_some(),
            Err(_) => false, // Calling from resume().
        }
    }

    /// Returns `true` if stack is empty.
    #[inline(always)]
    pub fn is_stack_empty(&self) -> bool {
        unsafe { self.top.get().offset_from_unsigned(self.stack.get()) == 1 }
    }

    /// Sets entry point to be start by [Self::resume()] or [Self::async_resume()].
    ///
    /// # Panics
    /// If `f` was created from different [Lua] instance.
    pub fn set_entry(&self, f: impl Into<UnsafeValue<A>>) -> Result<(), Box<dyn Error>> {
        // Only allows from top-level.
        let top = unsafe { self.top.get().offset_from_unsigned(self.stack.get()) };

        if top != 1 {
            return Err(Box::new(ThreadBusy));
        }

        // Check if function created from the same Lua.
        let f = f.into();

        if unsafe { (f.tt_ & 1 << 6) != 0 && (*f.value_.gc).global != self.hdr.global } {
            panic!("attempt to set entry point created from a different Lua");
        }

        // Write function.
        unsafe { lua_checkstack(self, 1, 0)? };

        unsafe { self.top.write(f) };
        unsafe { self.top.add(1) };

        Ok(())
    }

    /// Call a function or callable value.
    ///
    /// `args` can be either:
    ///
    /// - A unit to represents zero arguments.
    /// - Any value that can be converted to [UnsafeValue] or a tuple of it.
    /// - [DynamicInputs].
    ///
    /// `R` can be either:
    ///
    /// - A unit to discard all results.
    /// - [Value](crate::Value) to extract first result and discard the rest.
    /// - [Vec](alloc::vec::Vec) of [Value](crate::Value) to extract all results.
    ///
    /// The error will be either [CallError](crate::CallError) or something else.
    ///
    /// # Panics
    /// If `f` or some of `args` was created from different [Lua] instance.
    pub fn call<'a, R: Outputs<'a, A>>(
        &'a self,
        f: impl Into<UnsafeValue<A>>,
        args: impl Inputs<A>,
    ) -> Result<R, Box<dyn Error>> {
        // Check if function created from the same Lua.
        let f = f.into();

        if unsafe { (f.tt_ & 1 << 6) != 0 && (*f.value_.gc).global != self.hdr.global } {
            panic!("attempt to call a value created from a different Lua");
        }

        // Push function and its arguments.
        let ot = unsafe { self.top.get().offset_from_unsigned(self.stack.get()) };
        let nargs = args.len();

        unsafe { lua_checkstack(self, 1 + nargs, 0)? };

        unsafe { self.top.write(f) };
        unsafe { self.top.add(1) };
        unsafe { args.push_to(self) };

        // Call.
        {
            let f = unsafe { self.top.get().sub(nargs + 1) };
            let f = unsafe { pin!(luaD_call(self, f, R::N)) };
            let w = unsafe { Waker::new(null(), &NON_YIELDABLE_WAKER) };

            match f.poll(&mut Context::from_waker(&w)) {
                Poll::Ready(Ok(_)) => (),
                Poll::Ready(Err(e)) => return Err(e),
                Poll::Pending => unreachable!(),
            }
        }

        // Get number of results.
        let n = match R::N {
            -1 => unsafe {
                let ot = self.stack.get().add(ot);
                let v = self.top.get().offset_from_unsigned(ot);

                self.top.set(ot);

                v
            },
            0 => 0,
            v => unsafe {
                let v = v.try_into().unwrap();
                self.top.sub(v);
                v
            },
        };

        Ok(unsafe { R::new(self, n) })
    }

    /// Call a function with ability to call into [AsyncFp](crate::AsyncFp).
    ///
    /// `args` can be either:
    ///
    /// - A unit to represents zero arguments.
    /// - Any value that can be converted to [UnsafeValue] or a tuple of it.
    /// - [DynamicInputs].
    ///
    /// `R` can be either:
    ///
    /// - A unit to discard all results.
    /// - [Value](crate::Value) to extract first result and discard the rest.
    /// - [Vec](alloc::vec::Vec) of [Value](crate::Value) to extract all results.
    ///
    /// The error will be either [CallError](crate::CallError) or something else.
    ///
    /// This method is not available on main thread so you need to create a [Thread] to use this
    /// method.
    ///
    /// # Panics
    /// If `f` or some of `args` was created from different [Lua] instance.
    pub async fn async_call<'a, R: Outputs<'a, A>>(
        &'a self,
        f: &LuaFn<A>,
        args: impl Inputs<A>,
    ) -> Result<R, Box<dyn Error>> {
        // Only allows from top-level otherwise Lua stack can be corrupted when the future is
        // suspend.
        let top = unsafe { self.top.get().offset_from_unsigned(self.stack.get()) };

        if top != 1 {
            return Err(Box::new(ThreadBusy));
        }

        // Check if function created from the same Lua.
        if f.hdr.global != self.hdr.global {
            panic!("attempt to call a function created from a different Lua");
        }

        // Push function and its arguments.
        let nargs = args.len();

        unsafe { lua_checkstack(self, 1 + nargs, 0)? };

        unsafe { self.top.write(f.into()) };
        unsafe { self.top.add(1) };
        unsafe { args.push_to(self) };

        // Call.
        let f = unsafe { self.top.get().sub(nargs + 1) };

        if let Err(e) = unsafe { luaD_call(self, f, R::N).await } {
            return Err(e); // Required for unsized coercion.
        }

        // Get number of results.
        let n = match R::N {
            -1 => unsafe {
                let ot = self.stack.get().add(top);
                let v = self.top.get().offset_from_unsigned(ot);

                self.top.set(ot);

                v
            },
            0 => 0,
            v => unsafe {
                let v = v.try_into().unwrap();
                self.top.sub(v);
                v
            },
        };

        Ok(unsafe { R::new(self, n) })
    }

    /// Start of resume a function that was set with [Self::set_entry()].
    ///
    /// # Panics
    /// If some of `args` was created from different [Lua] instance.
    pub fn resume<'a, R: Outputs<'a, A>>(
        &'a self,
        args: impl Inputs<A>,
    ) -> Result<Coroutine<'a, A, R>, Box<dyn Error>> {
        // Get pending call.
        let top = unsafe { self.top.get().offset_from_unsigned(self.stack.get()) };
        let mut f = if top == 1 {
            return Err("cannot resume dead coroutine".into());
        } else if self.ci.get() != self.base_ci.get() {
            let f = match self.pending.try_borrow_mut() {
                Ok(v) => v,
                Err(_) => return Err(Box::new(ThreadBusy)), // Recursive call.
            };

            // Check if called while async call is active.
            let f = match RefMut::filter_map(f, |v| v.as_mut()) {
                Ok(v) => v,
                Err(_) => return Err("attempt to resume a thread without entry point".into()),
            };

            // Push arguments.
            let nargs = args.len();

            unsafe { lua_checkstack(self, nargs, 0)? };
            unsafe { args.push_to(self) };

            self.yielding.set(Some(nargs));

            f
        } else {
            // Push arguments.
            let nargs = args.len();

            unsafe { lua_checkstack(self, nargs, 0)? };
            unsafe { args.push_to(self) };

            // Start coroutine.
            let f = unsafe { self.top.get().sub(nargs + 1) };
            let f = unsafe { Box::pin(luaD_call(self, f, R::N)) };
            let f = f as Pin<Box<dyn Future<Output = Result<(), Box<CallError>>>>>;
            let p = self.pending.borrow_mut();

            RefMut::map(p, move |v| v.insert(unsafe { transmute(f) }))
        };

        // Resume.
        let r = {
            let w = unsafe { Waker::new(null(), &YIELDABLE_WAKER) };

            match f.as_mut().poll(&mut Context::from_waker(&w)) {
                Poll::Ready(v) => v,
                Poll::Pending => {
                    // Take values from yield.
                    let yields = self.yielding.take().unwrap();
                    let yields = unsafe {
                        self.top.sub(yields);
                        Outputs::new(self, yields)
                    };

                    // Reset stack.
                    let ci = self.ci.get();
                    let top = unsafe { self.stack.get().add((*ci).func + 1) };

                    unsafe { self.top.set(top) };

                    return Ok(Coroutine::Suspended(yields));
                }
            }
        };

        drop(f);

        *self.pending.borrow_mut() = None;

        if let Err(e) = r {
            return Err(e);
        }

        // Get number of results.
        let n = match R::N {
            -1 => unsafe {
                let ot = self.stack.get().add(1);
                let v = self.top.get().offset_from_unsigned(ot);

                self.top.set(ot);

                v
            },
            0 => 0,
            v => unsafe {
                let v = v.try_into().unwrap();
                self.top.sub(v);
                v
            },
        };

        Ok(Coroutine::Finished(unsafe { R::new(self, n) }))
    }

    /// Start of resume a function that was set with [Self::set_entry()].
    ///
    /// # Panics
    /// If some of `args` was created from different [Lua] instance.
    pub async fn async_resume<'a, R: Outputs<'a, A>>(
        &'a self,
        args: impl Inputs<A>,
    ) -> Result<Coroutine<'a, A, R>, Box<dyn Error>> {
        // Get pending call.
        let top = unsafe { self.top.get().offset_from_unsigned(self.stack.get()) };
        let f = if top == 1 {
            return Err("cannot resume dead coroutine".into());
        } else if self.ci.get() != self.base_ci.get() {
            let f = match self.pending.try_borrow_mut() {
                Ok(v) => v,
                Err(_) => return Err(Box::new(ThreadBusy)), // Recursive call.
            };

            // Check if called while async call is active.
            let f = match RefMut::filter_map(f, |v| v.as_mut()) {
                Ok(v) => v,
                Err(_) => return Err("attempt to resume a thread without entry point".into()),
            };

            // Push arguments.
            let nargs = args.len();

            unsafe { lua_checkstack(self, nargs, 0)? };
            unsafe { args.push_to(self) };

            self.yielding.set(Some(nargs));

            f
        } else {
            // Push arguments.
            let nargs = args.len();

            unsafe { lua_checkstack(self, nargs, 0)? };
            unsafe { args.push_to(self) };

            // Start coroutine.
            let f = unsafe { self.top.get().sub(nargs + 1) };
            let f = unsafe { Box::pin(luaD_call(self, f, R::N)) };
            let f = f as Pin<Box<dyn Future<Output = Result<(), Box<CallError>>>>>;
            let p = self.pending.borrow_mut();

            RefMut::map(p, move |v| v.insert(unsafe { transmute(f) }))
        };

        // Resume.
        let r = Resume {
            f,
            y: &self.yielding,
        }
        .await;

        match r {
            Ok(Some(yields)) => {
                // Take values from yield.
                let yields = unsafe {
                    self.top.sub(yields);
                    Outputs::new(self, yields)
                };

                // Reset stack.
                let ci = self.ci.get();
                let top = unsafe { self.stack.get().add((*ci).func + 1) };

                unsafe { self.top.set(top) };

                return Ok(Coroutine::Suspended(yields));
            }
            r => {
                *self.pending.borrow_mut() = None;

                if let Err(e) = r {
                    return Err(e);
                }
            }
        }

        // Get number of results.
        let n = match R::N {
            -1 => unsafe {
                let ot = self.stack.get().add(1);
                let v = self.top.get().offset_from_unsigned(ot);

                self.top.set(ot);

                v
            },
            0 => 0,
            v => unsafe {
                let v = v.try_into().unwrap();
                self.top.sub(v);
                v
            },
        };

        Ok(Coroutine::Finished(unsafe { R::new(self, n) }))
    }

    /// Index `t` with `k` and returns the result.
    ///
    /// This method honor `__index` metavalue.
    ///
    /// # Panics
    /// If `t` or `k` was created from different [Lua] instance.
    #[inline]
    pub fn index(
        &self,
        t: impl Into<UnsafeValue<A>>,
        k: impl Into<UnsafeValue<A>>,
    ) -> Result<Value<'_, A>, Box<dyn core::error::Error>> {
        // Check if table come from the same Lua.
        let t = t.into();

        if unsafe { (t.tt_ & 1 << 6 != 0) && (*t.value_.gc).global != self.hdr.global } {
            panic!("attempt to index a value created from different Lua");
        }

        // Check if key come from the same Lua.
        let k = k.into();

        if unsafe { (k.tt_ & 1 << 6 != 0) && (*k.value_.gc).global != self.hdr.global } {
            panic!("attempt to index a value with key created from different Lua");
        }

        // Try table.
        let mut slot = null();
        let ok = if !(t.tt_ == 5 | 0 << 4 | 1 << 6) {
            false
        } else {
            let t = unsafe { t.value_.gc.cast::<Table<A>>() };

            slot = unsafe { luaH_get(t, &k) };

            unsafe { !((*slot).tt_ & 0xf == 0) }
        };

        // Get value.
        if ok {
            return Ok(unsafe { Value::from_unsafe(slot) });
        }

        // Try __index. We need a strong reference for t here since luaV_finishget can call into
        // user function. k will be passed to the function to we don't need to a reference for it.
        let r = unsafe { Ref::<Object<A>>::from_unsafe(&t) };
        let v = unsafe { luaV_finishget(self, &t, &k, false)? };

        drop(r);

        Ok(unsafe { Value::from_unsafe(&v) })
    }

    /// Multiply `lhs` with `rhs`.
    ///
    /// This method honor `__mul` metavalue.
    ///
    /// # Panics
    /// If either `lhs` or `rhs` was created frim different [Lua] instance.
    #[inline]
    pub fn mul(
        &self,
        lhs: impl Into<UnsafeValue<A>>,
        rhs: impl Into<UnsafeValue<A>>,
    ) -> Result<Value<'_, A>, Box<dyn core::error::Error>> {
        // Check operands.
        let lhs = lhs.into();
        let rhs = rhs.into();

        if unsafe { (lhs.tt_ & 1 << 6 != 0) && (*lhs.value_.gc).global != self.hdr.global } {
            panic!("attempt to multiply on a value created from different Lua");
        }

        if unsafe { (rhs.tt_ & 1 << 6 != 0) && (*rhs.value_.gc).global != self.hdr.global } {
            panic!("attempt to multiply on a value created from different Lua");
        }

        // Perform multiply.
        let r = unsafe { luaO_arith(self, Ops::Mul, &lhs, &rhs)? };

        Ok(unsafe { Value::from_unsafe(&r) })
    }

    /// Divide `lhs` with `rhs`.
    ///
    /// This method honor `__div` metavalue.
    ///
    /// # Panics
    /// If either `lhs` or `rhs` was created from different [Lua] instance.
    #[inline]
    pub fn div(
        &self,
        lhs: impl Into<UnsafeValue<A>>,
        rhs: impl Into<UnsafeValue<A>>,
    ) -> Result<Value<'_, A>, Box<dyn core::error::Error>> {
        // Check operands.
        let lhs = lhs.into();
        let rhs = rhs.into();

        if unsafe { (lhs.tt_ & 1 << 6 != 0) && (*lhs.value_.gc).global != self.hdr.global } {
            panic!("attempt to divide a value created from different Lua");
        }

        if unsafe { (rhs.tt_ & 1 << 6 != 0) && (*rhs.value_.gc).global != self.hdr.global } {
            panic!("attempt to divide a value created from different Lua");
        }

        // Perform divide.
        let r = unsafe { luaO_arith(self, Ops::NumDiv, &lhs, &rhs)? };

        Ok(unsafe { Value::from_unsafe(&r) })
    }

    /// Inserts a key-value pair into `t`.
    ///
    /// This method honor `__newindex` metavalue.
    ///
    /// # Panics
    /// If either `t`, `k` or `v` was created from different [Lua] instance.
    pub fn set(
        &self,
        t: impl Into<UnsafeValue<A>>,
        k: impl Into<UnsafeValue<A>>,
        v: impl Into<UnsafeValue<A>>,
    ) -> Result<(), Box<dyn core::error::Error>> {
        // Check arguments.
        let t = t.into();
        let k = k.into();
        let v = v.into();

        if unsafe { (t.tt_ & 1 << 6 != 0) && (*t.value_.gc).global != self.hdr.global } {
            panic!("attempt to divide a value created from different Lua");
        }

        if unsafe { (k.tt_ & 1 << 6 != 0) && (*k.value_.gc).global != self.hdr.global } {
            panic!("attempt to divide a value created from different Lua");
        }

        if unsafe { (v.tt_ & 1 << 6 != 0) && (*v.value_.gc).global != self.hdr.global } {
            panic!("attempt to divide a value created from different Lua");
        }

        // Get slot.
        let s = match t.tt_ & 0xf {
            5 => unsafe { luaH_get(t.value_.gc.cast(), &k) },
            _ => null(),
        };

        if unsafe { !s.is_null() && (*s).tt_ & 0xf != 0 } {
            let t = unsafe { t.value_.gc };
            let s = s.cast_mut();

            unsafe { (*s).tt_ = v.tt_ };
            unsafe { (*s).value_ = v.value_ };

            if unsafe { (v.tt_ & 1 << 6 != 0) && ((*t).marked.get() & 1 << 5 != 0) } {
                if unsafe { (*v.value_.gc).marked.is_white() } {
                    unsafe { self.hdr.global().gc.barrier_back(t) };
                }
            }
        } else {
            // luaV_finishset can call into user function to we need a strong reference for t here.
            // k and v will be passed to the function to we don't need one for them.
            let r = unsafe { Ref::<Object<A>>::from_unsafe(&t) };

            unsafe { luaV_finishset(self, &t, &k, &v, s)? };

            drop(r);
        }

        Ok(())
    }

    /// Reserves capacity for at least `additional` more elements to be pushed.
    ///
    /// Usually you don't need this method unless you want to distinguished [StackOverflow] caused by too many arguments.
    ///
    /// This has the same semantic as `lua_checkstack`.
    #[inline(always)]
    pub fn reserve(&self, additional: usize) -> Result<(), StackOverflow> {
        unsafe { lua_checkstack(self, additional, 0) }
    }
}

impl<A> Drop for Thread<A> {
    #[inline(never)]
    fn drop(&mut self) {
        *self.pending.get_mut() = None;

        unsafe { luaF_closeupval(self, self.stack.get()) };

        // Free CI.
        self.ci.set(self.base_ci.get());
        let mut ci = self.ci.get();
        let mut next = unsafe { (*ci).next };

        unsafe { (*ci).next = null_mut() };

        loop {
            ci = next;

            if ci.is_null() {
                break;
            }

            next = unsafe { (*ci).next };

            unsafe { luaM_free_(ci.cast(), size_of::<CallInfo>()) };
            self.nci.set(self.nci.get().wrapping_sub(1));
        }

        // Free stack.
        let layout = Layout::array::<StackValue<A>>(unsafe {
            self.stack_last.get().offset_from_unsigned(self.stack.get()) + 5
        })
        .unwrap();

        unsafe { alloc::alloc::dealloc(self.stack.get().cast(), layout) };
    }
}

impl<A> PartialEq for Thread<A> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        addr_eq(self, other)
    }
}

/// Result of [Thread::resume()] or [Thread::async_resume()].
pub enum Coroutine<'a, A, R> {
    /// The coroutine execution is suspended.
    Suspended(Vec<Value<'a, A>>),
    /// The coroutine execution is finished.
    Finished(R),
}

/// Implementation of [Future] to resume coroutine.
struct Resume<'a> {
    f: RefMut<'a, Pin<Box<dyn Future<Output = Result<(), Box<CallError>>>>>>,
    y: &'a Cell<Option<usize>>,
}

impl<'a> Future for Resume<'a> {
    type Output = Result<Option<usize>, Box<CallError>>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // Poll.
        let w = unsafe { Waker::new(cx as *mut Context as *const (), &YIELDABLE_WAKER) };

        if let Poll::Ready(r) = self.f.as_mut().poll(&mut Context::from_waker(&w)) {
            return Poll::Ready(r.map(|_| None));
        }

        // Check if yield.
        match self.y.take() {
            Some(v) => Poll::Ready(Ok(Some(v))),
            None => Poll::Pending,
        }
    }
}

/// Represents an error when attempt to use a thread that has active call.
#[derive(Debug, Error)]
#[error("thread busy")]
pub struct ThreadBusy;