remedy_lua/lib.rs
1//! RemedyLua: a Lua 5.4-compatible scripting language, entirely in safe Rust.
2//!
3//! - **Lua 5.4 semantics**: values, tables with array and hash parts, metatables and
4//! metamethods (`__index`, `__newindex`, `__call`, `__eq`, `__lt`, `__le`, `__concat`,
5//! `__len`, arithmetic and bitwise ones, `__close`, `__tostring`, `__name`, `__pairs`,
6//! `__metatable`, `__mode`), closures with upvalues, varargs, multiple returns, integer
7//! and float subtypes, `goto`, `<const>` and `<close>`, coroutines, `error`/`pcall`/
8//! `xpcall` with any value. `.lua` files load as plain Lua 5.4.
9//! - **RemedyLua additions** (`.rlua` files, [`Dialect::RemedyLua`]): optional type
10//! annotations (`local v: number = 1`, function signatures, table shapes, `type`
11//! aliases), checked by a gradual type checker ([`check`]), compound assignment
12//! (`+= -= *= /= //= %= ..=`), `continue`, and string interpolation (`` `hi {name}` ``).
13//! They are pure syntax at run time: they compile to the same bytecode plain Lua would.
14//! - **A strict superset of Lua 5.4**: C Lua's fixed implementation limits (200 locals,
15//! 255 upvalues, syntax nesting, C stack depth) are gone; only the host's budgets bound
16//! a program.
17//! - **Limits in every step** ([`Limits`]): fuel (each instruction, and library functions
18//! charge for their work: `string.rep`, `gsub`, `sort`…), a memory cap counted when
19//! memory is taken, call depth, nesting of library callbacks, string and output sizes.
20//! A call over its fuel or memory stops with [`Error::Limit`]; scripts cannot catch it
21//! (`pcall`, `xpcall`, `coroutine.resume` and `__close` all pass it on).
22//! - **An incremental collector**: marking and sweeping run in small steps paid for by
23//! allocation, so scripts run between frames without long pauses.
24//! - **A host API**: Rust functions ([`Lua::create_function`], [`Lua::register`]), userdata
25//! ([`Lua::create_userdata`]), owned data in and out ([`Data`]), and capabilities
26//! ([`Libs`]): a host chooses which libraries each script gets. There is no file, process
27//! or network access in the language itself, and `load` takes text only, when allowed.
28//!
29//! # Embedding: handles and their lifetimes
30//!
31//! A [`Value`] is `Copy` and does not keep what it names alive. A heap value the host holds
32//! is valid while one of these holds:
33//!
34//! - it is reachable from the script (a global, a table the script keeps);
35//! - a [`Root`] holds it ([`Lua::root`]);
36//! - the host made or got it outside a call ([`Lua::create_string`], [`Lua::create_table`],
37//! [`Lua::create_function`], [`Lua::create_userdata`], [`Lua::from_data`], [`Lua::get`],
38//! and the results of [`Lua::call`]/[`Lua::exec`]): then it is valid until the host's next
39//! [`Lua::call`] (or `exec`, `call_global`) returns, or until it calls
40//! [`Lua::collect_garbage`]. And so that a host that never calls cannot fill memory with
41//! them, they are let go when memory is full outside a call even after a collection
42//! (then refused as collected);
43//! - inside a host function: it is one of the function's arguments, or the function made it
44//! (valid until the function returns). The results of a [`Lua::call`] made inside one are
45//! valid until its next `call`.
46//!
47//! A stale handle is refused ([`Error::Host`]) or reads as nil; it never reaches another
48//! object, and a handle from another state is refused too. A panic that unwinds through a
49//! call (a host function's, a clock's, a print sink's) poisons the state: every later call
50//! returns [`Error::Host`]. The [reference](https://github.com/AhmiDarrow/RemedyLua/blob/main/docs/reference.md) has the full embedding guide.
51//!
52//! ```
53//! use remedy_lua::{Lua, Limits, Libs, Value};
54//! let mut lua = Lua::new(Limits::default(), Libs::STANDARD);
55//! let out = lua.exec("local t = {} for i = 1, 3 do t[i] = i * i end return #t, t[3]", "=demo").unwrap();
56//! assert!(matches!(out[..], [Value::Int(3), Value::Int(9)]));
57//! ```
58
59#![deny(unsafe_code)]
60// Some items are used only by the `front-oracle` feature or by tests.
61#![allow(dead_code)]
62
63mod ast;
64mod bytecode;
65mod check;
66mod compiler;
67mod debug;
68mod diag;
69mod fast;
70mod fmt;
71mod gctrace;
72#[cfg(feature = "front-oracle")]
73#[doc(hidden)]
74#[path = "front.rs"]
75pub mod __front;
76#[cfg(feature = "front-oracle")]
77mod front_oracle;
78mod heap;
79mod lexer;
80mod number;
81mod parser;
82mod shardmap;
83mod stdlib;
84mod table;
85mod value;
86mod vm;
87
88use std::any::Any;
89use std::sync::atomic::{AtomicBool, Ordering};
90use std::sync::Arc;
91
92pub use diag::{Diagnostic, Pos, Severity};
93pub use value::{FuncRef, StrRef, TableRef, ThreadRef, UdRef, Value};
94pub use stdlib::io::{IoError, Stream};
95pub use vm::Lua;
96#[doc(hidden)]
97pub use gctrace::{FULL_BEGAN_MARK, FULL_BEGAN_PAUSE, FULL_BEGAN_SWEEP, TraceOp, TraceRecord};
98
99/// What `io.open` asks for a file (`Lua::set_file_opener`): the name and the mode.
100pub(crate) type IoOpener = std::sync::Arc<dyn Fn(&str, &str) -> Result<Box<dyn Stream>, IoError> + Send + Sync>;
101
102use vm::{Args, Flow, LuaError};
103use lexer::Text;
104use stdlib::base::Src;
105
106/// Which language a source is in.
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108#[non_exhaustive]
109pub enum Dialect {
110 /// Plain Lua 5.4 (`.lua`).
111 Lua54,
112 /// RemedyLua (`.rlua`): Lua 5.4 plus annotations, compound assignment, `continue` and
113 /// interpolation.
114 RemedyLua,
115}
116
117impl Dialect {
118 /// The dialect of a chunk named `name`: RemedyLua for `.rlua` files, else Lua 5.4.
119 pub fn for_name(name: &str) -> Dialect {
120 if name.to_ascii_lowercase().ends_with(".rlua") { Dialect::RemedyLua } else { Dialect::Lua54 }
121 }
122}
123
124/// How much a state may use. Fuel is per call from the host; the rest hold always.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126#[non_exhaustive]
127pub struct Limits {
128 /// Steps one call from the host may take: one per instruction, plus what library
129 /// functions charge for their work, plus collector work.
130 pub fuel: u64,
131 /// Bytes the state's objects may hold, with the free slots of each kind's slab (a
132 /// collected object's slot stays resident until a new object of its kind reuses it,
133 /// or until no object of its kind sits past it). The collector paces on the objects
134 /// alone. Besides these, a state keeps at most 64 KiB (or 1/16 of this limit, if less)
135 /// of freed table buffers for reuse, uncharged.
136 pub memory: usize,
137 /// Lua call frames one thread may have (deeper recursion is a `stack overflow` error).
138 /// Unlimited by default: frames are memory like the value stack, charged to `memory`,
139 /// and a call whose frame does not fit is the same catchable `stack overflow`. Lua-to-Lua
140 /// calls use no native stack.
141 pub call_depth: usize,
142 /// How deeply library functions may call back into Lua (`sort` comparators,
143 /// `__tostring`, `gsub` functions inside each other).
144 pub native_depth: usize,
145 /// Stack slots one thread may have. Unlimited by default: the stack is memory like any
146 /// other, charged to `memory` before it grows.
147 pub stack_slots: usize,
148 /// The longest string a script may make.
149 pub string_len: usize,
150 /// Bytes `print` may write per call from the host (and, with no sink set, the most
151 /// [`Lua::take_output`]'s buffer holds; what does not fit is dropped).
152 pub output: usize,
153 /// The longest error message kept.
154 pub error_len: usize,
155 /// Bytes of the native stack one call may use for library functions that call back
156 /// into Lua (and for the parser's recursion). Lua-to-Lua calls use none.
157 pub stack_bytes: usize,
158 /// The seed of the state's hashing and of `math.random`'s first state; `None` (the
159 /// default) is a fresh random seed per state, which keeps a script from aiming keys at
160 /// one hash slot. A fixed seed is for replays and tests: the same program then gives the
161 /// same results, `pairs` order and fuel on every run (see `hash_seed`).
162 pub hash_seed: Option<u64>,
163 /// Strict Lua 5.4: leave out what stock C Lua 5.4 builds with `LUA_COMPAT_5_3` (its
164 /// makefile's default), which RemedyLua offers by default: `__le` emulated with `__lt`
165 /// and `math.atan2`/`cosh`/`sinh`/`tanh`/`pow`/`frexp`/`ldexp`/`log10`. Read when the
166 /// state is made, and fixed for its life ([`Lua::set_limits`] keeps it).
167 pub strict_5_4: bool,
168}
169
170impl Default for Limits {
171 /// 10 million steps, 64 MiB, 200 nested callbacks within 512 KiB of native stack, call
172 /// frames and a stack bounded only by memory, 16 MiB strings, 1 MiB of output, 4 KiB
173 /// messages.
174 fn default() -> Self {
175 Limits {
176 fuel: 10_000_000,
177 memory: 64 << 20,
178 call_depth: usize::MAX,
179 native_depth: 200,
180 stack_slots: usize::MAX / 64,
181 string_len: 16 << 20,
182 output: 1 << 20,
183 error_len: 4096,
184 stack_bytes: 512 << 10,
185 hash_seed: None,
186 strict_5_4: false,
187 }
188 }
189}
190
191/// `Limits`' plain setters: `name(n)` sets the field `name`.
192macro_rules! setters {
193 ($($f:ident: $t:ty,)*) => {
194 $(
195 #[doc = concat!("Sets `", stringify!($f), "`.")]
196 pub fn $f(mut self, n: $t) -> Self {
197 self.$f = n;
198 self
199 }
200 )*
201 };
202}
203
204impl Limits {
205 /// No budgets at all (for benchmarks and trusted code): fuel and memory are unlimited
206 /// and the depth and size limits are as large as the machine allows. The interpreter
207 /// still counts, so a state can be measured; nothing a script does can hit a limit
208 /// except the native stack guard, which protects the process.
209 pub fn unmetered() -> Self {
210 Limits {
211 fuel: u64::MAX,
212 memory: usize::MAX,
213 call_depth: usize::MAX,
214 stack_slots: usize::MAX / 64,
215 string_len: usize::MAX / 2,
216 output: usize::MAX,
217 error_len: usize::MAX / 2,
218 ..Limits::default()
219 }
220 }
221
222 /// A fixed seed for hashing, `math.random` and `math.randomseed()` without arguments, so
223 /// that runs replay exactly: the same program with the same seed gives the same results,
224 /// `pairs` order and fuel every time (with the fast loop on or off). For replays and
225 /// tests; production code should keep the default, a random seed per state, which
226 /// defends against hash flooding. Read when the state is made.
227 pub fn hash_seed(mut self, seed: u64) -> Self {
228 self.hash_seed = Some(seed);
229 self
230 }
231
232 /// Sets `strict_5_4`: no Lua 5.3 compatibility (see the field).
233 pub fn strict_5_4(mut self, on: bool) -> Self {
234 self.strict_5_4 = on;
235 self
236 }
237
238 setters! {
239 fuel: u64,
240 memory: usize,
241 call_depth: usize,
242 native_depth: usize,
243 string_len: usize,
244 output: usize,
245 stack_slots: usize,
246 error_len: usize,
247 stack_bytes: usize,
248 }
249}
250
251/// The libraries a script gets: its capabilities. Combine with `|`.
252#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
253pub struct Libs(u32);
254
255impl Libs {
256 /// Nothing.
257 pub const NONE: Libs = Libs(0);
258 /// The base functions (`type`, `pairs`, `pcall`, `setmetatable`, `tostring`…).
259 pub const BASE: Libs = Libs(1);
260 /// `string`, and the string metatable (`s:upper()`).
261 pub const STRING: Libs = Libs(1 << 1);
262 /// `table`.
263 pub const TABLE: Libs = Libs(1 << 2);
264 /// `math`.
265 pub const MATH: Libs = Libs(1 << 3);
266 /// `utf8`.
267 pub const UTF8: Libs = Libs(1 << 4);
268 /// `coroutine`.
269 pub const COROUTINE: Libs = Libs(1 << 5);
270 /// `os.time`, `os.clock`, `os.date`, `os.difftime`, `os.setlocale` (the `"C"` locale
271 /// only; `os.getenv` is `ENV`'s).
272 pub const OS: Libs = Libs(1 << 6);
273 /// `load` (source text only, never bytecode).
274 pub const LOAD: Libs = Libs(1 << 7);
275 /// `print` (to the host's sink or [`Lua::take_output`]).
276 pub const PRINT: Libs = Libs(1 << 8);
277 /// `collectgarbage` (count, step, collect; steps are paid for in fuel).
278 pub const GC: Libs = Libs(1 << 9);
279 /// `debug.traceback` and a read-only `debug.getinfo` (no hooks, locals, upvalues,
280 /// registry or functions handed out). Not in `SAFE`, `STANDARD` or `ALL`: a host opts in.
281 pub const DEBUG_INFO: Libs = Libs(1 << 10);
282 /// `require` and `package` (`loaded`, `preload`, `searchers`), with modules only from the
283 /// host ([`Lua::add_module`], [`Lua::set_module_loader`]): no search path, no files. Not
284 /// in `SAFE`, `STANDARD` or `ALL`: a host opts in.
285 pub const REQUIRE: Libs = Libs(1 << 11);
286 /// `os.getenv`, reading only what the host put in the state's map ([`Lua::set_env`]),
287 /// never the process environment. Not in `SAFE`, `STANDARD` or `ALL`: a host opts in.
288 pub const ENV: Libs = Libs(1 << 12);
289 /// `io` over streams the host gives: `io.stdin`, `io.stdout` and `io.stderr` are the
290 /// host's ([`Lua::set_stdin`], [`Lua::set_stdout`], [`Lua::set_stderr`]; by default
291 /// stdin is empty and the others write where `print` writes), and `io.open` asks the
292 /// host's opener ([`Lua::set_file_opener`]): no file system, no process (`io.popen` and
293 /// `io.tmpfile` are absent). Not in `SAFE`, `STANDARD` or `ALL`: a host opts in.
294 pub const IO: Libs = Libs(1 << 13);
295 /// Everything but `load`, `print` and `collectgarbage`: what untrusted code gets.
296 pub const SAFE: Libs = Libs(0b111_1111);
297 /// The safe set plus `print` and `collectgarbage`.
298 pub const STANDARD: Libs = Libs(0b111_1111 | (1 << 8) | (1 << 9));
299 /// Every library of the standard set, `load` included (not the opt-in `DEBUG_INFO`,
300 /// `REQUIRE`, `ENV` and `IO`).
301 pub const ALL: Libs = Libs(0b11_1111_1111);
302
303 /// Both sets (`|` in a `const`).
304 pub const fn union(self, other: Libs) -> Libs {
305 Libs(self.0 | other.0)
306 }
307
308 /// Whether `other` is all included.
309 pub fn contains(self, other: Libs) -> bool {
310 self.0 & other.0 == other.0
311 }
312}
313
314impl std::ops::BitOr for Libs {
315 type Output = Libs;
316 fn bitor(self, rhs: Libs) -> Libs {
317 Libs(self.0 | rhs.0)
318 }
319}
320
321impl std::ops::Sub for Libs {
322 type Output = Libs;
323 fn sub(self, rhs: Libs) -> Libs {
324 Libs(self.0 & !rhs.0)
325 }
326}
327
328/// A module's source for `require` (`Libs::REQUIRE`), from the host: Lua source text,
329/// compiled as `load` compiles it (text only, charged the same) as chunk `@origin`.
330/// `require` gives `origin` as its second result, as C Lua gives a module's file name.
331#[derive(Clone, Debug)]
332pub struct ModuleSource {
333 /// The source text.
334 pub code: Arc<[u8]>,
335 /// Where it came from, for messages and tracebacks (`origin:3: ...`).
336 pub origin: String,
337}
338
339impl ModuleSource {
340 /// A module's source, shown in messages as `origin`.
341 pub fn new(code: impl AsRef<[u8]>, origin: impl Into<String>) -> ModuleSource {
342 ModuleSource { code: Arc::from(code.as_ref()), origin: origin.into() }
343 }
344}
345
346/// The host's module loader (`Lua::set_module_loader`): the source of the module named,
347/// or `None` when the host has no such module. It runs inside the script's call, on the
348/// host's own time; it gets no access to the state.
349pub type ModuleLoader = Arc<dyn Fn(&str) -> Option<ModuleSource> + Send + Sync>;
350
351/// Which limit stopped a call. More kinds may come: match with a `_` arm.
352#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
353#[non_exhaustive]
354pub enum LimitKind {
355 /// It ran out of fuel (took too many steps).
356 Fuel,
357 /// It used too much memory, or made a string too long.
358 Memory,
359 /// The host interrupted it ([`Interrupt`]).
360 Interrupted,
361 /// It ran past the host's time limit ([`Lua::set_time_limit`]).
362 Time,
363}
364
365/// The host's clock for time limits: the time now, from any fixed start (a wall clock, or
366/// a thread's CPU clock).
367pub type Clock = std::sync::Arc<dyn Fn() -> std::time::Duration + Send + Sync>;
368
369/// The `os` library's clocks where the platform has them: the system time, and the time
370/// since the state was made. A browser (`wasm32-unknown-unknown`) has neither in `std`:
371/// there the host supplies them ([`Lua::set_os_clocks`]), or they read as 0.
372#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
373pub(crate) fn default_os_clocks() -> (Option<Clock>, Option<Clock>) {
374 let start = std::time::Instant::now();
375 let wall: Clock = Arc::new(|| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default());
376 (Some(wall), Some(Arc::new(move || start.elapsed())))
377}
378
379#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
380pub(crate) fn default_os_clocks() -> (Option<Clock>, Option<Clock>) {
381 (None, None)
382}
383
384/// A handle that stops the state's running call from any thread: [`Interrupt::interrupt`]
385/// makes the call stop with [`Error::Limit`]`(`[`LimitKind::Interrupted`]`)` within a fraction
386/// of a millisecond of work, wherever it is (a loop, a long `gsub` or `sort`, a coroutine),
387/// and scripts cannot catch it. It stays set until [`Interrupt::reset`], and while it is set
388/// every entry into the state (a call, or making a value) stops at once.
389#[derive(Clone, Debug)]
390pub struct Interrupt(Arc<AtomicBool>);
391
392impl Interrupt {
393 /// Asks the running call (and every call after it, until reset) to stop.
394 pub fn interrupt(&self) {
395 self.0.store(true, Ordering::Relaxed);
396 }
397
398 /// Lets calls run again. A host that reuses one state for many calls resets the
399 /// handle before each call it wants to run.
400 pub fn reset(&self) {
401 self.0.store(false, Ordering::Relaxed);
402 }
403
404 /// Whether it is set.
405 pub fn is_set(&self) -> bool {
406 self.0.load(Ordering::Relaxed)
407 }
408}
409
410/// What went wrong.
411#[derive(Clone, Debug, PartialEq, Eq)]
412#[non_exhaustive]
413pub enum Error {
414 /// The source does not compile.
415 Syntax(Diagnostic),
416 /// The script raised an error that nothing caught.
417 Runtime {
418 /// The error, as text (`chunk:line: message` for messages raised by `error` or the
419 /// machine; other values are described).
420 message: String,
421 /// Where it happened.
422 traceback: String,
423 },
424 /// The call ran past a limit and was stopped.
425 Limit(LimitKind),
426 /// The host used the API wrongly (a value whose object was collected, a value that
427 /// cannot become data).
428 Host(String),
429}
430
431impl Error {
432 /// A runtime error with this message, for host functions to return.
433 pub fn runtime(message: impl Into<String>) -> Error {
434 Error::Runtime { message: message.into(), traceback: String::new() }
435 }
436
437 /// The message alone.
438 pub fn message(&self) -> String {
439 match self {
440 Error::Syntax(d) => d.to_string(),
441 Error::Runtime { message, .. } => message.clone(),
442 Error::Limit(LimitKind::Fuel) => "the script ran too long and was stopped".into(),
443 Error::Limit(LimitKind::Memory) => "the script used too much memory and was stopped".into(),
444 Error::Limit(LimitKind::Interrupted) => "the script was interrupted by the host".into(),
445 Error::Limit(LimitKind::Time) => "the script ran past its time limit and was stopped".into(),
446 Error::Host(m) => m.clone(),
447 }
448 }
449}
450
451impl std::fmt::Display for Error {
452 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453 f.write_str(&self.message())
454 }
455}
456
457impl std::error::Error for Error {}
458
459/// A value kept alive while this handle lives (values themselves do not keep objects
460/// alive; see [`Value`]).
461#[derive(Clone, Debug)]
462pub struct Root {
463 value: Value,
464 _alive: Arc<()>,
465}
466
467impl Root {
468 /// The value.
469 pub fn value(&self) -> Value {
470 self.value
471 }
472}
473
474/// Owned data that crosses between Rust and scripts by copy: no functions, userdata or
475/// threads; tables become key-value lists in traversal order. More variants may come:
476/// match with a `_` arm.
477#[derive(Clone, Debug, PartialEq)]
478#[non_exhaustive]
479pub enum Data {
480 /// `nil`.
481 Nil,
482 /// A boolean.
483 Bool(bool),
484 /// An integer.
485 Int(i64),
486 /// A float.
487 Num(f64),
488 /// A string (invalid UTF-8 replaced).
489 Str(String),
490 /// A table's entries.
491 Table(Vec<(Data, Data)>),
492}
493
494impl Data {
495 /// The value under string key `key`, for tables.
496 pub fn get(&self, key: &str) -> Option<&Data> {
497 match self {
498 Data::Table(pairs) => pairs.iter().find(|(k, _)| matches!(k, Data::Str(s) if s == key)).map(|(_, v)| v),
499 _ => None,
500 }
501 }
502}
503
504/// The deepest nesting [`Lua::to_data`] follows, whatever [`DataLimits::depth`] asks.
505pub const MAX_DATA_DEPTH: usize = 200;
506
507/// Bounds for copying a value out as [`Data`].
508#[derive(Clone, Copy, Debug)]
509pub struct DataLimits {
510 /// Deepest nesting (at most `MAX_DATA_DEPTH`, 200: each level is a native call).
511 pub depth: usize,
512 /// Most values in all.
513 pub nodes: usize,
514 /// Most string bytes in all.
515 pub bytes: usize,
516}
517
518impl Default for DataLimits {
519 /// 32 deep, 200 000 values, 8 MiB.
520 fn default() -> Self {
521 DataLimits { depth: 32, nodes: 200_000, bytes: 8 << 20 }
522 }
523}
524
525/// Parses `source` (a `.rlua` or `.lua` file, by `name`'s extension) without running
526/// anything, and type-checks a `.rlua` file's annotations: its diagnostics. A syntax error
527/// is the only diagnostic (the first one). Otherwise, for `.rlua`, the type errors
528/// (`Severity::Error`, at most 500), and a `Severity::Warning` if the check stopped at its
529/// work or memory bound. A plain `.lua` file has no annotations, so it gets none.
530/// Checking never changes how the program runs (see [The type checker](https://github.com/AhmiDarrow/RemedyLua/blob/main/docs/reference.md#the-type-checker)).
531///
532/// The parse may use 1 KiB per source byte plus 64 MiB ("not enough memory" past it), and
533/// the checker as much again for its own tables; its work is linear in the source.
534pub fn check(source: &[u8], name: &str) -> Vec<Diagnostic> {
535 let dialect = Dialect::for_name(name);
536 let memory = parser::host_memory(source.len());
537 match parser::parse_within(source, name, dialect, memory) {
538 Err(d) => vec![d],
539 Ok(block) if dialect == Dialect::RemedyLua => check::check(&block, name, source.len(), memory),
540 Ok(_) => Vec::new(),
541 }
542}
543
544/// Re-indents `source` (four spaces a level, normalized spacing at line starts), keeping
545/// comments and everything else as written. Fails when the source does not parse (within
546/// the memory [`check`] may use).
547pub fn format(source: &str, name: &str) -> Result<String, Diagnostic> {
548 fmt::format(source, name, Dialect::for_name(name))
549}
550
551fn to_error(lua: &mut Lua, e: LuaError) -> Error {
552 match *e.kind() {
553 vm::ErrorKind::Limit(k) => Error::Limit(k),
554 vm::ErrorKind::Pending => Error::Host("the call is pending".into()),
555 vm::ErrorKind::Value(v) => {
556 let message = lua.describe_error(v);
557 // Kept (rooted) so a host function re-raising it passes the object on.
558 lua.last_error = Some((message.clone(), v));
559 Error::Runtime { message, traceback: lua.take_traceback() }
560 }
561 _ => match lua.normalize(e) {
562 Ok(v) => {
563 let message = lua.describe_error(v);
564 Error::Runtime { message, traceback: lua.take_traceback() }
565 }
566 Err(e) => e.limit().map_or_else(|| Error::runtime("error"), Error::Limit),
567 },
568 }
569}
570
571/// A state dropped by the host frees what compiles from the host left to free on this
572/// thread (`diag::free_deferred`; nothing waits for it to return promptly here).
573impl Drop for Lua {
574 fn drop(&mut self) {
575 crate::diag::free_deferred(&mut self.deferred, || false);
576 }
577}
578
579impl Lua {
580 /// A host function's error, as the script sees it: the very error object when it is
581 /// one that just came out of the state (`lua.call` from the host function).
582 fn from_host_error(&mut self, e: Error) -> LuaError {
583 match e {
584 Error::Limit(k) => LuaError::Limit(k),
585 Error::Runtime { message, .. } => {
586 if let Some((text, v)) = self.last_error.take()
587 && text == message
588 && self.heap.is_live(v)
589 {
590 return LuaError::Value(v);
591 }
592 LuaError::Msg(message)
593 }
594 other => LuaError::Msg(other.message()),
595 }
596 }
597}
598
599impl Lua {
600 /// A state with `limits`, offering `libs`.
601 pub fn new(limits: Limits, libs: Libs) -> Lua {
602 Lua::new_vm(limits, libs)
603 }
604
605 fn describe_error(&self, v: Value) -> String {
606 match v {
607 Value::Str(s) => {
608 let b = self.bytes(s);
609 let cut = b.len().min(self.limits.error_len);
610 String::from_utf8_lossy(b.get(..cut).unwrap_or_default()).into_owned()
611 }
612 Value::Int(i) => i.to_string(),
613 Value::Num(f) => number::fmt_float(f),
614 Value::Nil => "nil".into(),
615 // As `lua.c`'s message handler: `luaL_typename`, never a `__name`.
616 other => format!("(error object is a {} value)", other.type_name()),
617 }
618 }
619
620 fn check_live(&mut self, v: Value) -> Result<(), Error> {
621 // An atomic step a call before stopped in is finished first: while it is
622 // suspended, a weak table's value it is about to clear still reads as live, and
623 // stored from the host it was freed in a live table (SEC7-H2). (Only between
624 // calls: the outermost entry finishes it, charged there.)
625 if self.entry == 0 && self.heap.atomic_suspended() {
626 self.enter(|_| Ok(()))?;
627 }
628 self.check_live_now(v)
629 }
630
631 /// `check_live` without finishing a suspended atomic step: for reads, which store
632 /// nothing.
633 fn check_live_now(&self, v: Value) -> Result<(), Error> {
634 // S5API-9: also what refuses a poisoned state in the entries that do not go through
635 // `enter` (`set_metatable` wrote into it, `to_data` read it as if nothing happened).
636 if self.poisoned {
637 return Err(Error::Host("a panic in an earlier call left this state unusable".into()));
638 }
639 self.not_pending()?;
640 if self.heap.is_live(v) { Ok(()) } else { Err(Error::Host("a value whose object was collected".into())) }
641 }
642
643 /// While a call is paused at a collector step the state is in the middle of it:
644 /// nothing else may run in it, write to it or allocate in it (SEC7-G1).
645 fn not_pending(&self) -> Result<(), Error> {
646 if self.entry == 0 && (self.pending_call.is_some() || self.pending_start.is_some()) {
647 return Err(Error::Host("a call is pending: resume or drop it first".into()));
648 }
649 Ok(())
650 }
651
652 /// Runs `f` as an entry from the host: fuel is reset for the outermost one.
653 fn enter<T>(&mut self, f: impl FnOnce(&mut Lua) -> Result<T, LuaError>) -> Result<T, Error> {
654 self.not_pending()?;
655 self.enter_as(true, f)
656 }
657
658 /// `enter`; `fresh` false: a paused call resumed, which keeps its fuel, its deadline
659 /// (the absolute one it started with) and what it carried: it is the same call.
660 fn enter_as<T>(&mut self, fresh: bool, f: impl FnOnce(&mut Lua) -> Result<T, LuaError>) -> Result<T, Error> {
661 if self.poisoned {
662 return Err(Error::Host("a panic in an earlier call left this state unusable".into()));
663 }
664 // The counters below are per thread: a state run from another state's host function
665 // keeps the outer state's uncharged steps aside and gives them back when it returns,
666 // so neither bills the other (S6-RES-4).
667 let mut outer = None;
668 if self.entry == 0 {
669 // What a compile left to free, before this call's clock.
670 self.free_deferred();
671 // Probe steps of host-side table access are not the script's.
672 outer = Some((crate::table::take_probes(), crate::debug::take_work()));
673 // The host's poll starts (SEC7-G1).
674 self.heap.poll_start = self.heap.scanned;
675 self.heap.poll_objs = 0;
676 self.stack_base = stack_pos();
677 }
678 if self.entry == 0 && fresh {
679 let total = i64::try_from(self.limits.fuel).unwrap_or(i64::MAX);
680 self.fuel = total.min(vm::FUEL_SLICE);
681 self.reserve = total - self.fuel;
682 // Collector work under a unit is carried within a call only (S5C-1), so a
683 // call's fuel never depends on what calls before it did. Marking work a step
684 // did past its budget (`gc_mark_over`) is not dropped, though: it is owed, as an
685 // atomic phase's is (`atomic_owed`), and charged by the steps of the calls after
686 // (dropped, a host stepping the collector a call at a time had that work
687 // uncharged, by an amount that followed the order objects are reached in, so
688 // the seed: S6GC-2e-R).
689 self.gc_work_carry = 0;
690 self.deadline = self.time_limit.as_ref().map(|(clock, d)| clock().saturating_add(*d));
691 // What long table resizes look at between pieces.
692 let w = crate::stdlib::pattern::Watch::of(self);
693 self.heap.mem.deadline = Some(w);
694 self.heap.mem.refused = false;
695 self.output_used = 0;
696 self.limit_hit = None;
697 self.stopped_left = None;
698 self.last_error = None;
699 // The last call's results were valid until now. A long list is not kept: one a
700 // limit cut short (or the host's results) was outside the account (SEC7-1).
701 crate::vm::clear_list(&mut self.rets);
702 crate::vm::clear_list(&mut self.host_rets);
703 self.host_rets_base = 0;
704 }
705 // An interrupt the host set stops every call until it is reset, even one that would
706 // finish before its first look at it.
707 if self.entry == 0 && self.interrupt.load(Ordering::Relaxed) {
708 if let Some((probes, work)) = outer {
709 crate::table::put_probes(probes);
710 crate::debug::put_work(work);
711 }
712 self.limit_hit = Some(LimitKind::Interrupted);
713 return Err(Error::Limit(LimitKind::Interrupted));
714 }
715 self.entry += 1;
716 // A host that catches a panic from a host function must not get the state back
717 // mid-instruction (wrong thread, frames and fuel): it is poisoned, like a mutex.
718 let outermost = self.entry == 1;
719 let r = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
720 // An atomic phase a call before stopped at its fuel is finished first (S6GC-2e).
721 // (A paused call resumed goes on with its own step instead.)
722 if outermost && fresh {
723 self.resume_atomic_pausable()?;
724 }
725 f(self)
726 })) {
727 Ok(r) => r,
728 Err(p) => {
729 self.poisoned = true;
730 // A host function further out may catch this panic and return normally: the
731 // script it returns to must stop at once (uncatchably), not run on.
732 self.limit_hit = Some(LimitKind::Interrupted);
733 self.fuel = -1;
734 self.reserve = 0;
735 std::panic::resume_unwind(p)
736 }
737 };
738 self.entry -= 1;
739 if let Some((probes, work)) = outer {
740 // This call's last uncharged steps are host-side now (as at its start).
741 crate::table::put_probes(probes);
742 crate::debug::put_work(work);
743 }
744 if self.poisoned {
745 return Err(Error::Host("a panic in an earlier call left this state unusable".into()));
746 }
747 if let Some(k) = r.as_ref().err().and_then(LuaError::limit) {
748 // Sticky for the rest of this call from the host. The fuel used stays what ran
749 // (the innermost call from the host sees the limit first).
750 self.limit_hit = Some(k);
751 if self.stopped_left.is_none() {
752 self.stopped_left = Some(self.fuel_left());
753 }
754 self.fuel = -1;
755 self.reserve = 0;
756 }
757 if self.entry == 0 {
758 self.clear_idle_stack();
759 }
760 r.map_err(|e| to_error(self, e))
761 }
762
763 /// Compiles `source` as a chunk named `name` (`=name` prints as `name` in messages,
764 /// `@file` as a file name); the dialect follows the name's extension. The chunk is a
765 /// function: call it to run it.
766 pub fn load(&mut self, source: impl AsRef<[u8]>, name: &str) -> Result<Root, Error> {
767 let dialect = Dialect::for_name(name.trim_start_matches(['=', '@']));
768 self.load_with(source, name, dialect)
769 }
770
771 /// [`Lua::load`] in a given dialect.
772 pub fn load_with(&mut self, source: impl AsRef<[u8]>, name: &str, dialect: Dialect) -> Result<Root, Error> {
773 // Compiling allocates (and may collect) outside `enter`: refused like every other
774 // entry once a panic left the state mid-instruction.
775 if self.poisoned {
776 return Err(Error::Host("a panic in an earlier call left this state unusable".into()));
777 }
778 let env = Value::Table(self.globals);
779 let mut r = self.compile_chunk(&mut Src::Text(source.as_ref()), name, dialect, env);
780 if matches!(r, Err(CompileError::Memory)) {
781 // Garbage may be what fills memory: collect and try again.
782 self.collect_garbage()?;
783 r = self.compile_chunk(&mut Src::Text(source.as_ref()), name, dialect, env);
784 }
785 let f = r.map_err(|e| match e {
786 CompileError::Syntax(d) => Error::Syntax(d),
787 CompileError::Memory => Error::Limit(LimitKind::Memory),
788 CompileError::Limit(k) => Error::Limit(k),
789 })?;
790 let root = self.root(f);
791 // `debug.getinfo`'s `source`. Out of memory, it stays unset (and reads as the
792 // short name).
793 if let Ok(n) = self.new_str(name.as_bytes()) {
794 self.set_chunk_name(f, n);
795 }
796 Ok(root)
797 }
798
799 pub(crate) fn compile_chunk(
800 &mut self,
801 source: &mut Src<'_>,
802 name: &str,
803 dialect: Dialect,
804 env: Value,
805 ) -> Result<Value, CompileError> {
806 if self.entry == 0 {
807 self.free_deferred();
808 }
809 if source.bytes().first() == Some(&0x1b) {
810 // Named as every other message names the chunk (it said `=t:1:`; S5C-FRONT-8).
811 let d = Diagnostic::error(&vm::chunk_id(name), Pos { line: 1, col: 1 }, "attempt to load a binary chunk (bytecode is not accepted)");
812 return Err(CompileError::Syntax(d));
813 }
814 // The host's interrupt stops a long compile too, and so does the running call's
815 // deadline (a load from the host outside any call has none).
816 let mut watch = crate::stdlib::pattern::Watch::of(self);
817 if self.entry == 0 {
818 watch = watch.without_deadline();
819 }
820 // Inside a call, the compiler's scan work is fuel (`diag::compile_work`); a load
821 // from the host outside any call has no fuel, only the interrupt.
822 let in_call = self.entry > 0;
823 let max_work = if in_call { self.fuel_left().saturating_mul(COMPILE_WORK_PER_FUEL) } else { u64::MAX };
824 let (r, stop, work) =
825 crate::diag::watched(watch, max_work, || self.compile_watched(source, name, dialect, env));
826 self.adopt_deferred();
827 if in_call
828 && work >= COMPILE_WORK_PER_FUEL
829 && let Some(k) = self.charge(work / COMPILE_WORK_PER_FUEL).err().as_ref().and_then(vm::LuaError::limit)
830 {
831 return Err(CompileError::Limit(k));
832 }
833 match stop {
834 Some(k) => Err(CompileError::Limit(k)),
835 None => r,
836 }
837 }
838
839 /// Takes what the compile just run left to free a piece at a time, charged to this
840 /// state's memory until it is freed (S6-FRONT-4: it sat uncharged until the next call
841 /// from the host). Held for the account only: not debt for the collector to work off.
842 fn adopt_deferred(&mut self) {
843 for (v, bytes) in crate::diag::take_deferred() {
844 self.heap.mem.used = self.heap.mem.used.saturating_add(bytes);
845 self.deferred.push((v, bytes));
846 }
847 }
848
849 /// Frees what compiles left, a piece at a time, until the host's interrupt says to
850 /// stop; what is freed is released from the account.
851 fn free_deferred(&mut self) {
852 if self.deferred.is_empty() {
853 return;
854 }
855 let flag = std::sync::Arc::clone(&self.interrupt);
856 let released = crate::diag::free_deferred(&mut self.deferred, || flag.load(std::sync::atomic::Ordering::Relaxed));
857 self.heap.mem.release(released);
858 }
859
860 fn compile_watched(&mut self, source: &mut Src<'_>, name: &str, dialect: Dialect, env: Value) -> Result<Value, CompileError> {
861 // From the host, what the compile built is freed at its next call, a piece at a
862 // time, watching the interrupt (S6-FRONT-4); inside a call, at once.
863 let host = self.entry == 0;
864 let was = crate::diag::set_deferring(host);
865 let r = self.compile_parsed(source, name, dialect, env, host);
866 crate::diag::set_deferring(was);
867 r
868 }
869
870 fn compile_parsed(&mut self, source: &mut Src<'_>, name: &str, dialect: Dialect, env: Value, host: bool) -> Result<Value, CompileError> {
871 let display = vm::chunk_id(name);
872 // (The table buffer pool's bytes are room too: the charge after the parse gives
873 // them back if it needs them, `Mem::fits`.)
874 let room = self.heap.mem.cap.saturating_sub(self.memory_used());
875 // A reader is called as the lexer reaches the end of what it gave.
876 let parsed = match source {
877 Src::Text(s) => parser::parse_counted(Text::Whole(s), &display, dialect, room, host).0,
878 Src::Reader(st, buf) => {
879 // While the reader runs, what the parse holds counts as used; after, the
880 // parse has the room the reader left it (SEC-M13).
881 let mut pull = |b: &mut Vec<u8>| {
882 let (held, _) = crate::diag::parse_reading((None, None));
883 self.heap.mem.used = self.heap.mem.used.saturating_add(held);
884 let more = crate::stdlib::base::read_piece(self, st, b);
885 self.heap.mem.used = self.heap.mem.used.saturating_sub(held);
886 crate::diag::parse_reading((None, Some(self.heap.mem.cap.saturating_sub(self.heap.mem.used))));
887 more
888 };
889 let (r, text) = parser::parse_counted(Text::Read(std::mem::take(*buf), Some(&mut pull)), &display, dialect, room, host);
890 **buf = text.take();
891 r
892 }
893 };
894 let source = source.bytes();
895 let (block, tree) = match parsed {
896 Ok(b) => b,
897 Err(d) if d.message == "not enough memory" => return Err(CompileError::Memory),
898 // Stopped by the host: no second parse for the message (`watched` reports it).
899 Err(d) if d.message == crate::diag::COMPILE_STOPPED => return Err(CompileError::Syntax(d)),
900 Err(d) => return Err(CompileError::Syntax(self.first_error(source, &display, dialect, room, d))),
901 };
902 // The tree is held while it is compiled: charged, so the compiler's own memory is
903 // what is left beside it (S6-FRONT-3: the two were each bounded by the room left,
904 // and a compile held up to twice the limit).
905 // (Held for the compile only: not debt for the collector to work off.)
906 if !self.heap.mem.fits(tree) {
907 return Err(CompileError::Memory);
908 }
909 self.heap.mem.used += tree;
910 let compiled = compiler::compile(&block, &display, &mut self.heap);
911 self.heap.mem.release(tree);
912 let proto = match compiled {
913 Ok(p) => {
914 if host {
915 crate::diag::defer_tree(block, parser::tree_bytes());
916 } else {
917 // Inside a call: now, a node at a time between looks (a 6 MB source's
918 // tree took up to 120 ms to drop in one go).
919 // (Told to stop, the rest is deferred and charged as the host path's is.)
920 crate::diag::free_watched(crate::ast::Dropper::of_block(block).with_bytes(parser::tree_bytes()));
921 }
922 p
923 }
924 Err(d) => {
925 if d.message == crate::diag::COMPILE_STOPPED || host {
926 // Freed later, so the stopped compile returns at once (S5C-FRONT-12).
927 crate::diag::defer_tree(block, parser::tree_bytes());
928 }
929 return Err(if d.message == "not enough memory" { CompileError::Memory } else { CompileError::Syntax(d) });
930 }
931 };
932 self.heap.blocked += 1;
933 let r = (|| {
934 self.heap.mem.charge(heap::UPVAL_SIZE + heap::FUNC_BASE + heap::boxed(8)).map_err(|()| CompileError::Memory)?;
935 let up = self.heap.new_upval_charged(heap::Upval::Closed(env));
936 Ok(self.heap.new_func_charged(heap::Func::Lua { proto, upvals: vec![up].into_boxed_slice() }))
937 })();
938 self.heap.blocked -= 1;
939 let f = Value::Func(r?);
940 self.hold(f);
941 Ok(f)
942 }
943
944 /// The error C Lua reports for `source`, which has the syntax error `syntax`: C Lua
945 /// compiles as it parses, so a compile error before that point comes first.
946 fn first_error(&mut self, source: &[u8], name: &str, dialect: Dialect, room: usize, syntax: Diagnostic) -> Diagnostic {
947 let Some((block, cut, follow)) = parser::prefix(source, name, dialect, room) else { return syntax };
948 match compiler::compile_prefix(&block, name, &mut self.heap, cut, follow) {
949 Err(d) if d.message != "not enough memory" && d.line <= syntax.line => d,
950 _ => syntax,
951 }
952 }
953
954 /// Compiles and runs `source`: what it returns.
955 pub fn exec(&mut self, source: impl AsRef<[u8]>, name: &str) -> Result<Vec<Value>, Error> {
956 let f = self.load(source, name)?;
957 self.call(f.value(), &[])
958 }
959
960 /// Calls `f` with `args` (a function, or a value with `__call`): its results. Fuel and
961 /// the time limit start afresh for a call from the host (not for one made inside a host
962 /// function). From the host, the results stay valid until its next `call` returns, and
963 /// the values it made before this call are released when it returns; inside a host
964 /// function, until that function's next `call` (see [the crate docs](crate)). Root a
965 /// value to keep it longer.
966 pub fn call(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, Error> {
967 // The host's poll, traced (SEC7-G1).
968 if self.entry == 0 && self.heap.mem.trace.is_some() {
969 let p = self.trace_poll();
970 let r = self.call_now(f, args);
971 if let Some(p) = p {
972 self.trace_poll_end(p);
973 }
974 return r;
975 }
976 self.call_now(f, args)
977 }
978
979 fn call_now(&mut self, f: Value, args: &[Value]) -> Result<Vec<Value>, Error> {
980 if let Err(e) = self.check_live(f) {
981 // Paused in the entry that finishes a suspended atomic step first (SEC7-G1):
982 // the call is pending before it started; it goes on from there.
983 if self.entry == 0 && self.gc_pending.is_some() && self.pending_call.is_none() {
984 self.pending_start = Some((f, args.to_vec()));
985 }
986 return Err(e);
987 }
988 for a in args {
989 self.check_live(*a)?;
990 }
991 let mark = self.scratch.len();
992 let out = self.enter(|l| {
993 l.scratch.push(f);
994 l.scratch.extend_from_slice(args);
995 l.call_nested(f, args)
996 });
997 // Results are kept reachable until the next call (in `rets`), not for the rest of
998 // a host function that calls in a loop.
999 self.scratch.truncate(mark);
1000 self.after_host_call(out)
1001 }
1002
1003 /// What `call` does with a call's results (a resumed one's too).
1004 fn after_host_call(&mut self, out: Result<Vec<Value>, Error>) -> Result<Vec<Value>, Error> {
1005 if self.entry == 0 {
1006 // From the host itself: what it held until now may go, the results stay.
1007 self.held.clear();
1008 self.held.extend(out.iter().flatten().copied().filter(|v| v.is_collectable()));
1009 }
1010 let out = out?;
1011 if self.native_depth > 0 {
1012 // Inside a host function: valid until its next call (S5API-3). They were kept in
1013 // `rets`, which any native the host function reached later (a metamethod's
1014 // `tostring`, run by `get`) cleared, so they could be collected under it.
1015 self.host_rets.truncate(self.host_rets_base);
1016 self.host_rets.extend(out.iter().copied().filter(|v| v.is_collectable()));
1017 // S6-4: each object once (they are uncharged copies, and every host function
1018 // further out keeps its own): 100,000 results naming one table, kept at each
1019 // of 74 nested levels, held 128 MB resident against 5.3 MB accounted.
1020 if self.host_rets.len() - self.host_rets_base > HOST_RETS_COMPACT {
1021 crate::vm::compact_values(&mut self.host_rets, self.host_rets_base);
1022 }
1023 }
1024 Ok(out)
1025 }
1026
1027 /// Starts calling `f` as [`Lua::call`] does, but at most `poll_slots` table slots of
1028 /// the collector's work in this poll (and in each poll after): when the collector
1029 /// reaches that, the call pauses and this returns [`CallPoll::Pending`]; the host
1030 /// resumes it with [`Lua::resume_call`] (in its next frame, say) or drops it with
1031 /// [`Lua::cancel_call`]. A pause is invisible to the script: its results, its fuel,
1032 /// where a limit stops it and every effect are those of `call`. While a call is
1033 /// pending nothing else runs in the state (every entry returns an error).
1034 #[cfg(feature = "unstable-resumable")]
1035 pub fn start_call(&mut self, f: Value, args: &[Value], poll_slots: usize) -> CallPoll {
1036 let r = self.gc_start_sliced(f, args, poll_slots);
1037 if self.gc_is_pending() { CallPoll::Pending } else { CallPoll::Ready(r) }
1038 }
1039
1040 /// The pending call's next poll (see [`Lua::start_call`]); an error when none is.
1041 #[cfg(feature = "unstable-resumable")]
1042 pub fn resume_call(&mut self) -> CallPoll {
1043 let r = self.gc_resume_poll();
1044 if self.gc_is_pending() { CallPoll::Pending } else { CallPoll::Ready(r) }
1045 }
1046
1047 /// Drops the pending call (the collector's step it paused in is finished first,
1048 /// uncharged): the state is usable again, as after a call stopped by a limit.
1049 #[cfg(feature = "unstable-resumable")]
1050 pub fn cancel_call(&mut self) {
1051 self.gc_drop_pending();
1052 }
1053
1054 /// Whether a call is pending (see [`Lua::start_call`]).
1055 #[cfg(feature = "unstable-resumable")]
1056 pub fn call_pending(&self) -> bool {
1057 self.gc_is_pending()
1058 }
1059
1060 /// Test probe (SEC7-G1, until the host's entry for it is settled): calls `f` with the
1061 /// collector's polls bounded to `slots` table slots each, resuming the call each time a
1062 /// marking step pauses at a poll's end, until it returns. Its result, and the polls it
1063 /// took. A pause is invisible to the script and to the fuel: the result, the fuel and
1064 /// where a tight limit stops it are those of `call`.
1065 #[doc(hidden)]
1066 pub fn gc_sliced_call(&mut self, f: Value, args: &[Value], slots: usize) -> (Result<Vec<Value>, Error>, u32) {
1067 self.heap.poll_allow = Some(slots.max(1));
1068 let mut r = self.call(f, args);
1069 let mut polls = 1;
1070 while self.pending_call.is_some() || self.pending_start.is_some() {
1071 r = self.resume_poll();
1072 polls += 1;
1073 }
1074 self.heap.poll_allow = None;
1075 (r, polls)
1076 }
1077
1078 /// Test probe: `gc_sliced_call`'s first poll only; then `gc_resume_poll` for each
1079 /// next, or `gc_drop_pending`.
1080 #[doc(hidden)]
1081 pub fn gc_start_sliced(&mut self, f: Value, args: &[Value], slots: usize) -> Result<Vec<Value>, Error> {
1082 self.heap.poll_allow = Some(slots.max(1));
1083 let r = self.call(f, args);
1084 if !self.gc_is_pending() {
1085 self.heap.poll_allow = None;
1086 }
1087 r
1088 }
1089
1090 /// Test probe: the call `gc_start_sliced` left pending is.
1091 #[doc(hidden)]
1092 pub fn gc_is_pending(&self) -> bool {
1093 self.pending_call.is_some() || self.pending_start.is_some()
1094 }
1095
1096 /// Test probe: the next poll of the pending call.
1097 #[doc(hidden)]
1098 pub fn gc_resume_poll(&mut self) -> Result<Vec<Value>, Error> {
1099 let r = self.resume_poll();
1100 if !self.gc_is_pending() {
1101 self.heap.poll_allow = None;
1102 }
1103 r
1104 }
1105
1106 /// Test probe: drops the pending call (its step finished first).
1107 #[doc(hidden)]
1108 pub fn gc_drop_pending(&mut self) {
1109 if self.gc_is_pending() && self.entry == 0 {
1110 vm::Lua::cancel_nested(self);
1111 self.clear_idle_stack();
1112 }
1113 self.heap.poll_allow = None;
1114 }
1115
1116 /// The pending call's next poll: an interrupt set meanwhile drops it, as a stop would.
1117 fn resume_poll(&mut self) -> Result<Vec<Value>, Error> {
1118 if !self.gc_is_pending() {
1119 return Err(Error::Host("no call is pending".into()));
1120 }
1121 if self.interrupt.load(Ordering::Relaxed) {
1122 vm::Lua::cancel_nested(self);
1123 self.clear_idle_stack();
1124 self.limit_hit = Some(LimitKind::Interrupted);
1125 return Err(Error::Limit(LimitKind::Interrupted));
1126 }
1127 if self.heap.mem.trace.is_some() {
1128 let p = self.trace_poll_resumed();
1129 let r = self.resume_now();
1130 if let Some(p) = p {
1131 self.trace_poll_end(p);
1132 }
1133 return r;
1134 }
1135 self.resume_now()
1136 }
1137
1138 fn resume_now(&mut self) -> Result<Vec<Value>, Error> {
1139 if let Some((f, args)) = self.pending_start.take() {
1140 // Paused in the entry that finishes a suspended atomic step before a call
1141 // (`check_live`): that entry goes on; then the call, as `call_now` goes on.
1142 let out = self.enter_as(false, |l| l.resume_atomic_pausable());
1143 if self.gc_pending.is_some() && self.pending_call.is_none() {
1144 self.pending_start = Some((f, args));
1145 return out.map(|()| Vec::new());
1146 }
1147 out?;
1148 return self.call_now(f, &args);
1149 }
1150 let out = self.enter_as(false, vm::Lua::resume_nested);
1151 self.after_host_call(out)
1152 }
1153
1154 fn trace_poll_resumed(&mut self) -> Option<(std::time::Duration, usize, i64)> {
1155 let t = self.heap.mem.trace.as_mut()?;
1156 t.poll += 1;
1157 Some((t.now(), self.heap.scanned, 0))
1158 }
1159
1160 /// Where the collector stands, and the fuel it is known to need (SEC8-F3 O5): for a host
1161 /// that gives calls a fixed fuel, to tell a call that will be spent in the collector
1162 /// from one that will run the script (at the memory limit an allocation's emergency
1163 /// collection can take hundreds of such calls: SEC8-G3, a known limitation). Two
1164 /// different quantities:
1165 /// - `owed_fuel`: work already done and not yet charged. The collector's next steps (or
1166 /// next collection) charge it before they do more. Exact.
1167 /// - `remaining_fuel_at_least`: a floor on the fuel the cycle under way still needs
1168 /// past that. Not an estimate of the cost: marking finds the objects it must mark as
1169 /// it goes, so while it runs (`more_may_be_found`) the rest is not known ahead.
1170 /// A full collection (`collectgarbage()`, `collect_garbage`, or the one an allocation
1171 /// makes at the memory limit) finishes the cycle under way and then runs a whole new
1172 /// one, which neither figure includes. Reading it enters nothing and charges nothing.
1173 pub fn collector_status(&self) -> CollectorStatus {
1174 let phase = match self.heap.phase {
1175 crate::heap::Phase::Pause => CollectorPhase::Idle,
1176 crate::heap::Phase::Propagate if self.heap.atomic_suspended() => CollectorPhase::AtomicSuspended,
1177 crate::heap::Phase::Propagate => CollectorPhase::Marking,
1178 crate::heap::Phase::Sweep => CollectorPhase::Sweeping,
1179 };
1180 let owed = self.gc_mark_over + self.atomic_owed;
1181 CollectorStatus {
1182 phase,
1183 owed_fuel: (owed / vm::WORK_PER_FUEL) as u64,
1184 remaining_fuel_at_least: (self.heap.sweep_floor() / vm::WORK_PER_FUEL) as u64,
1185 more_may_be_found: phase != CollectorPhase::Idle,
1186 }
1187 }
1188
1189 /// Test probe (SEC8-F7): the collector's work units owed past a call's fuel since the
1190 /// state was made (charged by its next steps or collection, never dropped), those of
1191 /// them a cycle's start charged, and those owed now.
1192 #[doc(hidden)]
1193 pub fn gc_owed_probe(&self) -> (u64, u64, u64) {
1194 (self.gc_owed_probe.0, self.gc_owed_probe.1, (self.gc_mark_over + self.atomic_owed) as u64)
1195 }
1196
1197 /// Test probe: the slots grown in the cycle that marking scanned (paid as the table
1198 /// grew), the marking steps' budgets in work units, since the state was made, and the
1199 /// units a grown slot spends of a budget (SEC7-G1: the grown slots times that never pass
1200 /// the budgets by more than a chunk's over any run of calls).
1201 #[doc(hidden)]
1202 pub fn gc_pace_probe(&self) -> (u64, u64, u64) {
1203 (self.heap.probe_prepaid, self.heap.probe_budget, crate::heap::GROWN_SLOT_WORK as u64)
1204 }
1205
1206 /// Test probe: traces the collector's work (SEC7-G1) on `clock` in a buffer of
1207 /// `capacity` records taken now (None: no trace). One record a call from the host
1208 /// ([`TraceOp::Poll`]), one a collector step, and one an operation traced inside one;
1209 /// records past the buffer's end are counted, not kept. Changes no fuel.
1210 #[doc(hidden)]
1211 pub fn gc_trace(&mut self, clock: Option<Clock>, capacity: usize) {
1212 self.heap.mem.trace = clock.map(|c| Box::new(gctrace::Trace::new(c, capacity)));
1213 }
1214
1215 /// Test probe: the trace's records so far, and how many did not fit (both reset).
1216 #[doc(hidden)]
1217 pub fn gc_trace_take(&mut self) -> (Vec<TraceRecord>, u64) {
1218 self.heap.mem.trace.as_mut().map(|t| t.take()).unwrap_or_default()
1219 }
1220
1221 fn trace_poll(&mut self) -> Option<(std::time::Duration, usize, i64)> {
1222 let t = self.heap.mem.trace.as_mut()?;
1223 t.call += 1;
1224 t.poll += 1;
1225 Some((t.now(), self.heap.scanned, 0))
1226 }
1227
1228 #[cold]
1229 fn trace_poll_end(&mut self, (start, scanned, _): (std::time::Duration, usize, i64)) {
1230 let slots = self.heap.scanned.wrapping_sub(scanned) as u64;
1231 let used = self.limits.fuel.saturating_sub(self.fuel_left());
1232 if let Some(t) = self.heap.mem.trace.as_mut() {
1233 t.note(TraceOp::Poll, 0, slots, 0, used, start);
1234 }
1235 }
1236
1237 /// Runs `f` with `vals` kept alive (the operands of a host call while it allocates).
1238 fn with_held<T>(&mut self, vals: &[Value], f: impl FnOnce(&mut Lua) -> Result<T, LuaError>) -> Result<T, LuaError> {
1239 let mark = self.scratch.len();
1240 self.scratch.extend_from_slice(vals);
1241 let r = f(self);
1242 self.scratch.truncate(mark);
1243 r
1244 }
1245
1246 /// Keeps a value the host was handed alive: until the running host function returns
1247 /// (inside one), else until the next call from the host returns.
1248 fn keep(&mut self, v: Value) -> Value {
1249 if v.is_collectable() {
1250 if self.native_depth > 0 {
1251 self.push_scratch(v);
1252 } else if self.entry == 0 {
1253 self.push_held(v);
1254 }
1255 }
1256 v
1257 }
1258
1259 /// Calls the global function `name` (or a dotted path, `table.field`, read raw), if
1260 /// there is one: `Ok(None)` when it is missing or not a function.
1261 pub fn call_global(&mut self, name: &str, args: &[Value]) -> Result<Option<Vec<Value>>, Error> {
1262 let f = self.get_path(name)?;
1263 if !matches!(f, Value::Func(_)) {
1264 return Ok(None);
1265 }
1266 self.call(f, args).map(Some)
1267 }
1268
1269 /// Read as `get_global` reads (SEC8-F3 O2): each name looked up, not made.
1270 fn get_path(&mut self, name: &str) -> Result<Value, Error> {
1271 self.check_live_now(Value::Nil)?;
1272 let mut cur = Value::Table(self.globals);
1273 for part in name.split('.') {
1274 let Value::Table(t) = cur else { return Ok(Value::Nil) };
1275 let Some(k) = self.heap.find_interned_quiet(part.as_bytes()) else { return Ok(Value::Nil) };
1276 cur = crate::table::host_side(|| self.raw_get(t, Value::Str(k)));
1277 }
1278 Ok(cur)
1279 }
1280
1281 /// The globals table.
1282 pub fn globals(&self) -> TableRef {
1283 self.globals
1284 }
1285
1286 /// A global, read raw (no metamethods run). A read: it does not enter the state, so it
1287 /// neither finishes an atomic phase a call before stopped in nor pays for one (made
1288 /// with `create_string`, the name entered, and while that phase did not fit in the
1289 /// call's fuel the read failed with `Limit(Fuel)`: SEC8-F3). The name is looked up, not
1290 /// made: table keys are interned, so a name never made is no global's. (A value read
1291 /// here and stored from the host is checked then, the phase finished first: SEC7-H2.)
1292 pub fn get_global(&mut self, name: &str) -> Result<Value, Error> {
1293 self.check_live_now(Value::Nil)?;
1294 let Some(k) = self.heap.find_interned_quiet(name.as_bytes()) else { return Ok(Value::Nil) };
1295 Ok(crate::table::host_side(|| self.raw_get(self.globals, Value::Str(k))))
1296 }
1297
1298 /// Sets a global, raw.
1299 pub fn set_global(&mut self, name: &str, v: Value) -> Result<(), Error> {
1300 self.check_live(v)?;
1301 let k = self.create_string(name.as_bytes())?;
1302 // Making the name may have needed the memory `v` held.
1303 self.check_live(v)?;
1304 let g = self.globals;
1305 self.enter(|l| l.with_held(&[k, v], |l| l.raw_set(g, k, v)))
1306 }
1307
1308 /// `t[k]`, raw (nil for a handle whose table was collected).
1309 pub fn table_get(&self, t: TableRef, k: Value) -> Value {
1310 if !self.heap.is_live(Value::Table(t)) || !self.heap.is_live(k) {
1311 return Value::Nil;
1312 }
1313 crate::table::host_side(|| self.raw_get(t, k))
1314 }
1315
1316 /// `t[k] = v`, raw.
1317 pub fn table_set(&mut self, t: TableRef, k: Value, v: Value) -> Result<(), Error> {
1318 self.check_live(Value::Table(t))?;
1319 self.check_live(k)?;
1320 self.check_live(v)?;
1321 self.enter(|l| l.with_held(&[k, v], |l| l.raw_set(t, k, v)))
1322 }
1323
1324 /// `t[k]` with metamethods (which run under the call's fuel).
1325 pub fn get(&mut self, t: Value, k: Value) -> Result<Value, Error> {
1326 self.check_live(t)?;
1327 self.check_live(k)?;
1328 let v = self.enter(|l| l.with_held(&[t, k], |l| l.index_nested(t, k)))?;
1329 Ok(self.keep(v))
1330 }
1331
1332 /// `t[k] = v` with metamethods.
1333 pub fn set(&mut self, t: Value, k: Value, v: Value) -> Result<(), Error> {
1334 self.check_live(t)?;
1335 self.check_live(k)?;
1336 self.check_live(v)?;
1337 self.enter(|l| l.with_held(&[t, k, v], |l| l.set_index_nested(t, k, v)))
1338 }
1339
1340 /// `#t`, raw (0 for a handle whose table was collected).
1341 pub fn table_len(&self, t: TableRef) -> i64 {
1342 if !self.heap.is_live(Value::Table(t)) {
1343 return 0;
1344 }
1345 crate::table::host_side(|| self.raw_len(t))
1346 }
1347
1348 /// Every entry of `t`, raw, in traversal order (none for a stale handle).
1349 pub fn table_pairs(&self, t: TableRef) -> Vec<(Value, Value)> {
1350 if !self.heap.is_live(Value::Table(t)) {
1351 return Vec::new();
1352 }
1353 crate::table::host_side(|| self.heap.tables.get(t.idx).map(|t| t.entries().collect()).unwrap_or_default())
1354 }
1355
1356 /// A new empty table.
1357 pub fn create_table(&mut self) -> Result<TableRef, Error> {
1358 let t = self.enter(|l| l.new_table(0, 0))?;
1359 self.keep(Value::Table(t));
1360 Ok(t)
1361 }
1362
1363 /// A string.
1364 pub fn create_string(&mut self, s: impl AsRef<[u8]>) -> Result<Value, Error> {
1365 let b = s.as_ref();
1366 let v = self.enter(|l| l.new_str(b))?;
1367 Ok(self.keep(v))
1368 }
1369
1370 /// The bytes of a string value.
1371 pub fn str_bytes(&self, v: Value) -> Option<&[u8]> {
1372 match v {
1373 Value::Str(s) if self.heap.is_live(v) => Some(self.bytes(s)),
1374 _ => None,
1375 }
1376 }
1377
1378 /// Raw equality as Lua's `rawequal` sees it: strings by content (two equal long
1379 /// strings made apart are different objects, so `Value`'s `==` tells them apart),
1380 /// `1 == 1.0`, other objects by identity. No metamethods run.
1381 pub fn raw_equal(&self, a: &Value, b: &Value) -> bool {
1382 match (*a, *b) {
1383 (Value::Str(x), Value::Str(y)) if self.heap.is_live(*a) && self.heap.is_live(*b) => {
1384 self.heap.str_eq_quick(x, y).unwrap_or_else(|| self.bytes(x) == self.bytes(y))
1385 }
1386 (x, y) => x.raw_eq(y),
1387 }
1388 }
1389
1390 /// A string value as text (invalid UTF-8 replaced).
1391 pub fn to_string_lossy(&self, v: Value) -> Option<String> {
1392 self.str_bytes(v).map(|b| String::from_utf8_lossy(b).into_owned())
1393 }
1394
1395 /// Sets a table's metatable.
1396 pub fn set_metatable(&mut self, t: TableRef, meta: Option<TableRef>) -> Result<(), Error> {
1397 self.check_live(Value::Table(t))?;
1398 if let Some(m) = meta {
1399 self.check_live(Value::Table(m))?;
1400 if !self.tm_in(m, vm::Tm::Gc).is_nil() {
1401 return Err(Error::Host("__gc metamethods are not supported".into()));
1402 }
1403 }
1404 if let Some(tab) = self.heap.tables.get_mut(t.idx) {
1405 tab.meta = meta;
1406 }
1407 self.heap.barrier_table(t);
1408 Ok(())
1409 }
1410
1411 /// Keeps `v` alive while the returned handle lives.
1412 pub fn root(&mut self, v: Value) -> Root {
1413 let alive = Arc::new(());
1414 // Dropped roots are forgotten here too (not only during a collection), whenever
1415 // the list has doubled since it was last pruned: amortized O(1) per root.
1416 if self.roots.len() >= self.roots_pruned_at.saturating_mul(2).max(64) {
1417 self.prune_roots();
1418 self.roots_pruned_at = self.roots.len();
1419 }
1420 // Counted (LR-17), whatever the limit says: making a handle cannot fail. Given back
1421 // when its dropped entry is pruned.
1422 self.heap.mem.used = self.heap.mem.used.saturating_add(heap::ROOT_BYTES);
1423 // S5API-8: a stale handle (or another state's) must not keep alive whatever object
1424 // now has its slot here; the root keeps nothing then.
1425 let kept = if self.heap.is_live(v) { v } else { Value::Nil };
1426 self.roots.push((Arc::downgrade(&alive), kept));
1427 Root { value: v, _alive: alive }
1428 }
1429
1430 /// A Rust function scripts can call. It gets the arguments and returns the results,
1431 /// or an error the script sees as an error (catchable by `pcall` unless it is an
1432 /// [`Error::Limit`]; an [`Error::Runtime`] that a `lua.call` inside it returned passes
1433 /// the script's own error value on). It may call back into the state (`lua.call`), and
1434 /// a script may reach it again while it runs, so it is `Fn + Sync`: keep mutable state
1435 /// behind a `Mutex` or in [`Lua::app_data_mut`], or use [`Lua::create_function_mut`],
1436 /// which takes an `FnMut` that need not be `Sync` and refuses to run inside itself. When it returns, the host's interrupt and the
1437 /// call's deadline are checked, so time spent waiting in it counts. A panic in it
1438 /// unwinds to the host and poisons the state; catch panics inside it to contain them.
1439 pub fn create_function(
1440 &mut self,
1441 name: &str,
1442 f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static,
1443 ) -> Result<Value, Error> {
1444 let host: heap::HostFn = Arc::new(move |lua: &mut Lua, a: Args| -> Result<Flow, LuaError> {
1445 let args: Vec<Value> = (0..a.n).map(|i| lua.st(a.base + i)).collect();
1446 // Its calls' results go above those of the host functions further out.
1447 let rets_base = std::mem::replace(&mut lua.host_rets_base, lua.host_rets.len());
1448 // The uncharged probe steps and error-naming work (per thread) are the calling
1449 // script's: set aside while the host function runs, so nothing it does to any
1450 // state (a compile in another, which does not enter it) is billed here, and put
1451 // back after (the residual of S6-RES-4).
1452 let aside = (crate::table::take_probes(), crate::debug::take_work());
1453 let out = f(lua, &args);
1454 crate::table::put_probes(aside.0);
1455 crate::debug::put_work(aside.1);
1456 lua.host_rets.truncate(lua.host_rets_base);
1457 lua.host_rets_base = rets_base;
1458 // Time spent in the host function counts: one that waits (and spends no fuel)
1459 // must not keep a script past its interrupt or deadline.
1460 if lua.interrupt.load(Ordering::Relaxed) {
1461 return Err(LuaError::Limit(LimitKind::Interrupted));
1462 }
1463 if let (Some(at), Some((clock, _))) = (lua.deadline, &lua.time_limit)
1464 && clock() >= at
1465 {
1466 return Err(LuaError::Limit(LimitKind::Time));
1467 }
1468 let out = match out {
1469 Ok(out) => out,
1470 Err(e) => return Err(lua.from_host_error(e)),
1471 };
1472 // A value whose object was collected must not reach the script.
1473 if out.iter().any(|v| !lua.heap.is_live(*v)) {
1474 return Err(LuaError::msg("a host function returned a value whose object was collected"));
1475 }
1476 lua.rets.clear();
1477 lua.rets.extend(out);
1478 Ok(Flow::Return)
1479 });
1480 // LR-17: its closure's `Arc` (counts, the captured state rounded to 16, the header)
1481 // and its name's (likewise), not a flat 32.
1482 let round = |n: usize| n.div_ceil(16) * 16;
1483 let bytes = round(16 + std::mem::size_of_val(&*host)) + heap::ALLOC_OVERHEAD + round(16 + name.len()) + heap::ALLOC_OVERHEAD;
1484 let name: Arc<str> = Arc::from(name);
1485 let v = self.enter(|l| {
1486 l.charge_mem(heap::FUNC_BASE + bytes)?;
1487 let r = l.heap.new_func_charged(heap::Func::Host { f: host, name, bytes });
1488 Ok(Value::Func(r))
1489 })?;
1490 Ok(self.keep(v))
1491 }
1492
1493 /// Makes a Rust function a global (`name`) or a field of a global table (`lib.name`,
1494 /// the table made if missing).
1495 pub fn register(
1496 &mut self,
1497 name: &str,
1498 f: impl Fn(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + Sync + 'static,
1499 ) -> Result<(), Error> {
1500 let short = name.rsplit('.').next().unwrap_or(name).to_owned();
1501 let func = self.create_function(&short, f)?;
1502 self.register_value(name, func)
1503 }
1504
1505 /// [`Lua::register`] for a [`Lua::create_function_mut`] function.
1506 pub fn register_mut(
1507 &mut self,
1508 name: &str,
1509 f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static,
1510 ) -> Result<(), Error> {
1511 let short = name.rsplit('.').next().unwrap_or(name).to_owned();
1512 let func = self.create_function_mut(&short, f)?;
1513 self.register_value(name, func)
1514 }
1515
1516 /// A Rust function scripts can call, like [`Lua::create_function`], that may keep
1517 /// mutable state and need not be `Sync`. Because it is `FnMut`, it cannot run inside
1518 /// itself: when a script reaches it again while it runs (through a callback it calls),
1519 /// that inner call is an ordinary script error, "a host function was called again while
1520 /// it ran". `create_function` needs `Sync` because it may run inside itself, and the
1521 /// state, which is `Send`, shares it between those runs; `Mutex` makes this one `Sync`
1522 /// without that.
1523 pub fn create_function_mut(
1524 &mut self,
1525 name: &str,
1526 f: impl FnMut(&mut Lua, &[Value]) -> Result<Vec<Value>, Error> + Send + 'static,
1527 ) -> Result<Value, Error> {
1528 let f = std::sync::Mutex::new(f);
1529 self.create_function(name, move |lua, args| match f.try_lock() {
1530 Ok(mut f) => f(lua, args),
1531 Err(std::sync::TryLockError::WouldBlock) => Err(Error::runtime("a host function was called again while it ran")),
1532 // A panic in it poisoned the state too: nothing runs here again.
1533 Err(std::sync::TryLockError::Poisoned(_)) => Err(Error::Host("a panic in an earlier call left this state unusable".into())),
1534 })
1535 }
1536
1537 fn register_value(&mut self, name: &str, func: Value) -> Result<(), Error> {
1538 let func = self.root(func);
1539 let mut parts: Vec<&str> = name.split('.').collect();
1540 let last = parts.pop().unwrap_or(name);
1541 let mut t = self.globals;
1542 for p in parts {
1543 let k = self.create_string(p.as_bytes())?;
1544 t = match self.raw_get(t, k) {
1545 Value::Table(inner) => inner,
1546 _ => {
1547 let inner = self.create_table()?;
1548 self.table_set(t, k, Value::Table(inner))?;
1549 inner
1550 }
1551 };
1552 }
1553 let k = self.create_string(last.as_bytes())?;
1554 self.table_set(t, k, func.value())
1555 }
1556
1557 /// A full userdata holding `data`, with an optional metatable (for methods: set its
1558 /// `__index`; a `__gc` field never runs). It counts `size_of::<T>()` plus a small
1559 /// header against the memory limit; declare what `T` owns on the heap (a `Vec`'s
1560 /// buffer) with [`Lua::set_userdata_size`].
1561 pub fn create_userdata<T: Any + Send>(&mut self, data: T, meta: Option<TableRef>) -> Result<Value, Error> {
1562 self.new_userdata_value(Box::new(data), std::mem::size_of::<T>(), meta, None)
1563 }
1564
1565 /// A userdata of `size` bytes, tracked under `notify`. A tracked one also charges the
1566 /// slot its key takes in the collected queue (S5API-4), so a script that makes and drops
1567 /// tracked userdata in a loop is stopped by the memory limit, not the host's memory.
1568 /// `take_collected` gives the slot back.
1569 fn new_userdata_value(
1570 &mut self,
1571 data: Box<dyn Any + Send>,
1572 size: usize,
1573 meta: Option<TableRef>,
1574 notify: Option<u64>,
1575 ) -> Result<Value, Error> {
1576 if let Some(m) = meta {
1577 self.check_live(Value::Table(m))?;
1578 }
1579 let held = meta.map_or(Value::Nil, Value::Table);
1580 let queued = if notify.is_some() { QUEUE_ENTRY } else { 0 };
1581 let v = self.enter(|l| {
1582 l.with_held(&[held], |l| {
1583 l.charge_mem(heap::UD_BASE + size + queued)?;
1584 l.heap.mem.release(heap::UD_BASE + size);
1585 let r = match l.alloc_ud(data, size, meta) {
1586 Ok(r) => r,
1587 Err(e) => {
1588 l.heap.mem.release(queued);
1589 return Err(e);
1590 }
1591 };
1592 if let Some(ud) = l.heap.uds.get_mut(r.idx) {
1593 ud.notify = notify;
1594 }
1595 Ok(Value::UserData(r))
1596 })
1597 })?;
1598 Ok(self.keep(v))
1599 }
1600
1601 /// Sets what the userdata `v` counts against the memory limit, besides a small header:
1602 /// `bytes`, in place of `size_of::<T>()`. A host whose userdata owns heap memory (a
1603 /// buffer a script asked for) declares it here, `size_of::<T>() + buffer.capacity()`,
1604 /// when it grows or shrinks; the difference is charged now, so a script cannot make
1605 /// the host allocate past its budget. Over the limit (or past `isize::MAX`, the largest
1606 /// allocation there is): [`Error::Limit`]`(Memory)` and nothing changes (inside a host
1607 /// function, return the error, so the call stops).
1608 pub fn set_userdata_size(&mut self, v: Value, bytes: usize) -> Result<(), Error> {
1609 let Value::UserData(u) = v else { return Err(Error::Host("set_userdata_size takes a userdata".into())) };
1610 self.check_live(v)?;
1611 self.enter(|l| {
1612 // S5API-5: no allocation is this big, and with an unlimited memory cap a size
1613 // near `usize::MAX` was accepted and overflowed the header added at collection.
1614 if bytes > MAX_UD_BYTES {
1615 return Err(LuaError::Limit(LimitKind::Memory));
1616 }
1617 l.with_held(&[v], |l| {
1618 let old = l.heap.uds.get(u.idx).map_or(bytes, |d| d.size);
1619 if bytes > old {
1620 l.charge_mem(bytes - old)?;
1621 } else {
1622 l.heap.mem.release(old - bytes);
1623 }
1624 if let Some(d) = l.heap.uds.get_mut(u.idx) {
1625 d.size = bytes;
1626 }
1627 Ok(())
1628 })
1629 })
1630 }
1631
1632 /// A userdata like [`Lua::create_userdata`] whose collection the host hears about: once
1633 /// no script or root can reach it and the collector frees it, `key` is queued for
1634 /// [`Lua::take_collected`]. For host objects that must be released when scripts drop
1635 /// their handles; no Lua code runs at collection (there is no `__gc`). It counts 8 bytes
1636 /// more than an untracked one: the room its key takes in that queue.
1637 pub fn create_userdata_tracked<T: Any + Send>(&mut self, data: T, meta: Option<TableRef>, key: u64) -> Result<Value, Error> {
1638 self.new_userdata_value(Box::new(data), std::mem::size_of::<T>(), meta, Some(key))
1639 }
1640
1641 /// The data of a userdata, if it holds a `T`.
1642 pub fn userdata<T: Any>(&self, v: Value) -> Option<&T> {
1643 let Value::UserData(u) = v else { return None };
1644 if !self.heap.is_live(v) {
1645 return None;
1646 }
1647 self.heap.uds.get(u.idx)?.data.as_ref()?.downcast_ref::<T>()
1648 }
1649
1650 /// The data of a userdata, mutably, if it holds a `T`.
1651 pub fn userdata_mut<T: Any>(&mut self, v: Value) -> Option<&mut T> {
1652 let Value::UserData(u) = v else { return None };
1653 if !self.heap.is_live(v) {
1654 return None;
1655 }
1656 self.heap.uds.get_mut(u.idx)?.data.as_mut()?.downcast_mut::<T>()
1657 }
1658
1659 /// Copies a value out as owned [`Data`], raw (no metamethod runs: `__pairs` and
1660 /// `__index` are ignored), within `limits`. A function, userdata or thread, or a table
1661 /// nested deeper than `limits.depth` (a table that holds itself, say), is an
1662 /// [`Error::Host`].
1663 pub fn to_data(&self, v: Value, limits: DataLimits) -> Result<Data, Error> {
1664 self.check_live_now(v)?;
1665 let mut budget = (limits.nodes, limits.bytes);
1666 // Each level of nesting is a native call: capped, so a host asking for any depth
1667 // cannot overflow its stack on a script's deeply nested table.
1668 crate::table::host_side(|| self.to_data_inner(v, 0, limits.depth.min(MAX_DATA_DEPTH), &mut budget))
1669 }
1670
1671 fn to_data_inner(&self, v: Value, depth: usize, max: usize, budget: &mut (usize, usize)) -> Result<Data, Error> {
1672 if depth > max {
1673 return Err(Error::Host("table nested too deeply".into()));
1674 }
1675 if budget.0 == 0 {
1676 return Err(Error::Host("too much data".into()));
1677 }
1678 budget.0 -= 1;
1679 Ok(match v {
1680 Value::Nil => Data::Nil,
1681 Value::Bool(b) => Data::Bool(b),
1682 Value::Int(i) => Data::Int(i),
1683 Value::Num(f) => Data::Num(f),
1684 Value::Str(s) => {
1685 let b = self.bytes(s);
1686 if b.len() > budget.1 {
1687 return Err(Error::Host("too much data".into()));
1688 }
1689 budget.1 -= b.len();
1690 Data::Str(String::from_utf8_lossy(b).into_owned())
1691 }
1692 Value::Table(t) => {
1693 let mut out = Vec::new();
1694 // Read in place: copying every entry first allocated the whole table natively
1695 // (uncharged) before the node budget could stop it.
1696 let Some(tab) = self.heap.tables.get(t.idx).filter(|_| self.heap.is_live(Value::Table(t))) else {
1697 return Ok(Data::Table(out));
1698 };
1699 for (k, v) in tab.entries() {
1700 let k = self.to_data_inner(k, depth + 1, max, budget)?;
1701 let v = self.to_data_inner(v, depth + 1, max, budget)?;
1702 out.push((k, v));
1703 }
1704 Data::Table(out)
1705 }
1706 other => return Err(Error::Host(format!("a {} cannot be copied out", other.type_name()))),
1707 })
1708 }
1709
1710 /// Makes a value from owned [`Data`] (nil and NaN keys are skipped), nested at most 64
1711 /// deep; its size is bounded by the memory limit only. [`Lua::from_data_with`] bounds it.
1712 pub fn from_data(&mut self, d: &Data) -> Result<Value, Error> {
1713 self.from_data_with(d, DataLimits { depth: MAX_FROM_DATA_DEPTH, nodes: usize::MAX, bytes: usize::MAX })
1714 }
1715
1716 /// [`Lua::from_data`] within `limits`, checked before anything is made: deeper (than
1717 /// `limits.depth`, and never more than 64), more values or more string bytes is an
1718 /// [`Error::Host`], as for [`Lua::to_data`].
1719 pub fn from_data_with(&mut self, d: &Data, limits: DataLimits) -> Result<Value, Error> {
1720 fn fits(d: &Data, depth: usize, max: usize, budget: &mut (usize, usize)) -> Result<(), Error> {
1721 if depth > max {
1722 return Err(Error::Host("data nested too deeply".into()));
1723 }
1724 if budget.0 == 0 {
1725 return Err(Error::Host("too much data".into()));
1726 }
1727 budget.0 -= 1;
1728 match d {
1729 Data::Str(s) => {
1730 budget.1 = budget.1.checked_sub(s.len()).ok_or_else(|| Error::Host("too much data".into()))?;
1731 }
1732 Data::Table(pairs) => {
1733 for (k, v) in pairs {
1734 fits(k, depth + 1, max, budget)?;
1735 fits(v, depth + 1, max, budget)?;
1736 }
1737 }
1738 _ => {}
1739 }
1740 Ok(())
1741 }
1742 // S5API-6: never deeper than `from_data_inner` goes (64), so data that passes is made
1743 // (it failed half-made, as a runtime error), and `fits` recurses no deeper.
1744 fits(d, 0, limits.depth.min(MAX_FROM_DATA_DEPTH), &mut (limits.nodes, limits.bytes))?;
1745 self.enter(|l| {
1746 let base = l.scratch.len();
1747 l.native_depth += 1;
1748 let r = l.from_data_inner(d, 0);
1749 l.native_depth -= 1;
1750 let r = r.map(|v| {
1751 l.scratch.truncate(base);
1752 v
1753 });
1754 l.scratch.truncate(base);
1755 r
1756 })
1757 .map(|v| self.keep(v))
1758 }
1759
1760 fn from_data_inner(&mut self, d: &Data, depth: usize) -> Result<Value, LuaError> {
1761 if depth > MAX_FROM_DATA_DEPTH {
1762 return Err(LuaError::msg("data nested too deeply"));
1763 }
1764 Ok(match d {
1765 Data::Nil => Value::Nil,
1766 Data::Bool(b) => Value::Bool(*b),
1767 Data::Int(i) => Value::Int(*i),
1768 Data::Num(f) => Value::Num(*f),
1769 Data::Str(s) => self.new_str(s.as_bytes())?,
1770 Data::Table(pairs) => {
1771 let t = self.new_table(0, pairs.len().min(1 << 16))?;
1772 for (k, v) in pairs {
1773 if matches!(k, Data::Nil) || matches!(k, Data::Num(f) if f.is_nan()) {
1774 continue;
1775 }
1776 let kv = self.from_data_inner(k, depth + 1)?;
1777 let vv = self.from_data_inner(v, depth + 1)?;
1778 self.raw_set(t, kv, vv)?;
1779 }
1780 Value::Table(t)
1781 }
1782 })
1783 }
1784
1785 /// Turns `warn` output on or off, as a script's `warn("@on")` / `warn("@off")` does.
1786 /// Warnings start off, as in C Lua's `luaL_newstate`; they go where `print` goes, and
1787 /// only with the `PRINT` library allowed. A script can still switch them afterwards.
1788 pub fn set_warnings(&mut self, on: bool) {
1789 self.warn_on = on;
1790 }
1791
1792 /// Test switch: with `false`, every instruction runs through the full interpreter
1793 /// path instead of the fast loop (results, fuel and memory must not change). Also off
1794 /// for every state when the environment has `REMEDYLUA_TEST_NO_FAST_LOOP`.
1795 #[doc(hidden)]
1796 pub fn set_fast_loop(&mut self, on: bool) {
1797 self.fast = on;
1798 }
1799
1800 /// Test probe: library functions called so far through the interpreter's general native
1801 /// call (a call the fast loop runs in place does not count).
1802 #[doc(hidden)]
1803 pub fn native_calls(&self) -> u64 {
1804 self.native_calls
1805 }
1806
1807 /// Test mode: instructions the full path has run while the fast loop was on (the ones
1808 /// the fast loop left to it), so a test can check which operations stay in the loop.
1809 #[doc(hidden)]
1810 pub fn full_steps(&self) -> u64 {
1811 self.full_steps
1812 }
1813
1814 /// Test mode: a whole collection at every allocation, to shake out values the
1815 /// interpreter holds without rooting them. Very slow.
1816 #[doc(hidden)]
1817 pub fn set_gc_stress(&mut self, on: bool) {
1818 self.heap.mem.stress = on;
1819 }
1820
1821 /// Test probe: the most slots of one table the collector scanned in one go (a whole
1822 /// table, or one chunk of a big one: at most 4,096 while marking is incremental,
1823 /// S6GC-2e-R) since this was last called.
1824 #[doc(hidden)]
1825 pub fn gc_most_slots_at_once(&mut self) -> usize {
1826 std::mem::take(&mut self.heap.most_at_once)
1827 }
1828
1829 /// Test probe: the array slots copied into new buffers by growths on this thread, and the
1830 /// array parts made segmented, since the last read.
1831 #[doc(hidden)]
1832 pub fn table_slots_copied(&mut self) -> (u64, u64) {
1833 crate::table::take_copied()
1834 }
1835
1836 /// Test probe: the slots growths read under a fuel watch (made a piece at a time within
1837 /// the call's fuel, SEC8-F4) on this thread since the last read, a piece at a time.
1838 #[doc(hidden)]
1839 pub fn table_slots_watched(&mut self) -> u64 {
1840 crate::table::take_watched()
1841 }
1842
1843 /// Test probe: the slots of new array tails a resize made on this thread since the last
1844 /// read (a resize given up and gone on with makes each once).
1845 #[doc(hidden)]
1846 pub fn table_slots_staged(&mut self) -> u64 {
1847 crate::table::take_staged()
1848 }
1849
1850 /// Test probe (segmented storage): the objects slabs' storage moved on this thread since
1851 /// the last read (none once past a slab's first chunk).
1852 #[cfg(any(target_family = "wasm", feature = "segmented-arrays"))]
1853 #[doc(hidden)]
1854 pub fn slab_objects_moved(&mut self) -> u64 {
1855 crate::heap::take_moved()
1856 }
1857
1858 /// Test probe: the most table slots the atomic phase scanned between two looks at the
1859 /// interrupt and the deadline since the last read.
1860 #[doc(hidden)]
1861 pub fn gc_most_slots_between_looks(&mut self) -> usize {
1862 std::mem::take(&mut self.heap.most_between_looks)
1863 }
1864
1865 /// Test probe: sizes of the state's bookkeeping that `memory_used` does not count
1866 /// (so the soak tests can see it return to its baseline).
1867 #[doc(hidden)]
1868 pub fn internal_sizes(&self) -> Vec<(&'static str, usize)> {
1869 let h = &self.heap;
1870 let mut v = vec![
1871 ("interned", h.interner.count),
1872 ("interner_slots", h.interner.slots.len()),
1873 ("interner_moving", h.interner.old.len()),
1874 ("roots", self.roots.len()),
1875 ("scratch", self.scratch.len()),
1876 ("held", self.held.len()),
1877 ("rets", self.rets.len()),
1878 ("host_rets", self.host_rets.len()),
1879 ("collected", h.collected.len()),
1880 ("gc_scratch_bytes", h.scratch_bytes()),
1881 ("app_data", self.app_data.len()),
1882 ("stack", self.cur.stack.len()),
1883 ];
1884 // Each slab's objects, slots, and free slots below its last object.
1885 fn counts<T>(s: &heap::Slab<T>) -> [usize; 3] {
1886 [s.slots() - s.free.len(), s.slot_capacity(), s.free.len()]
1887 }
1888 let slabs = [
1889 ("strings", counts(&h.strings)),
1890 ("tables", counts(&h.tables)),
1891 ("funcs", counts(&h.funcs)),
1892 ("upvals", counts(&h.upvals)),
1893 ("uds", counts(&h.uds)),
1894 ("threads", counts(&h.threads)),
1895 ("protos", counts(&h.protos)),
1896 ];
1897 v.extend(slabs.iter().map(|&(n, [live, _, _])| (n, live)));
1898 v.push(("slab_slots", slabs.iter().map(|&(_, [_, cap, _])| cap).sum()));
1899 // SEC-M5: free slots below the last object of their slab, and their bytes
1900 // (counted in `memory_used`).
1901 v.push(("free_slots", slabs.iter().map(|&(_, [_, _, free])| free).sum()));
1902 v.push(("slack_bytes", h.mem.slack));
1903 v
1904 }
1905
1906 /// Bytes the state's objects hold now, free slots included (they are resident: a
1907 /// slab keeps the slots below its last object).
1908 pub fn memory_used(&self) -> usize {
1909 // (Without the table buffer pool: it counts against the limit, but what it holds
1910 // depends on when it was last given back, which the two paths may not share.)
1911 self.heap.mem.used - self.heap.mem.pool.bytes
1912 }
1913
1914 /// The limits.
1915 pub fn limits(&self) -> Limits {
1916 self.limits
1917 }
1918
1919 /// Changes the limits (the memory cap applies to what is allocated from now on). The
1920 /// dialect and seed are the state's for life: `strict_5_4` and `hash_seed` keep the
1921 /// values the state was made with (the math table and `__le` must agree, and the
1922 /// hashing has already used the seed), whatever `limits` says.
1923 pub fn set_limits(&mut self, limits: Limits) {
1924 let (strict, seed) = (self.limits.strict_5_4, self.limits.hash_seed);
1925 self.limits = Limits { strict_5_4: strict, hash_seed: seed, ..limits };
1926 self.limits.stack_bytes = self.limits.stack_bytes.min(test_stack_cap());
1927 self.heap.mem.cap = limits.memory;
1928 // The fast loop's context copies limits (`Lua::ctx_epoch`).
1929 self.ctx_epoch += 1;
1930 }
1931
1932 /// Fuel left in the current (or last) call.
1933 pub fn fuel_left(&self) -> u64 {
1934 if let Some(n) = self.stopped_left {
1935 return n;
1936 }
1937 // (A charge past the slice is owed by the reserve even when the call stopped before
1938 // `refuel` took it from there: LR-29d, a resize finished in a sliced call was
1939 // reported as the slice alone, 16,384 units of its 3,670,016.)
1940 u64::try_from(self.fuel.saturating_add(self.reserve.max(0)).max(0)).unwrap_or(0)
1941 }
1942
1943 /// The state's interrupt: a handle to keep (on any thread) and set to stop the running
1944 /// call. Every handle from the same state is the same interrupt.
1945 pub fn interrupt_handle(&self) -> Interrupt {
1946 Interrupt(Arc::clone(&self.interrupt))
1947 }
1948
1949 /// Stops each call from the host once it has run `limit` by `clock` (looked at every few
1950 /// thousand steps, so the stop comes within a fraction of a millisecond of work past it):
1951 /// [`Error::Limit`]`(`[`LimitKind::Time`]`)`. `None` removes the time limit.
1952 pub fn set_time_limit(&mut self, limit: Option<(Clock, std::time::Duration)>) {
1953 self.time_limit = limit;
1954 }
1955
1956 /// Keeps `data` with the state: the host's own data for its functions to reach
1957 /// ([`Lua::app_data_mut`]), one value per type, replacing the last of that type. `Send`
1958 /// because the state is `Send` (it may move to another thread with what it holds).
1959 pub fn set_app_data<T: Any + Send>(&mut self, data: T) {
1960 self.app_data.insert(std::any::TypeId::of::<T>(), Box::new(data));
1961 }
1962
1963 /// The host's data of type `T`, if set.
1964 pub fn app_data<T: Any>(&self) -> Option<&T> {
1965 self.app_data.get(&std::any::TypeId::of::<T>())?.downcast_ref::<T>()
1966 }
1967
1968 /// The host's data of type `T`, mutably, if set.
1969 pub fn app_data_mut<T: Any>(&mut self) -> Option<&mut T> {
1970 self.app_data.get_mut(&std::any::TypeId::of::<T>())?.downcast_mut::<T>()
1971 }
1972
1973 /// Takes the host's data of type `T` out of the state.
1974 pub fn take_app_data<T: Any>(&mut self) -> Option<T> {
1975 let b = self.app_data.remove(&std::any::TypeId::of::<T>())?;
1976 b.downcast::<T>().ok().map(|b| *b)
1977 }
1978
1979 /// The keys of tracked userdata ([`Lua::create_userdata_tracked`]) the collector has
1980 /// freed since the last take, oldest first. Nothing runs in Lua when one is collected:
1981 /// the host drains this queue when it chooses (after a call, or a collection). Each key
1982 /// waiting here counts 8 bytes against the memory limit (charged when its userdata was
1983 /// made) until it is taken, so a host that tracks userdata drains it after each call.
1984 pub fn take_collected(&mut self) -> Vec<u64> {
1985 let keys = std::mem::take(&mut self.heap.collected);
1986 // Each key's slot was charged when its userdata was made (S5API-4).
1987 self.heap.mem.release(keys.len().saturating_mul(QUEUE_ENTRY));
1988 keys
1989 }
1990
1991 /// Runs a complete collection now. From the host (not inside a host function) it also
1992 /// lets go of the values held for the host since its last call (see
1993 /// [the crate docs](crate)): root what must survive it.
1994 pub fn collect_garbage(&mut self) -> Result<(), Error> {
1995 if self.entry == 0 {
1996 self.held.clear();
1997 }
1998 self.enter(|l| l.full_gc())
1999 }
2000
2001 /// Takes what `print` (and `warn`) wrote since the last take; empty when a sink is set.
2002 /// Each call from the host may write at most [`Limits::output`] bytes; more is dropped.
2003 pub fn take_output(&mut self) -> String {
2004 // The buffer leaves the state's memory with the host.
2005 self.heap.mem.release(std::mem::take(&mut self.output_charged));
2006 String::from_utf8_lossy(&std::mem::take(&mut self.output)).into_owned()
2007 }
2008
2009 /// Sends `print` (and `warn`) output to `sink` instead of the buffer, within
2010 /// [`Limits::output`] per call. The sink runs inside the call: a panic in it poisons
2011 /// the state.
2012 pub fn set_print(&mut self, sink: impl FnMut(&str) + Send + 'static) {
2013 self.print_sink = Some(Box::new(sink));
2014 }
2015
2016 /// Drops the sink [`Lua::set_print`] set: output goes to the buffer again
2017 /// ([`Lua::take_output`]).
2018 pub fn clear_print(&mut self) {
2019 self.print_sink = None;
2020 }
2021
2022 /// Sets the clocks of the `os` library: `wall`, the time since the Unix epoch, for
2023 /// `os.time` and `os.date`; `cpu`, the time the program has run, for `os.clock`. By
2024 /// default they are the system's (the process clock from when the state was made), and
2025 /// in a browser (`wasm32-unknown-unknown`, which has no clock in `std`) there are none.
2026 /// `None` makes that clock read as 0, which also makes a replay independent of the time.
2027 pub fn set_os_clocks(&mut self, wall: Option<Clock>, cpu: Option<Clock>) {
2028 self.os_clocks = (wall, cpu);
2029 }
2030
2031 /// Sets what `os.getenv(name)` returns (`Libs::ENV`): `Some(value)` adds or replaces
2032 /// `name`, `None` removes it. The map starts empty, and nothing else reaches it: the
2033 /// process environment is never read. Neither copy counts against the memory limit; the
2034 /// string `os.getenv` makes does.
2035 pub fn set_env(&mut self, name: impl AsRef<[u8]>, value: Option<&[u8]>) {
2036 let name = name.as_ref().to_vec();
2037 match value {
2038 Some(v) => {
2039 self.env_name_max = self.env_name_max.max(name.len());
2040 self.env.insert(name, v.into());
2041 }
2042 None => {
2043 self.env.remove(&name);
2044 }
2045 }
2046 }
2047
2048 /// Sets `io.stdin` (`Libs::IO`): what `io.read` and `io.lines()` read by default. `None`
2049 /// is the default, an empty stream.
2050 pub fn set_stdin(&mut self, stream: Option<Box<dyn Stream>>) {
2051 self.io_std[0] = stream.map(|s| stdlib::io::FileState::new(stdlib::io::Backing::Stream(s)));
2052 }
2053
2054 /// Sets `io.stdout` (`Libs::IO`): where `io.write` writes by default. `None` is the
2055 /// default: where `print` writes (the host's sink or [`Lua::take_output`]).
2056 pub fn set_stdout(&mut self, stream: Option<Box<dyn Stream>>) {
2057 self.io_std[1] = stream.map(|s| stdlib::io::FileState::new(stdlib::io::Backing::Stream(s)));
2058 }
2059
2060 /// Sets `io.stderr` (`Libs::IO`). `None` is the default: where `print` writes.
2061 pub fn set_stderr(&mut self, stream: Option<Box<dyn Stream>>) {
2062 self.io_std[2] = stream.map(|s| stdlib::io::FileState::new(stdlib::io::Backing::Stream(s)));
2063 }
2064
2065 /// Sets what `io.open(name, mode)` (and `io.lines(name)`, `io.input(name)`,
2066 /// `io.output(name)`) asks for a file (`Libs::IO`): the name (up to its first zero
2067 /// byte; one that is not UTF-8 is never asked for) and a mode `io.open` accepted (C's
2068 /// `[rwa]%+?b*`). An error is the script's `nil, "name: message", code`. `None`
2069 /// (the default) has every name fail with "No such file or directory".
2070 pub fn set_file_opener(&mut self, opener: Option<impl Fn(&str, &str) -> Result<Box<dyn Stream>, IoError> + Send + Sync + 'static>) {
2071 self.io_opener = opener.map(|f| Arc::new(f) as IoOpener);
2072 }
2073
2074 /// Empties `os.getenv`'s map ([`Lua::set_env`]).
2075 pub fn clear_env(&mut self) {
2076 self.env.clear();
2077 }
2078
2079 /// Sets the time zone `os.date` uses for local time, in seconds east of UTC.
2080 pub fn set_utc_offset(&mut self, seconds: i64) {
2081 self.utc_offset = seconds;
2082 }
2083
2084 /// Registers module `name` for `require` (`Libs::REQUIRE`): `require(name)` compiles
2085 /// `code` as chunk `@name` (unless `package.loaded` or `package.preload` has it first).
2086 /// The host's copy is not counted against the memory limit; what compiling it makes is.
2087 pub fn add_module(&mut self, name: &str, code: impl AsRef<[u8]>) {
2088 self.modules.insert(name.as_bytes().to_vec(), ModuleSource::new(code, name));
2089 }
2090
2091 /// Registers module `name` with its own origin (see [`ModuleSource`]).
2092 pub fn add_module_source(&mut self, name: &str, source: ModuleSource) {
2093 self.modules.insert(name.as_bytes().to_vec(), source);
2094 }
2095
2096 /// Sets the loader `require` asks for modules not registered with `add_module`
2097 /// (`None` removes it). A name that is not UTF-8 is never asked for.
2098 pub fn set_module_loader(&mut self, loader: Option<impl Fn(&str) -> Option<ModuleSource> + Send + Sync + 'static>) {
2099 self.module_loader = loader.map(|f| Arc::new(f) as ModuleLoader);
2100 }
2101
2102 /// Opens more libraries (a capability granted later).
2103 pub fn open_libs(&mut self, libs: Libs) {
2104 self.libs = self.libs | libs;
2105 stdlib::open(self, libs);
2106 }
2107}
2108
2109/// The deepest nesting [`Lua::from_data`] makes.
2110const MAX_FROM_DATA_DEPTH: usize = 64;
2111
2112/// Bytes a tracked userdata's key takes in the collected queue (charged while queued).
2113const QUEUE_ENTRY: usize = std::mem::size_of::<u64>();
2114
2115/// The most bytes [`Lua::set_userdata_size`] accepts (no allocation is larger).
2116const MAX_UD_BYTES: usize = isize::MAX as usize - heap::UD_BASE;
2117
2118/// Units of compiler scan work per unit of fuel (`diag::compile_work`).
2119const COMPILE_WORK_PER_FUEL: u64 = 8;
2120
2121pub(crate) enum CompileError {
2122 Syntax(Diagnostic),
2123 Memory,
2124 /// The host's interrupt or deadline stopped it.
2125 Limit(LimitKind),
2126}
2127
2128impl Lua {
2129 pub(crate) fn alloc_ud(&mut self, data: Box<dyn Any + Send>, size: usize, meta: Option<TableRef>) -> Result<UdRef, LuaError> {
2130 match self.heap.new_userdata(data, size, meta) {
2131 Ok(r) => Ok(r),
2132 Err(()) => Err(LuaError::Limit(LimitKind::Memory)),
2133 }
2134 }
2135}
2136
2137/// Roughly where the native stack is now (the address of a local), to measure how much a
2138/// call uses. Safe: the address is only compared, never dereferenced.
2139#[inline(never)]
2140pub(crate) fn stack_pos() -> usize {
2141 let marker = 0u8;
2142 std::hint::black_box(&marker) as *const u8 as usize
2143}
2144
2145thread_local! {
2146 /// Test switch (`set_test_stack_cap`): the most `Limits::stack_bytes` may be for states
2147 /// made or re-limited on this thread.
2148 static TEST_STACK_CAP: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
2149}
2150
2151/// Test switch: states made (or given new limits) on this thread use at most `bytes` of
2152/// native stack for library callbacks, whatever their `Limits::stack_bytes`. The test
2153/// suites run fuzzers and stress modes on small-stack threads with it, so any recursion
2154/// whose depth depends on a script's data overflows in a test, not in production.
2155#[doc(hidden)]
2156pub fn set_test_stack_cap(bytes: Option<usize>) {
2157 TEST_STACK_CAP.with(|c| c.set(bytes.unwrap_or(usize::MAX)));
2158}
2159
2160pub(crate) fn test_stack_cap() -> usize {
2161 TEST_STACK_CAP.with(std::cell::Cell::get)
2162}
2163
2164/// Results of a host function's call past which its part of `host_rets` keeps each object
2165/// once (S6-4).
2166const HOST_RETS_COMPACT: usize = 256;
2167
2168/// The collector's phase (`Lua::collector_status`).
2169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2170#[non_exhaustive]
2171pub enum CollectorPhase {
2172 /// Between cycles: none under way.
2173 Idle,
2174 /// Marking what is reachable, a step at a time.
2175 Marking,
2176 /// The end of marking (the atomic phase), suspended at a call's fuel: the next call
2177 /// from the host finishes it before any script code runs, charged to that call.
2178 AtomicSuspended,
2179 /// Freeing what marking did not reach, a step at a time.
2180 Sweeping,
2181}
2182
2183/// What `Lua::collector_status` reports.
2184#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2185#[non_exhaustive]
2186pub struct CollectorStatus {
2187 /// Where the cycle under way is.
2188 pub phase: CollectorPhase,
2189 /// Fuel for work already done and not yet charged: the collector's next steps or
2190 /// collection charge it first. Exact (work under one unit of fuel is not counted).
2191 pub owed_fuel: u64,
2192 /// At least this much more fuel finishes the cycle under way (0 when `Idle`). A floor:
2193 /// the sweep's unit per object for the slabs it has not reached, nothing for marking.
2194 pub remaining_fuel_at_least: u64,
2195 /// Whether the cycle can need more than `remaining_fuel_at_least` (every phase but
2196 /// `Idle`): marking finds the objects it must mark as it goes, the atomic phase what
2197 /// the writes since gave it, and the sweep walks the interner for each dead interned
2198 /// string.
2199 pub more_may_be_found: bool,
2200}
2201
2202/// How a call started with [`Lua::start_call`] stands after a poll.
2203#[cfg(feature = "unstable-resumable")]
2204#[derive(Debug)]
2205pub enum CallPoll {
2206 /// It returned (or stopped): what [`Lua::call`] would have returned.
2207 Ready(Result<Vec<Value>, Error>),
2208 /// It paused at the end of the poll: resume it with [`Lua::resume_call`].
2209 Pending,
2210}