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
use core::cell::Cell;
use std::sync::Arc;

use luau_vm::Thread as VmThread;
use luau_vm::state::{GcInterrupt as VmGcInterrupt, GcPhase as VmGcPhase, InterruptRequest};
use luau_vm::{VmErrorResult, VmResult};

use crate::callback::{raise_callback_error, raise_callback_vm_error};
use crate::error::{Error, Result};
use crate::lua::runtime::RuntimeData;
use crate::lua::{Lua, LuaRef, StackInfo};

/// The control action requested at an execution interrupt point.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum InterruptAction {
    /// Continue execution.
    #[default]
    Continue,
    /// Yield the active thread.
    Yield,
    /// Break the active thread.
    Break,
}

/// Controls when an interrupt handler is called.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum InterruptMode {
    /// Call the handler at every interrupt point.
    #[default]
    Continuous,
    /// Call the handler only after its handle is requested.
    Requested,
}

/// A thread-safe handle for requesting interrupt delivery.
#[must_use = "retain the handle to request interrupts"]
#[derive(Clone, Debug)]
pub struct InterruptHandle {
    request: Arc<InterruptRequest>,
}

/// The collector phase active immediately before a garbage-collection step.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GcPhase {
    /// The collector is between cycles.
    Pause,
    /// The collector is tracing reachable objects.
    Propagate,
    /// The collector is revisiting objects before the atomic phase.
    PropagateAgain,
    /// The collector is completing the mark phase.
    Atomic,
    /// The collector is reclaiming unreachable objects.
    Sweep,
}

/// The point at which a garbage-collection observer was invoked.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GcInterruptStage {
    /// Immediately before a collector step.
    BeforeStep,
    /// Immediately after a collector step.
    AfterStep {
        /// The collector phase active before the step.
        previous_phase: GcPhase,
    },
}

/// Context supplied at a Luau execution safepoint.
#[derive(Clone, Copy)]
pub struct ExecutionInterruptContext<'callback> {
    lua: LuaRef<'callback>,
    deferred: &'callback Cell<bool>,
}

/// Context supplied during pattern matching.
#[derive(Clone, Copy)]
pub struct PatternInterruptContext<'callback> {
    lua: LuaRef<'callback>,
    deferred: &'callback Cell<bool>,
}

/// Context supplied around a garbage-collection step.
#[derive(Clone, Copy)]
pub struct GcInterruptContext<'callback> {
    lua: LuaRef<'callback>,
    stage: GcInterruptStage,
    deferred: &'callback Cell<bool>,
}

/// A coherent set of callbacks for VM interrupt points.
///
/// Continuous handlers run at every interrupt point. A request-driven handler
/// runs only after its state's [`InterruptHandle`] is requested, which can be
/// done from another thread. While a callback is running, nested execution,
/// pattern, and garbage-collection interrupts are suppressed.
///
/// The first interrupt point consumes a request. Default methods defer it so an
/// unimplemented callback cannot consume a request intended for another point.
/// An implemented callback can defer delivery through its context.
pub trait InterruptHandler: 'static {
    /// Returns how this handler should be delivered.
    ///
    /// This is read when the handler is installed.
    fn mode(&self) -> InterruptMode {
        InterruptMode::Continuous
    }

    /// Called at Luau execution safepoints.
    fn execution(&self, context: ExecutionInterruptContext<'_>) -> Result<InterruptAction> {
        context.defer_interrupt();
        Ok(InterruptAction::Continue)
    }

    /// Called periodically during string pattern matching.
    fn pattern(&self, context: PatternInterruptContext<'_>) -> Result<()> {
        context.defer_interrupt();
        Ok(())
    }

    /// Called immediately before and after garbage-collection steps.
    fn garbage_collection(&self, context: GcInterruptContext<'_>) {
        context.defer_interrupt();
    }
}

type ExecutionCallback =
    Box<dyn for<'callback> Fn(ExecutionInterruptContext<'callback>) -> Result<InterruptAction>>;
type PatternCallback = Box<dyn for<'callback> Fn(PatternInterruptContext<'callback>) -> Result<()>>;
type GcCallback = Box<dyn for<'callback> Fn(GcInterruptContext<'callback>)>;

/// Closure-based builder for an [`InterruptHandler`].
#[derive(Default)]
pub struct InterruptHooks {
    mode: InterruptMode,
    execution: Option<ExecutionCallback>,
    pattern: Option<PatternCallback>,
    garbage_collection: Option<GcCallback>,
}

