Files
Lua-compilateur/include/luacpp/rt.hpp
T
BlackAngelTV 517ed0bf4d feat(compiler): add a Lua 5.4 to C++ module transpiler
Each Lua module becomes a header/source pair exposing a C++ namespace, so Lua
code can be linked and consumed like any C++ package while keeping the exact
semantics of the official 5.4 VM.
2026-11-18 08:48:05 +01:00

754 lines
23 KiB
C++

// luacpp runtime: thin C++ layer over the official Lua 5.4 C API.
// Used both by the code generated by the `luacpp` transpiler and by host C++ code
// that consumes compiled Lua modules as C++ packages.
#pragma once
#include <lua.hpp>
#if LUA_VERSION_NUM != 504
#error "luacpp requires Lua 5.4 (LUA_VERSION_NUM == 504)"
#endif
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
namespace luacpp {
class Error : public std::runtime_error {
public:
explicit Error(const std::string& m) : std::runtime_error(m) {}
};
namespace detail {
inline std::string take_error(lua_State* L) {
const char* s = lua_tostring(L, -1);
std::string m = s ? s : "unknown Lua error";
lua_pop(L, 1);
return m;
}
inline void need_stack(lua_State* L, int n) {
if (!lua_checkstack(L, n)) throw Error("Lua stack overflow");
}
} // namespace detail
// ---------------------------------------------------------------------------
// Raw helpers used by generated code. They must never throw C++ exceptions:
// they either succeed or raise a Lua error (longjmp) like any C function.
// ---------------------------------------------------------------------------
inline void check_stack(lua_State* L, int n) {
if (!lua_checkstack(L, n)) luaL_error(L, "luacpp: stack overflow");
}
// Ensures that exactly `want` values sit above `base` (pads with nil / trims).
inline void adjust(lua_State* L, int base, int want) {
int got = lua_gettop(L) - base;
if (got < want) {
check_stack(L, want - got);
for (; got < want; ++got) lua_pushnil(L);
} else if (got > want) {
lua_settop(L, base + want);
}
}
inline bool pop_bool(lua_State* L) {
bool b = lua_toboolean(L, -1) != 0;
lua_pop(L, 1);
return b;
}
// Packs the extra arguments of a vararg C function into a table at `slot`.
inline void pack_varargs(lua_State* L, int nparams, int slot) {
int n = lua_gettop(L);
if (n < nparams) {
lua_settop(L, nparams);
n = nparams;
}
int tbl = n + 1;
check_stack(L, 2);
lua_createtable(L, n - nparams, 0);
for (int i = nparams + 1; i <= n; ++i) {
lua_pushvalue(L, i);
lua_rawseti(L, tbl, i - nparams);
}
if (tbl != slot) lua_replace(L, slot);
lua_settop(L, slot);
}
// Pushes every packed vararg (dynamic count).
inline void push_varargs(lua_State* L, int slot) {
lua_Integer n = static_cast<lua_Integer>(lua_rawlen(L, slot));
check_stack(L, static_cast<int>(n) + 1);
for (lua_Integer i = 1; i <= n; ++i) lua_rawgeti(L, slot, i);
}
// Numeric `for`: normalises the three control values, returns false when the
// loop body must never run. Mirrors Lua 5.4 integer/float semantics.
inline bool numeric_for_prep(lua_State* L, int idx, int limit, int step) {
if (lua_isinteger(L, idx) && lua_isinteger(L, limit) && lua_isinteger(L, step)) {
lua_Integer s = lua_tointeger(L, step);
if (s == 0) luaL_error(L, "'for' step is zero");
lua_Integer i = lua_tointeger(L, idx);
lua_Integer l = lua_tointeger(L, limit);
return s > 0 ? (i <= l) : (i >= l);
}
lua_Number i = luaL_checknumber(L, idx);
lua_Number l = luaL_checknumber(L, limit);
lua_Number s = luaL_checknumber(L, step);
if (s == 0) luaL_error(L, "'for' step is zero");
lua_pushnumber(L, i);
lua_replace(L, idx);
lua_pushnumber(L, l);
lua_replace(L, limit);
lua_pushnumber(L, s);
lua_replace(L, step);
return s > 0 ? (i <= l) : (i >= l);
}
inline bool numeric_for_next(lua_State* L, int idx, int limit, int step) {
if (lua_isinteger(L, idx) && lua_isinteger(L, limit) && lua_isinteger(L, step)) {
lua_Integer i = lua_tointeger(L, idx);
lua_Integer l = lua_tointeger(L, limit);
lua_Integer s = lua_tointeger(L, step);
lua_Integer v;
if (s > 0) {
if (i > LUA_MAXINTEGER - s) return false;
v = i + s;
if (v > l) return false;
} else {
if (s == LUA_MININTEGER) {
if (i < 0) return false;
} else if (i < LUA_MININTEGER - s) {
return false;
}
v = i + s;
if (v < l) return false;
}
lua_pushinteger(L, v);
lua_replace(L, idx);
return true;
}
lua_Number i = lua_tonumber(L, idx);
lua_Number l = lua_tonumber(L, limit);
lua_Number s = lua_tonumber(L, step);
lua_Number v = i + s;
bool cont = s > 0 ? (v <= l) : (v >= l);
if (!cont) return false;
lua_pushnumber(L, v);
lua_replace(L, idx);
return true;
}
// Generic `for`: calls f(s, ctl), stores the results into the loop variables
// and returns false when the iteration must stop.
inline bool generic_next(lua_State* L, int f, int s, int ctl, int vars, int nvars) {
int base = lua_gettop(L);
check_stack(L, nvars + 8);
lua_pushvalue(L, f);
lua_pushvalue(L, s);
lua_pushvalue(L, ctl);
lua_call(L, 2, LUA_MULTRET);
int nres = lua_gettop(L) - base;
if (nres < 1 || lua_isnil(L, base + 1)) {
lua_settop(L, base);
return false;
}
lua_copy(L, base + 1, ctl);
for (int i = 0; i < nvars; ++i) {
if (i + 1 <= nres) {
lua_copy(L, base + 1 + i, vars + i);
} else {
lua_pushnil(L);
lua_replace(L, vars + i);
}
}
lua_settop(L, base);
return true;
}
// Appends every value above `tableidx` to the given table (used by `{f()}`).
inline void append_all(lua_State* L, int tableidx) {
int n = lua_gettop(L) - tableidx;
lua_Integer len = static_cast<lua_Integer>(lua_rawlen(L, tableidx));
for (int i = 1; i <= n; ++i) {
lua_pushvalue(L, tableidx + i);
lua_rawseti(L, tableidx, len + i);
}
lua_settop(L, tableidx);
}
// ---------------------------------------------------------------------------
// Compiled module registry + `require`
// ---------------------------------------------------------------------------
inline std::unordered_map<std::string, lua_CFunction>& module_registry() {
static std::unordered_map<std::string, lua_CFunction> registry;
return registry;
}
inline void register_builtin(const char* name, lua_CFunction opener) {
module_registry()[name] = opener;
}
// Registers a compiled Lua module at static-initialisation time.
struct AutoModule {
AutoModule(const char* name, lua_CFunction opener) { register_builtin(name, opener); }
};
// Pushes the module value. Returns false (with the error message on the stack)
// when loading fails.
inline bool try_require(lua_State* L, const char* name) {
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
lua_getfield(L, -1, name);
if (!lua_isnil(L, -1)) {
lua_remove(L, -2);
return true;
}
lua_pop(L, 2);
auto it = module_registry().find(name);
if (it != module_registry().end()) {
check_stack(L, 4);
lua_pushcfunction(L, it->second);
if (lua_pcall(L, 0, 1, 0) != LUA_OK) return false;
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_pushboolean(L, 1);
}
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
lua_pushvalue(L, -2);
lua_setfield(L, -2, name);
lua_pop(L, 1);
return true;
}
lua_getglobal(L, "require");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 1);
lua_pushfstring(L, "module '%s' not found", name);
return false;
}
lua_pushstring(L, name);
return lua_pcall(L, 1, 1, 0) == LUA_OK;
}
// `require` as seen by compiled Lua code: errors propagate as Lua errors.
inline void require(lua_State* L, const char* name) {
if (!try_require(L, name)) lua_error(L);
}
// ---------------------------------------------------------------------------
// Argument pushing (forward declared so Value::call can use it)
// ---------------------------------------------------------------------------
class Value;
void push_arg(lua_State* L, const Value& v);
void push_arg(lua_State* L, Value&& v);
inline void push_arg(lua_State* L, bool v) { lua_pushboolean(L, v ? 1 : 0); }
inline void push_arg(lua_State* L, int v) { lua_pushinteger(L, v); }
inline void push_arg(lua_State* L, long v) { lua_pushinteger(L, static_cast<lua_Integer>(v)); }
inline void push_arg(lua_State* L, long long v) { lua_pushinteger(L, static_cast<lua_Integer>(v)); }
inline void push_arg(lua_State* L, unsigned v) { lua_pushinteger(L, v); }
inline void push_arg(lua_State* L, double v) { lua_pushnumber(L, static_cast<lua_Number>(v)); }
inline void push_arg(lua_State* L, float v) { lua_pushnumber(L, static_cast<lua_Number>(v)); }
inline void push_arg(lua_State* L, const char* v) { lua_pushstring(L, v); }
inline void push_arg(lua_State* L, const std::string& v) { lua_pushlstring(L, v.data(), v.size()); }
inline void push_arg(lua_State* L, std::string_view v) { lua_pushlstring(L, v.data(), v.size()); }
inline void push_arg(lua_State* L, lua_CFunction f) { lua_pushcfunction(L, f); }
// ---------------------------------------------------------------------------
// Value
// ---------------------------------------------------------------------------
class Value {
public:
enum class Kind { Nil, Bool, Number, Integer, String, Ref };
Value() = default;
Value(std::nullptr_t) {}
Value(bool b) : kind_(Kind::Bool), bool_(b) {}
Value(int v) : kind_(Kind::Integer), int_(v) {}
Value(long v) : kind_(Kind::Integer), int_(static_cast<lua_Integer>(v)) {}
Value(long long v) : kind_(Kind::Integer), int_(static_cast<lua_Integer>(v)) {}
Value(unsigned v) : kind_(Kind::Integer), int_(v) {}
Value(double v) : kind_(Kind::Number), num_(v) {}
Value(float v) : kind_(Kind::Number), num_(v) {}
Value(const char* s) : kind_(Kind::String), str_(s ? s : "") {}
Value(std::string s) : kind_(Kind::String), str_(std::move(s)) {}
Value(std::string_view s) : kind_(Kind::String), str_(s) {}
Value(const Value&) = default;
Value(Value&&) noexcept = default;
Value& operator=(const Value&) = default;
Value& operator=(Value&&) noexcept = default;
// Pops the value on top of the stack and takes ownership of it.
static Value adopt(lua_State* L) {
Value v;
switch (lua_type(L, -1)) {
case LUA_TNIL:
break;
case LUA_TBOOLEAN:
v.kind_ = Kind::Bool;
v.bool_ = lua_toboolean(L, -1) != 0;
break;
case LUA_TNUMBER:
if (lua_isinteger(L, -1)) {
v.kind_ = Kind::Integer;
v.int_ = lua_tointeger(L, -1);
} else {
v.kind_ = Kind::Number;
v.num_ = lua_tonumber(L, -1);
}
break;
case LUA_TSTRING: {
size_t n = 0;
const char* s = lua_tolstring(L, -1, &n);
v.kind_ = Kind::String;
v.str_.assign(s, n);
break;
}
default:
v.kind_ = Kind::Ref;
v.ref_ = std::make_shared<Ref>(L, luaL_ref(L, LUA_REGISTRYINDEX));
return v;
}
lua_pop(L, 1);
return v;
}
static Value from_stack(lua_State* L, int idx) {
lua_pushvalue(L, idx);
return adopt(L);
}
Kind kind() const { return kind_; }
bool is_nil() const { return kind_ == Kind::Nil; }
bool is_bool() const { return kind_ == Kind::Bool; }
bool is_number() const { return kind_ == Kind::Number || kind_ == Kind::Integer; }
bool is_integer() const { return kind_ == Kind::Integer; }
bool is_string() const { return kind_ == Kind::String; }
bool is_table() const { return is_ref_of(LUA_TTABLE); }
bool is_function() const { return is_ref_of(LUA_TFUNCTION); }
const char* type_name() const {
switch (kind_) {
case Kind::Nil: return "nil";
case Kind::Bool: return "boolean";
case Kind::Number:
case Kind::Integer: return "number";
case Kind::String: return "string";
case Kind::Ref: {
lua_State* L = state();
if (!L) return "nil";
lua_rawgeti(L, LUA_REGISTRYINDEX, ref_->ref);
const char* t = luaL_typename(L, -1);
lua_pop(L, 1);
return t;
}
}
return "nil";
}
// Lua truthiness: everything but nil and false.
bool truthy() const {
if (kind_ == Kind::Nil) return false;
if (kind_ == Kind::Bool) return bool_;
return true;
}
double as_number() const {
switch (kind_) {
case Kind::Number: return num_;
case Kind::Integer: return static_cast<double>(int_);
case Kind::String: return parse_number();
default: throw Error(std::string("expected a number, got ") + type_name());
}
}
lua_Integer as_integer() const {
switch (kind_) {
case Kind::Integer: return int_;
case Kind::Number: {
if (std::floor(num_) != num_ || num_ < -9.2233720368547758e18 || num_ > 9.2233720368547758e18)
throw Error("number has no integer representation");
return static_cast<lua_Integer>(num_);
}
case Kind::String: {
double d = parse_number();
if (std::floor(d) != d) throw Error("string has no integer representation");
return static_cast<lua_Integer>(d);
}
default: throw Error(std::string("expected an integer, got ") + type_name());
}
}
const std::string& as_string() const {
if (kind_ != Kind::String) throw Error(std::string("expected a string, got ") + type_name());
return str_;
}
const std::string& raw_string() const { return as_string(); }
std::string to_string() const {
switch (kind_) {
case Kind::Nil: return "nil";
case Kind::Bool: return bool_ ? "true" : "false";
case Kind::Integer: return std::to_string(int_);
case Kind::Number: {
char buf[64];
std::snprintf(buf, sizeof buf, LUA_NUMBER_FMT, static_cast<lua_Number>(num_));
std::string s(buf);
if (s.find_first_of(".eEni") == std::string::npos) s += ".0";
return s;
}
case Kind::String: return str_;
case Kind::Ref: {
lua_State* L = state();
if (!L) return "nil";
detail::need_stack(L, 2);
lua_rawgeti(L, LUA_REGISTRYINDEX, ref_->ref);
size_t n = 0;
const char* s = luaL_tolstring(L, -1, &n);
std::string out(s ? s : "", n);
lua_pop(L, 2);
return out;
}
}
return "nil";
}
std::size_t length() const {
if (kind_ == Kind::String) return str_.size();
lua_State* L = state();
if (!L) throw Error("length of a nil value");
detail::need_stack(L, 2);
lua_rawgeti(L, LUA_REGISTRYINDEX, ref_->ref);
lua_len(L, -1);
std::size_t n = static_cast<std::size_t>(lua_tointeger(L, -1));
lua_pop(L, 2);
return n;
}
lua_State* state() const { return ref_ ? ref_->L : nullptr; }
void push(lua_State* L) const {
switch (kind_) {
case Kind::Nil: lua_pushnil(L); break;
case Kind::Bool: lua_pushboolean(L, bool_ ? 1 : 0); break;
case Kind::Number: lua_pushnumber(L, static_cast<lua_Number>(num_)); break;
case Kind::Integer: lua_pushinteger(L, int_); break;
case Kind::String: lua_pushlstring(L, str_.data(), str_.size()); break;
case Kind::Ref:
if (ref_->L != L) throw Error("luacpp::Value belongs to another Lua state");
lua_rawgeti(L, LUA_REGISTRYINDEX, ref_->ref);
break;
}
}
Value get(const std::string& key) const { return field(key); }
Value field(const std::string& key) const {
lua_State* L = require_state();
int base = lua_gettop(L);
detail::need_stack(L, 3);
push(L);
lua_getfield(L, -1, key.c_str());
Value v = adopt(L);
lua_settop(L, base);
return v;
}
Value at(lua_Integer index) const {
lua_State* L = require_state();
int base = lua_gettop(L);
detail::need_stack(L, 3);
push(L);
lua_geti(L, -1, index);
Value v = adopt(L);
lua_settop(L, base);
return v;
}
Value at(const Value& key) const {
lua_State* L = require_state();
int base = lua_gettop(L);
detail::need_stack(L, 4);
push(L);
key.push(L);
lua_gettable(L, -2);
Value v = adopt(L);
lua_settop(L, base);
return v;
}
bool has(const std::string& key) const { return !field(key).is_nil(); }
template <class... Args>
Value call(Args&&... args) const {
lua_State* L = require_state();
int base = lua_gettop(L);
detail::need_stack(L, static_cast<int>(sizeof...(Args)) + 4);
push(L);
(push_arg(L, std::forward<Args>(args)), ...);
if (lua_pcall(L, static_cast<int>(sizeof...(Args)), 1, 0) != LUA_OK) {
std::string m = detail::take_error(L);
lua_settop(L, base);
throw Error(m);
}
Value v = adopt(L);
lua_settop(L, base);
return v;
}
template <class... Args>
std::vector<Value> call_multi(Args&&... args) const {
lua_State* L = require_state();
int base = lua_gettop(L);
detail::need_stack(L, static_cast<int>(sizeof...(Args)) + 4);
push(L);
(push_arg(L, std::forward<Args>(args)), ...);
if (lua_pcall(L, static_cast<int>(sizeof...(Args)), LUA_MULTRET, 0) != LUA_OK) {
std::string m = detail::take_error(L);
lua_settop(L, base);
throw Error(m);
}
int n = lua_gettop(L) - base;
std::vector<Value> out;
out.reserve(n > 0 ? static_cast<std::size_t>(n) : 0);
for (int i = 1; i <= n; ++i) out.push_back(Value::from_stack(L, base + i));
lua_settop(L, base);
return out;
}
private:
struct Ref {
lua_State* L;
int ref;
~Ref() { luaL_unref(L, LUA_REGISTRYINDEX, ref); }
Ref(lua_State* state, int r) : L(state), ref(r) {}
Ref(const Ref&) = delete;
Ref& operator=(const Ref&) = delete;
};
bool is_ref_of(int luaType) const {
lua_State* L = state();
if (!L) return false;
lua_rawgeti(L, LUA_REGISTRYINDEX, ref_->ref);
bool ok = lua_type(L, -1) == luaType;
lua_pop(L, 1);
return ok;
}
double parse_number() const {
const char* s = str_.c_str();
char* end = nullptr;
double d = std::strtod(s, &end);
while (end && (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r')) ++end;
if (!end || *end != '\0' || end == s) throw Error("cannot convert string to number: '" + str_ + "'");
return d;
}
lua_State* require_state() const {
lua_State* L = state();
if (!L) throw Error("value is not bound to a Lua state (cannot index or call a scalar)");
return L;
}
Kind kind_ = Kind::Nil;
bool bool_ = false;
lua_Integer int_ = 0;
lua_Number num_ = 0;
std::string str_;
std::shared_ptr<Ref> ref_;
};
inline void push_arg(lua_State* L, const Value& v) { v.push(L); }
inline void push_arg(lua_State* L, Value&& v) { v.push(L); }
// Convenience: a std::vector<Value> becomes a Lua array (1-based).
inline void push_arg(lua_State* L, const std::vector<Value>& values) {
check_stack(L, static_cast<int>(values.size()) + 1);
lua_createtable(L, static_cast<int>(values.size()), 0);
for (size_t i = 0; i < values.size(); ++i) {
values[i].push(L);
lua_rawseti(L, -2, static_cast<lua_Integer>(i) + 1);
}
}
// ---------------------------------------------------------------------------
// Module
// ---------------------------------------------------------------------------
class Module {
public:
Module() = default;
Module(Value table, std::string name) : table_(std::move(table)), name_(std::move(name)) {}
const Value& table() const { return table_; }
const std::string& name() const { return name_; }
bool valid() const { return !table_.is_nil(); }
Value get(const std::string& key) const { return table_.field(key); }
bool has(const std::string& key) const { return table_.has(key); }
void set(const std::string& key, const Value& v) const {
lua_State* L = table_.state();
if (!L) throw Error("invalid module");
detail::need_stack(L, 4);
table_.push(L);
v.push(L);
lua_setfield(L, -2, key.c_str());
lua_pop(L, 1);
}
template <class... Args>
Value call(const std::string& fn, Args&&... args) const {
return get(fn).call(std::forward<Args>(args)...);
}
template <class... Args>
std::vector<Value> call_multi(const std::string& fn, Args&&... args) const {
return get(fn).call_multi(std::forward<Args>(args)...);
}
private:
Value table_;
std::string name_;
};
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
class State {
public:
State() {
L_ = luaL_newstate();
if (!L_) throw Error("cannot create a Lua state");
own_ = true;
luaL_openlibs(L_);
}
explicit State(lua_State* L, bool own = false) : L_(L), own_(own) {
if (own_ && L_) luaL_openlibs(L_);
}
~State() {
if (own_ && L_) lua_close(L_);
}
State(const State&) = delete;
State& operator=(const State&) = delete;
State(State&& other) noexcept : L_(other.L_), own_(other.own_) {
other.L_ = nullptr;
other.own_ = false;
}
State& operator=(State&& other) noexcept {
if (this != &other) {
if (own_ && L_) lua_close(L_);
L_ = other.L_;
own_ = other.own_;
other.L_ = nullptr;
other.own_ = false;
}
return *this;
}
lua_State* raw() const { return L_; }
Value require(const std::string& name) const {
int base = lua_gettop(L_);
detail::need_stack(L_, 2);
if (!try_require(L_, name.c_str())) {
std::string m = detail::take_error(L_);
lua_settop(L_, base);
throw Error(m);
}
Value v = Value::adopt(L_);
lua_settop(L_, base);
return v;
}
Module module(const std::string& name) const { return Module(require(name), name); }
Value global(const std::string& name) const {
int base = lua_gettop(L_);
lua_getglobal(L_, name.c_str());
Value v = Value::adopt(L_);
lua_settop(L_, base);
return v;
}
void set_global(const std::string& name, const Value& v) {
detail::need_stack(L_, 2);
v.push(L_);
lua_setglobal(L_, name.c_str());
}
void do_string(const std::string& code, const char* chunkname = "=string") {
int base = lua_gettop(L_);
if (luaL_loadbuffer(L_, code.data(), code.size(), chunkname) != LUA_OK) {
std::string m = detail::take_error(L_);
lua_settop(L_, base);
throw Error(m);
}
if (lua_pcall(L_, 0, 0, 0) != LUA_OK) {
std::string m = detail::take_error(L_);
lua_settop(L_, base);
throw Error(m);
}
lua_settop(L_, base);
}
void do_file(const std::string& path) {
int base = lua_gettop(L_);
if (luaL_loadfile(L_, path.c_str()) != LUA_OK) {
std::string m = detail::take_error(L_);
lua_settop(L_, base);
throw Error(m);
}
if (lua_pcall(L_, 0, 0, 0) != LUA_OK) {
std::string m = detail::take_error(L_);
lua_settop(L_, base);
throw Error(m);
}
lua_settop(L_, base);
}
// Lets plain `.lua` files be required as a fallback next to compiled modules.
void add_package_path(const std::string& dir) {
detail::need_stack(L_, 4);
lua_getglobal(L_, "package");
if (!lua_istable(L_, -1)) {
lua_pop(L_, 1);
return;
}
lua_getfield(L_, -1, "path");
std::string path = lua_isstring(L_, -1) ? lua_tostring(L_, -1) : std::string();
lua_pop(L_, 1);
path += ";" + dir + "/?.lua;" + dir + "/?/init.lua";
lua_pushlstring(L_, path.data(), path.size());
lua_setfield(L_, -2, "path");
lua_pop(L_, 1);
}
private:
lua_State* L_ = nullptr;
bool own_ = false;
};
} // namespace luacpp