use crate::heap::Heap;
use crate::value::{StrRef, TableRef, Value};
use crate::vm::{Args, Flow, Lua, LuaError, NativeFn};
pub(crate) mod base;
mod coroutine;
mod debuglib;
pub(crate) mod io;
mod math;
mod os;
mod pack;
mod package;
pub(crate) mod pattern;
pub(crate) mod string;
mod strformat;
pub(crate) mod table;
pub(crate) mod utf8;
pub(crate) type R = Result<Flow, LuaError>;
thread_local! {
static OWED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub(crate) fn owe(n: u64) {
OWED.with(|o| o.set(o.get().saturating_add(n)));
}
pub(crate) fn owed() -> u64 {
OWED.with(std::cell::Cell::get)
}
pub(crate) fn set_owed(n: u64) {
OWED.with(|o| o.set(n));
}
thread_local! {
static HELD_BACK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub(crate) fn held_back() -> usize {
HELD_BACK.with(std::cell::Cell::get)
}
pub(crate) fn set_held_back(n: usize) {
HELD_BACK.with(|h| h.set(n));
}
#[derive(Default)]
pub(crate) struct MemHold {
held: usize,
}
impl MemHold {
pub(crate) fn cover(&mut self, lua: &mut Lua, cap: usize) -> Result<(), LuaError> {
if cap > self.held {
let n = cap - self.held;
lua.charge_mem(n)?;
lua.heap.mem.debt = lua.heap.mem.debt.saturating_sub(isize::try_from(n).unwrap_or(isize::MAX));
self.held = cap;
}
Ok(())
}
#[inline]
pub(crate) fn reserve(&mut self, lua: &mut Lua, buf: &mut Vec<u8>, n: usize) -> Result<(), LuaError> {
let need = buf.len().saturating_add(n);
if need <= buf.capacity() {
return Ok(());
}
self.grow(lua, buf, need)
}
#[cold]
#[inline(never)]
fn grow(&mut self, lua: &mut Lua, buf: &mut Vec<u8>, need: usize) -> Result<(), LuaError> {
let cap = buf.capacity().saturating_mul(2).min(lua.limits.string_len).max(need);
self.cover(lua, cap)?;
if (COPY_PIECE..32 << 20).contains(&buf.capacity()) {
let mut new = Vec::with_capacity(cap);
for (i, piece) in buf.chunks(COPY_PIECE).enumerate() {
if i > 0 {
lua.check_time()?;
}
new.extend_from_slice(piece);
}
*buf = new;
} else {
buf.reserve_exact(cap - buf.len());
}
self.cover(lua, buf.capacity())
}
pub(crate) fn give_back(&mut self, lua: &mut Lua) {
lua.heap.mem.release(std::mem::take(&mut self.held));
}
}
impl Drop for MemHold {
fn drop(&mut self) {
if self.held > 0 {
let n = std::mem::take(&mut self.held);
HELD_BACK.with(|h| h.set(h.get().saturating_add(n)));
}
}
}
pub(crate) struct OutBuf {
buf: Vec<u8>,
per_unit: usize,
paid: u64,
mem: MemHold,
}
impl OutBuf {
pub(crate) fn new(per_unit: usize) -> OutBuf {
OutBuf { buf: Vec::new(), per_unit: per_unit.max(1), paid: 0, mem: MemHold::default() }
}
fn due(&self) -> u64 {
((self.buf.len() / self.per_unit) as u64).saturating_sub(self.paid)
}
pub(crate) fn pay(&mut self, lua: &mut Lua) -> Result<(), LuaError> {
let due = self.due();
if due > 0 {
self.paid += due;
lua.charge(due)?;
}
self.mem.cover(lua, self.buf.capacity())
}
pub(crate) fn reserve(&mut self, lua: &mut Lua, n: usize) -> Result<(), LuaError> {
self.mem.reserve(lua, &mut self.buf, n)
}
pub(crate) fn into_vec(mut self, lua: &mut Lua) -> Vec<u8> {
owe(self.due());
self.paid = 0;
self.mem.give_back(lua);
std::mem::take(&mut self.buf)
}
}
impl std::ops::Deref for OutBuf {
type Target = Vec<u8>;
fn deref(&self) -> &Vec<u8> {
&self.buf
}
}
impl std::ops::DerefMut for OutBuf {
fn deref_mut(&mut self) -> &mut Vec<u8> {
&mut self.buf
}
}
impl Drop for OutBuf {
fn drop(&mut self) {
owe(self.due());
}
}
pub(crate) struct Names {
pub n: StrRef,
types: [StrRef; 8],
pub next_fn: Option<crate::value::FuncRef>,
pub ipairs_aux: Option<crate::value::FuncRef>,
pub utf8_iters: [Option<crate::value::FuncRef>; 2],
pub math_fast: [Option<crate::value::FuncRef>; 6],
pub table_fast: [Option<crate::value::FuncRef>; 2],
pub table_mask: u64,
pub math_mask: u64,
pub yield_fn: Option<crate::value::FuncRef>,
pub collect_fn: Option<crate::value::FuncRef>,
pub loaded: Option<TableRef>,
}
pub(crate) const NATIVE_CHUNK: usize = 1 << 16;
pub(crate) const COPY_PIECE: usize = 1 << 20;
const TYPE_NAMES: [&str; 8] = ["nil", "boolean", "number", "string", "table", "function", "userdata", "thread"];
impl Names {
pub fn new(heap: &mut Heap) -> Names {
let mk = |h: &mut Heap, s: &str| h.intern(s.as_bytes()).unwrap_or(StrRef { idx: 0, generation: 0 });
Names { n: mk(heap, "n"), types: TYPE_NAMES.map(|t| mk(heap, t)), next_fn: None, ipairs_aux: None, utf8_iters: [None; 2], math_fast: [None; 6], math_mask: 0, table_fast: [None; 2], table_mask: 0, yield_fn: None, collect_fn: None, loaded: None }
}
pub fn mark(&self, heap: &mut Heap) {
heap.mark(Value::Str(self.n));
for t in self.types {
heap.mark(Value::Str(t));
}
}
pub fn type_of(&self, v: Value) -> StrRef {
self.types.get(type_index(v)).copied().unwrap_or(self.n)
}
pub(crate) fn types(&self) -> &[StrRef; 8] {
&self.types
}
}
pub(crate) fn type_index(v: Value) -> usize {
match v {
Value::Nil => 0,
Value::Bool(_) => 1,
Value::Int(_) | Value::Num(_) => 2,
Value::Str(_) => 3,
Value::Table(_) => 4,
Value::Func(_) => 5,
Value::UserData(_) => 6,
Value::Thread(_) => 7,
}
}
pub(crate) fn open(lua: &mut Lua, libs: crate::Libs) {
use crate::Libs;
let saved = lua.heap.mem.headroom;
lua.heap.mem.headroom = 1 << 20;
lua.heap.blocked += 1;
if libs.contains(Libs::BASE) {
base::open(lua, libs);
}
let opens: [(Libs, fn(&mut Lua)); 10] = [
(Libs::STRING, string::open),
(Libs::TABLE, table::open),
(Libs::MATH, math::open),
(Libs::UTF8, utf8::open),
(Libs::COROUTINE, coroutine::open),
(Libs::OS, os::open),
(Libs::ENV, os::open_env),
(Libs::IO, io::open),
(Libs::DEBUG_INFO, debuglib::open),
(Libs::REQUIRE, package::open),
];
for (lib, open) in opens {
if libs.contains(lib) {
open(lua);
}
}
let opened: [(Libs, &str); 11] = [
(Libs::BASE, "_G"),
(Libs::REQUIRE, "package"),
(Libs::COROUTINE, "coroutine"),
(Libs::TABLE, "table"),
(Libs::OS, "os"),
(Libs::ENV, "os"),
(Libs::IO, "io"),
(Libs::STRING, "string"),
(Libs::MATH, "math"),
(Libs::UTF8, "utf8"),
(Libs::DEBUG_INFO, "debug"),
];
if let Some(loaded) = lua.ensure_loaded() {
for (lib, name) in opened {
if libs.contains(lib) {
let k = lua.new_str(name.as_bytes()).unwrap_or_default();
let v = lua.raw_get(lua.globals, k);
if !v.is_nil() {
let _ = lua.raw_set(loaded, k, v);
}
}
}
}
lua.heap.blocked -= 1;
lua.heap.mem.headroom = saved;
}
impl Lua {
pub(crate) fn loaded_table(&self) -> Option<TableRef> {
self.names.loaded.filter(|t| self.heap.is_live(Value::Table(*t)))
}
pub(crate) fn ensure_loaded(&mut self) -> Option<TableRef> {
if let Some(t) = self.loaded_table() {
return Some(t);
}
let t = self.new_table(0, 16).ok()?;
let k = self.new_str(b"_LOADED").ok()?;
let reg = self.registry;
self.raw_set(reg, k, Value::Table(t)).ok()?;
self.names.loaded = Some(t);
Some(t)
}
pub(crate) fn lib_table(&mut self, name: &str) -> TableRef {
let k = self.new_str(name.as_bytes()).unwrap_or_default();
if let Value::Table(t) = self.raw_get(self.globals, k) {
return t;
}
let t = self.new_table(0, 32).unwrap_or(self.globals);
let g = self.globals;
let _ = self.raw_set(g, k, Value::Table(t));
t
}
pub(crate) fn set_fn(&mut self, t: TableRef, name: &str, qualified: &'static str, f: NativeFn) {
let k = self.new_str(name.as_bytes()).unwrap_or_default();
let v = self.new_native(f, qualified, Vec::new()).unwrap_or_default();
let _ = self.raw_set(t, k, v);
}
pub(crate) fn set_field(&mut self, t: TableRef, name: &str, v: Value) {
let k = self.new_str(name.as_bytes()).unwrap_or_default();
let _ = self.raw_set(t, k, v);
}
#[inline]
pub(crate) fn arg(&self, a: Args, i: usize) -> Value {
if i < a.n { self.st(a.base + i) } else { Value::Nil }
}
fn got(&self, a: Args, i: usize) -> String {
if i >= a.n { "no value".into() } else { self.arg_type_name(self.arg(a, i)) }
}
pub(crate) fn type_error(&self, a: Args, i: usize, expected: &str) -> LuaError {
LuaError::Arg(i + 1, format!("{expected} expected, got {}", self.got(a, i)))
}
pub(crate) fn check_any(&self, a: Args, i: usize) -> Result<Value, LuaError> {
if i >= a.n { Err(LuaError::Arg(i + 1, "value expected".into())) } else { Ok(self.arg(a, i)) }
}
pub(crate) fn check_table(&self, a: Args, i: usize) -> Result<TableRef, LuaError> {
match self.arg(a, i) {
Value::Table(t) => Ok(t),
_ => Err(self.type_error(a, i, "table")),
}
}
pub(crate) fn check_int(&mut self, a: Args, i: usize) -> Result<i64, LuaError> {
match self.tonumber_charged(self.arg(a, i))? {
Some(Value::Int(n)) => Ok(n),
Some(Value::Num(f)) => {
crate::number::float_to_int(f).ok_or_else(|| LuaError::Arg(i + 1, "number has no integer representation".into()))
}
_ => Err(self.type_error(a, i, "number")),
}
}
pub(crate) fn opt_int(&mut self, a: Args, i: usize, d: i64) -> Result<i64, LuaError> {
if self.arg(a, i).is_nil() { Ok(d) } else { self.check_int(a, i) }
}
pub(crate) fn check_num(&mut self, a: Args, i: usize) -> Result<f64, LuaError> {
match self.tonumber_charged(self.arg(a, i))? {
Some(v) => Ok(v.as_num().unwrap_or(0.0)),
None => Err(self.type_error(a, i, "number")),
}
}
#[inline]
pub(crate) fn check_str(&mut self, a: Args, i: usize) -> Result<StrRef, LuaError> {
match self.arg(a, i) {
Value::Str(s) => Ok(s),
_ => self.check_str_conv(a, i),
}
}
#[inline(never)]
fn check_str_conv(&mut self, a: Args, i: usize) -> Result<StrRef, LuaError> {
match self.arg(a, i) {
Value::Str(s) => Ok(s),
v @ (Value::Int(_) | Value::Num(_)) => {
let mut b = Vec::new();
match v {
Value::Int(n) => b.extend_from_slice(n.to_string().as_bytes()),
Value::Num(f) => {
owe(crate::vm::FLOAT_TEXT_FUEL);
b.extend_from_slice(crate::number::fmt_float(f).as_bytes());
}
_ => {}
}
match self.new_str(&b)? {
Value::Str(s) => Ok(s),
_ => Err(self.type_error(a, i, "string")),
}
}
_ => Err(self.type_error(a, i, "string")),
}
}
#[inline]
pub(crate) fn check_len(&self, n: usize) -> Result<(), LuaError> {
if n > self.limits.string_len { Err(LuaError::Limit(crate::LimitKind::Memory)) } else { Ok(()) }
}
pub(crate) fn opt_str(&mut self, a: Args, i: usize) -> Result<Option<StrRef>, LuaError> {
if self.arg(a, i).is_nil() { Ok(None) } else { self.check_str(a, i).map(Some) }
}
#[inline]
pub(crate) fn ret(&mut self, vals: &[Value]) -> R {
self.rets.clear();
self.rets.extend_from_slice(vals);
Ok(Flow::Return)
}
#[inline]
pub(crate) fn ret1(&mut self, v: Value) -> R {
self.rets.clear();
self.rets.push(v);
Ok(Flow::Return)
}
pub(crate) fn ret_str(&mut self, b: &[u8]) -> R {
let v = self.new_str(b)?;
self.ret1(v)
}
pub(crate) fn extend_watched(&mut self, out: &mut Vec<u8>, s: StrRef, from: usize, to: usize) -> Result<(), LuaError> {
let to = to.min(self.heap.str_bytes(s).len());
if from >= to {
return Ok(());
}
if to - from > COPY_PIECE {
out.reserve(to - from);
}
let mut at = from;
while at < to {
let end = at.saturating_add(COPY_PIECE).min(to);
out.extend_from_slice(self.heap.str_bytes(s).get(at..end).unwrap_or_default());
at = end;
if at < to {
self.check_time()?;
}
}
Ok(())
}
pub(crate) fn new_copied(&mut self, s: StrRef, from: usize, to: usize) -> Result<Value, LuaError> {
let len = self.heap.str_bytes(s).get(from..to).map_or(0, <[u8]>::len);
if len <= COPY_PIECE {
return self.new_derived(s, from, to, |src, dest| dest.copy_from_slice(src));
}
let charged = crate::heap::str_mem(len);
self.charge_mem(charged)?;
let mut buf = Vec::with_capacity(len);
if let Err(e) = self.extend_watched(&mut buf, s, from, to) {
self.heap.mem.release(charged);
return Err(e);
}
let v = Value::Str(self.heap.new_long_charged(buf.into_boxed_slice()));
self.hold(v);
Ok(v)
}
pub(crate) fn new_owned(&mut self, b: Vec<u8>) -> Result<Value, LuaError> {
if b.len() <= crate::heap::SHORT_LEN || b.len() > self.limits.string_len {
return self.new_str(&b);
}
self.charge_mem(crate::heap::str_mem(b.len()))?;
let v = Value::Str(self.heap.new_long_charged(b.into_boxed_slice()));
self.hold(v);
Ok(v)
}
pub(crate) fn ret_owned(&mut self, b: Vec<u8>) -> R {
let v = self.new_owned(b)?;
self.ret1(v)
}
pub(crate) fn ret_derived(&mut self, s: StrRef, from: usize, to: usize, fill: impl Fn(&[u8], &mut [u8])) -> R {
let v = self.new_derived(s, from, to, fill)?;
self.ret1(v)
}
pub(crate) fn new_derived(&mut self, s: StrRef, from: usize, to: usize, fill: impl Fn(&[u8], &mut [u8])) -> Result<Value, LuaError> {
let len = self.heap.str_bytes(s).get(from..to).map_or(0, <[u8]>::len);
self.new_built(len, |h, dest| fill(h.str_bytes(s).get(from..to).unwrap_or_default(), dest))
}
pub(crate) fn ret_mapped(&mut self, s: StrRef, fill: impl Fn(&[u8], usize, &mut [u8])) -> R {
const CHUNK: usize = 1 << 20;
let len = self.heap.str_bytes(s).len();
if len <= CHUNK {
return self.ret_derived(s, 0, len, |src, dest| fill(src, 0, dest));
}
self.charge_mem(crate::heap::str_mem(len))?;
let mut buf = vec![0u8; len].into_boxed_slice();
for (k, dest) in buf.chunks_mut(CHUNK).enumerate() {
if k > 0
&& let Err(e) = self.check_time()
{
self.heap.mem.release(crate::heap::str_mem(len));
return Err(e);
}
fill(self.heap.str_bytes(s), k * CHUNK, dest);
}
let v = Value::Str(self.heap.new_long_charged(buf));
self.hold(v);
self.ret1(v)
}
pub(crate) fn new_built(&mut self, len: usize, fill: impl Fn(&Heap, &mut [u8])) -> Result<Value, LuaError> {
if len <= crate::heap::SHORT_LEN {
let mut buf = [0u8; crate::heap::SHORT_LEN];
let dest = buf.get_mut(..len).unwrap_or_default();
fill(&self.heap, dest);
return self.new_str(dest);
}
self.charge_mem(crate::heap::str_mem(len))?;
let mut buf = vec![0u8; len].into_boxed_slice();
fill(&self.heap, &mut buf);
let v = Value::Str(self.heap.new_long_charged(buf));
self.hold(v);
Ok(v)
}
pub(crate) fn native_upval(&self, a: Args, i: usize) -> Value {
let Value::Func(f) = self.st(a.func) else { return Value::Nil };
match self.heap.funcs.get(f.idx) {
Some(crate::heap::Func::Native { upvals, .. }) => upvals.get(i).copied().unwrap_or_default(),
_ => Value::Nil,
}
}
pub(crate) fn check_option(&mut self, a: Args, i: usize, def: Option<&str>, names: &[&str]) -> Result<usize, LuaError> {
let name = match (self.arg(a, i), def) {
(Value::Nil, Some(d)) => d.as_bytes().to_vec(),
_ => {
let s = self.check_str(a, i)?;
self.bytes(s).split(|&c| c == 0).next().unwrap_or_default().to_vec()
}
};
names.iter().position(|n| n.as_bytes() == name).ok_or_else(|| {
let shown = String::from_utf8_lossy(name.get(..name.len().min(self.limits.error_len)).unwrap_or_default()).into_owned();
LuaError::Arg(i + 1, format!("invalid option '{shown}'"))
})
}
pub(crate) fn native_upvals_len(&self, a: Args) -> usize {
let Value::Func(f) = self.st(a.func) else { return 0 };
match self.heap.funcs.get(f.idx) {
Some(crate::heap::Func::Native { upvals, .. }) => upvals.len(),
_ => 0,
}
}
pub(crate) fn set_native_upval(&mut self, a: Args, i: usize, v: Value) {
let Value::Func(f) = self.st(a.func) else { return };
if let Some(crate::heap::Func::Native { upvals, .. }) = self.heap.funcs.get_mut(f.idx)
&& let Some(s) = upvals.get_mut(i)
{
*s = v;
}
if v.is_collectable() {
if self.heap.phase == crate::heap::Phase::Propagate {
self.heap.mark(v);
}
}
}
}