impl InterruptHooks {
    /// Creates an empty interrupt callback set.
    pub const fn new() -> Self {
        Self {
            mode: InterruptMode::Continuous,
            execution: None,
            pattern: None,
            garbage_collection: None,
        }
    }

    /// Sets how these callbacks should be delivered.
    #[must_use]
    pub const fn set_mode(mut self, mode: InterruptMode) -> Self {
        self.mode = mode;
        self
    }

    /// Sets the execution interrupt callback.
    #[must_use]
    pub fn on_execution<F>(mut self, callback: F) -> Self
    where
        F: for<'callback> Fn(ExecutionInterruptContext<'callback>) -> Result<InterruptAction>
            + 'static,
    {
        self.execution = Some(Box::new(callback));
        self
    }

    /// Sets the pattern interrupt callback.
    #[must_use]
    pub fn on_pattern<F>(mut self, callback: F) -> Self
    where
        F: for<'callback> Fn(PatternInterruptContext<'callback>) -> Result<()> + 'static,
    {
        self.pattern = Some(Box::new(callback));
        self
    }

    /// Sets the garbage-collection observer.
    #[must_use]
    pub fn on_garbage_collection<F>(mut self, callback: F) -> Self
    where
        F: for<'callback> Fn(GcInterruptContext<'callback>) + 'static,
    {
        self.garbage_collection = Some(Box::new(callback));
        self
    }
}

impl InterruptHandler for InterruptHooks {
    fn mode(&self) -> InterruptMode {
        self.mode
    }

    fn execution(&self, context: ExecutionInterruptContext<'_>) -> Result<InterruptAction> {
        match &self.execution {
            Some(callback) => callback(context),
            None => {
                context.defer_interrupt();
                Ok(InterruptAction::Continue)
            }
        }
    }

    fn pattern(&self, context: PatternInterruptContext<'_>) -> Result<()> {
        match &self.pattern {
            Some(callback) => callback(context),
            None => {
                context.defer_interrupt();
                Ok(())
            }
        }
    }

    fn garbage_collection(&self, context: GcInterruptContext<'_>) {
        if let Some(callback) = &self.garbage_collection {
            callback(context);
        } else {
            context.defer_interrupt();
        }
    }
}

impl Lua {
    /// Returns a handle for requesting a request-driven interrupt handler.
    pub fn interrupt_handle(&self) -> InterruptHandle {
        self.runtime.callbacks().interrupt_handle()
    }

    /// Installs the interrupt callbacks for this state.
    ///
    /// Use [`Lua::interrupt_handle`] to trigger a handler whose mode is
    /// [`InterruptMode::Requested`].
    pub fn set_interrupt_handler(&mut self, handler: impl InterruptHandler) {
        self.runtime
            .callbacks_mut()
            .set_interrupt_handler(Box::new(handler));
        self.install_callbacks();
    }

    /// Removes the interrupt callbacks from this state.
    pub fn remove_interrupt_handler(&mut self) {
        self.runtime.callbacks_mut().remove_interrupt_handler();
        self.install_callbacks();
    }
}

impl InterruptHandle {
    pub(in crate::hooks) fn new() -> Self {
        Self {
            request: Arc::new(InterruptRequest::new()),
        }
    }

    /// Requests delivery at the next interrupt point.
    ///
    /// Multiple requests made before delivery are coalesced.
    pub fn request(&self) {
        self.request.request();
    }

    pub(in crate::hooks) fn clear(&self) {
        self.request.clear();
    }

    pub(in crate::hooks) fn as_ptr(&self) -> *const InterruptRequest {
        Arc::as_ptr(&self.request)
    }
}

impl<'callback> ExecutionInterruptContext<'callback> {
    pub(in crate::hooks) const fn new(
        lua: LuaRef<'callback>,
        deferred: &'callback Cell<bool>,
    ) -> Self {
        Self { lua, deferred }
    }

    /// Returns a borrowed reference to the active Luau state.
    pub const fn lua(&self) -> LuaRef<'callback> {
        self.lua
    }

    /// Returns whether the active thread can yield.
    pub fn is_yieldable(&self) -> bool {
        self.lua.is_yieldable()
    }

    /// Defers a requested delivery to a later interrupt point.
    ///
    /// This has no effect on a continuous handler.
    pub fn defer_interrupt(&self) {
        self.deferred.set(true);
    }
}

impl<'callback> PatternInterruptContext<'callback> {
    pub(in crate::hooks) const fn new(
        lua: LuaRef<'callback>,
        deferred: &'callback Cell<bool>,
    ) -> Self {
        Self { lua, deferred }
    }

    /// Returns a borrowed reference to the active Luau state.
    pub const fn lua(&self) -> LuaRef<'callback> {
        self.lua
    }

    /// Defers a requested delivery to a later interrupt point.
    ///
    /// This has no effect on a continuous handler.
    pub fn defer_interrupt(&self) {
        self.deferred.set(true);
    }
}

impl<'callback> GcInterruptContext<'callback> {
    pub(in crate::hooks) const fn new(
        lua: LuaRef<'callback>,
        stage: GcInterruptStage,
        deferred: &'callback Cell<bool>,
    ) -> Self {
        Self {
            lua,
            stage,
            deferred,
        }
    }

    /// Returns the point around the collection step at which this callback ran.
    pub const fn stage(&self) -> GcInterruptStage {
        self.stage
    }

    /// Inspects the active stack frame at `level`.
    pub fn inspect_stack<R>(
        &self,
        level: usize,
        inspect: impl FnOnce(&StackInfo<'_>) -> R,
    ) -> Result<Option<R>> {
        self.lua.inspect_stack(level, inspect)
    }

    /// Defers a requested delivery to a later interrupt point.
    ///
    /// This has no effect on a continuous handler.
    pub fn defer_interrupt(&self) {
        self.deferred.set(true);
    }
}

pub(in crate::hooks) fn execution_interrupt(thread: &VmThread) -> VmResult {
    let runtime = RuntimeData::from_thread(thread);
    let result = runtime.callbacks().invoke_interrupt(|handler, delivery| {
        runtime.with_thread(thread, || {
            let lua = LuaRef::new(thread, runtime);
            let action = match handler.execution(ExecutionInterruptContext::new(lua, delivery)) {
                Ok(action) => action,
                Err(error) => return raise_callback_error(thread, runtime, error),
            };

            match action {
                InterruptAction::Continue => Ok(()),
                InterruptAction::Yield if lua.is_yieldable() => unsafe {
                    thread.yield_current(0).map(|_| ())
                },
                InterruptAction::Yield => raise_callback_error(
                    thread,
                    runtime,
                    Error::runtime(
                        "interrupt handler attempted to yield from a non-yieldable boundary",
                    ),
                ),
                InterruptAction::Break => unsafe { thread.break_current().map(|_| ()) },
            }
        })
    });
    let Some(result) = result else {
        return Ok(());
    };
    result
}

pub(in crate::hooks) fn pattern_interrupt(thread: &VmThread) -> VmErrorResult {
    let runtime = RuntimeData::from_thread(thread);
    let result = runtime.callbacks().invoke_interrupt(|handler, delivery| {
        runtime.with_thread(thread, || {
            let lua = LuaRef::new(thread, runtime);
            handler
                .pattern(PatternInterruptContext::new(lua, delivery))
                .or_else(|error| raise_callback_vm_error(thread, runtime, error))
        })
    });
    let Some(result) = result else {
        return Ok(());
    };
    result
}

pub(in crate::hooks) fn gc_interrupt(thread: &VmThread, event: VmGcInterrupt) -> VmErrorResult {
    let runtime = RuntimeData::from_thread(thread);
    let stage = match event {
        VmGcInterrupt::BeforeStep => GcInterruptStage::BeforeStep,
        VmGcInterrupt::AfterStep { previous_phase } => GcInterruptStage::AfterStep {
            previous_phase: map_gc_phase(previous_phase),
        },
    };
    let result = runtime.callbacks().invoke_interrupt(|handler, delivery| {
        runtime.with_thread(thread, || {
            handler.garbage_collection(GcInterruptContext::new(
                LuaRef::new(thread, runtime),
                stage,
                delivery,
            ))
        })
    });
    let Some(()) = result else {
        return Ok(());
    };
    Ok(())
}

const fn map_gc_phase(phase: VmGcPhase) -> GcPhase {
    match phase {
        VmGcPhase::Pause => GcPhase::Pause,
        VmGcPhase::Propagate => GcPhase::Propagate,
        VmGcPhase::PropagateAgain => GcPhase::PropagateAgain,
        VmGcPhase::Atomic => GcPhase::Atomic,
        VmGcPhase::Sweep => GcPhase::Sweep,
    }
}