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.
This commit is contained in:
BlackAngelTV committed 2026-11-18 08:48:05 +01:00
1 parent b7636626fe
commit ab5ff6978a
8 files changed
+3476

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
cmake_minimum_required(VERSION 3.20)
project(luacpp VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(LUACPP_BUILD_EXAMPLES "Build the example package and program" ON)
option(LUACPP_BUILD_TESTS "Build the conformance test" ON)
# --- Lua 5.4 -----------------------------------------------------------------
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(LUA54 QUIET IMPORTED_TARGET lua5.4)
endif()
if(NOT LUA54_FOUND)
find_package(Lua 5.4 REQUIRED)
endif()
add_library(luacpp_rt INTERFACE)
add_library(luacpp::rt ALIAS luacpp_rt)
target_include_directories(luacpp_rt INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include")
if(LUA54_FOUND)
target_link_libraries(luacpp_rt INTERFACE PkgConfig::LUA54)
message(STATUS "luacpp: using Lua 5.4 from pkg-config")
else()
target_include_directories(luacpp_rt INTERFACE ${LUA_INCLUDE_DIR})
target_link_libraries(luacpp_rt INTERFACE ${LUA_LIBRARIES})
message(STATUS "luacpp: using Lua 5.4 from FindLua")
endif()
# --- compiler ----------------------------------------------------------------
add_executable(luacpp
src/main.cpp
src/frontend.cpp
src/codegen.cpp)
target_include_directories(luacpp PRIVATE src)
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(luacpp PRIVATE -Wall -Wextra -Wpedantic)
endif()
include(cmake/lua-package.cmake)
if(LUACPP_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(LUACPP_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
+70
View File
@@ -0,0 +1,70 @@
# add_lua_package(<target>
# ROOT <dir> # directory the Lua module names are relative to
# MODULES <a.lua> [b.lua ...]
# [OUTPUT_DIR <dir>] # where the .hpp/.cpp files are generated
# [NAMESPACE <ns>]) # C++ namespace prefix, also prefixes Lua module names
#
# Creates an OBJECT library <target> holding the compiled Lua modules. Link it
# into an executable to make the modules part of the binary:
#
# add_lua_package(my_lua ROOT lua MODULES mathx.lua pkg/util.lua)
# target_link_libraries(my_app PRIVATE my_lua)
#
# The OBJECT library is used (instead of a static library) so that every module
# translation unit is kept, including the ones only reachable through `require`.
function(add_lua_package target)
cmake_parse_arguments(ARG "" "ROOT;OUTPUT_DIR;NAMESPACE" "MODULES" ${ARGN})
if(NOT ARG_MODULES)
message(FATAL_ERROR "add_lua_package(${target}): MODULES is required")
endif()
if(NOT TARGET luacpp)
message(FATAL_ERROR "add_lua_package(${target}): the 'luacpp' executable target is required")
endif()
if(NOT ARG_ROOT)
set(ARG_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
get_filename_component(_root "${ARG_ROOT}" ABSOLUTE)
if(ARG_OUTPUT_DIR)
get_filename_component(_out "${ARG_OUTPUT_DIR}" ABSOLUTE)
else()
set(_out "${CMAKE_CURRENT_BINARY_DIR}/luacpp_${target}")
endif()
set(_namespace_args "")
if(ARG_NAMESPACE)
set(_namespace_args --namespace "${ARG_NAMESPACE}")
endif()
set(_sources "")
foreach(_module IN LISTS ARG_MODULES)
get_filename_component(_abs "${_module}" ABSOLUTE BASE_DIR "${_root}")
if(NOT EXISTS "${_abs}")
message(FATAL_ERROR "add_lua_package(${target}): module not found: ${_abs}")
endif()
file(RELATIVE_PATH _rel "${_root}" "${_abs}")
string(REGEX REPLACE "\\.lua$" "" _stem "${_rel}")
string(REGEX REPLACE "/init$" "" _stem "${_stem}")
set(_hpp "${_out}/${_stem}.hpp")
set(_cpp "${_out}/${_stem}.cpp")
add_custom_command(
OUTPUT "${_hpp}" "${_cpp}"
COMMAND luacpp "${_abs}" --root "${_root}" --output "${_out}" ${_namespace_args}
DEPENDS "${_abs}" $<TARGET_FILE:luacpp>
COMMENT "luacpp: compiling ${_rel}"
VERBATIM)
list(APPEND _sources "${_cpp}")
endforeach()
add_library(${target} OBJECT ${_sources})
target_include_directories(${target} PUBLIC "${_out}")
target_link_libraries(${target} PUBLIC luacpp::rt)
set_target_properties(${target} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
POSITION_INDEPENDENT_CODE ON)
endfunction()
+753
View File
@@ -0,0 +1,753 @@
// 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
+1259
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
// C++ back end: turns a Lua AST into a .hpp/.cpp pair that rebuilds the module
// on top of the official Lua 5.4 VM.
#pragma once
#include <stdexcept>
#include <string>
#include "frontend.hpp"
namespace lc {
class CompileError : public std::runtime_error {
public:
explicit CompileError(const std::string& msg) : std::runtime_error(msg) {}
};
struct ModuleOptions {
std::string moduleName; // e.g. "pkg.mathx"
std::string headerPath; // path used by the generated #include, e.g. "pkg/mathx.hpp"
std::string cppNamespace; // e.g. "pkg::mathx"
};
struct GeneratedModule {
std::string header;
std::string source;
};
GeneratedModule generate_module(BlockP chunk, const ModuleOptions& options);
} // namespace lc
+919
View File
@@ -0,0 +1,919 @@
#include "frontend.hpp"
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <set>
#include <string>
namespace lc {
namespace {
const std::set<std::string>& keywords() {
static const std::set<std::string> kw = {
"and", "break", "do", "else", "elseif", "end", "false", "for", "function",
"goto", "if", "in", "local", "nil", "not", "or", "repeat", "return",
"then", "true", "until", "while"};
return kw;
}
bool is_name_start(char c) { return std::isalpha(static_cast<unsigned char>(c)) || c == '_'; }
bool is_name_char(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }
void append_utf8(std::string& out, unsigned long cp) {
if (cp < 0x80) {
out += static_cast<char>(cp);
} else if (cp < 0x800) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
}
} // namespace
const char* binop_symbol(BinOp op) {
switch (op) {
case BinOp::Add: return "+";
case BinOp::Sub: return "-";
case BinOp::Mul: return "*";
case BinOp::Div: return "/";
case BinOp::IDiv: return "//";
case BinOp::Mod: return "%";
case BinOp::Pow: return "^";
case BinOp::Concat: return "..";
case BinOp::Eq: return "==";
case BinOp::Ne: return "~=";
case BinOp::Lt: return "<";
case BinOp::Le: return "<=";
case BinOp::Gt: return ">";
case BinOp::Ge: return ">=";
case BinOp::And: return "and";
case BinOp::Or: return "or";
case BinOp::BAnd: return "&";
case BinOp::BOr: return "|";
case BinOp::BXor: return "~";
case BinOp::Shl: return "<<";
case BinOp::Shr: return ">>";
}
return "?";
}
// ---------------------------------------------------------------------------
// Lexer
// ---------------------------------------------------------------------------
Lexer::Lexer(std::string source, std::string chunkname)
: src_(std::move(source)), chunkname_(std::move(chunkname)) {}
void Lexer::fail(const std::string& msg) const {
throw ParseError(msg + " (" + chunkname_ + ")", line_);
}
char Lexer::get() {
char c = src_[pos_++];
if (c == '\n') ++line_;
return c;
}
void Lexer::skip_space_and_comments() {
for (;;) {
while (!eof() && std::isspace(static_cast<unsigned char>(peek()))) get();
if (peek() == '-' && peek(1) == '-') {
get();
get();
if (peek() == '[') {
// maybe a long comment
size_t save = pos_;
int saveLine = line_;
get();
int level = 0;
while (peek() == '=') {
get();
++level;
}
if (peek() == '[') {
get();
make_long_string(level, saveLine); // content discarded
continue;
}
pos_ = save;
line_ = saveLine;
}
while (!eof() && peek() != '\n') get();
continue;
}
return;
}
}
Token Lexer::make_name() {
Token t;
t.line = line_;
size_t start = pos_;
while (!eof() && is_name_char(peek())) get();
t.text = src_.substr(start, pos_ - start);
t.kind = keywords().count(t.text) ? TokKind::Keyword : TokKind::Name;
return t;
}
Token Lexer::make_number() {
Token t;
t.line = line_;
size_t start = pos_;
bool isHex = peek() == '0' && (peek(1) == 'x' || peek(1) == 'X');
if (isHex) {
get();
get();
while (!eof() && (std::isxdigit(static_cast<unsigned char>(peek())) || peek() == '.')) get();
if (peek() == 'p' || peek() == 'P') {
get();
if (peek() == '+' || peek() == '-') get();
while (!eof() && std::isdigit(static_cast<unsigned char>(peek()))) get();
}
} else {
while (!eof() && (std::isdigit(static_cast<unsigned char>(peek())) || peek() == '.')) get();
if (peek() == 'e' || peek() == 'E') {
get();
if (peek() == '+' || peek() == '-') get();
while (!eof() && std::isdigit(static_cast<unsigned char>(peek()))) get();
}
}
t.text = src_.substr(start, pos_ - start);
bool looksFloat = t.text.find('.') != std::string::npos || t.text.find('p') != std::string::npos ||
t.text.find('P') != std::string::npos || t.text.find('e') != std::string::npos ||
t.text.find('E') != std::string::npos;
if (!looksFloat) {
errno = 0;
char* end = nullptr;
long long v = std::strtoll(t.text.c_str(), &end, isHex ? 16 : 10);
if (errno == 0 && end && *end == '\0') {
t.kind = TokKind::Number;
t.isInt = true;
t.ival = v;
return t;
}
}
char* end = nullptr;
double d = std::strtod(t.text.c_str(), &end);
if (!end || *end != '\0') {
fail("malformed number near '" + t.text + "'");
}
t.kind = TokKind::Number;
t.isInt = false;
t.dval = d;
return t;
}
Token Lexer::make_short_string(char quote) {
Token t;
t.line = line_;
get(); // opening quote
std::string out;
for (;;) {
if (eof()) fail("unfinished string");
char c = get();
if (c == quote) break;
if (c == '\n') fail("unfinished string");
if (c != '\\') {
out += c;
continue;
}
if (eof()) fail("unfinished string");
char e = get();
switch (e) {
case 'a': out += '\a'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'v': out += '\v'; break;
case '\\': out += '\\'; break;
case '"': out += '"'; break;
case '\'': out += '\''; break;
case '\n': out += '\n'; break;
case 'x': {
int value = 0, digits = 0;
while (digits < 2 && !eof() && std::isxdigit(static_cast<unsigned char>(peek()))) {
char h = get();
value = value * 16 + (std::isdigit(static_cast<unsigned char>(h)) ? h - '0'
: std::tolower(h) - 'a' + 10);
++digits;
}
if (digits == 0) fail("invalid hexadecimal escape");
out += static_cast<char>(value);
break;
}
case 'z':
while (!eof() && std::isspace(static_cast<unsigned char>(peek()))) get();
break;
case 'u': {
if (peek() != '{') fail("missing '{' in \\u{xxxx}");
get();
unsigned long cp = 0;
int digits = 0;
while (!eof() && peek() != '}') {
char h = get();
if (!std::isxdigit(static_cast<unsigned char>(h))) fail("invalid UTF-8 escape");
cp = cp * 16 + (std::isdigit(static_cast<unsigned char>(h)) ? h - '0'
: std::tolower(h) - 'a' + 10);
++digits;
}
if (eof() || digits == 0) fail("invalid UTF-8 escape");
get(); // '}'
append_utf8(out, cp);
break;
}
default:
if (std::isdigit(static_cast<unsigned char>(e))) {
int value = e - '0', digits = 1;
while (digits < 3 && !eof() && std::isdigit(static_cast<unsigned char>(peek()))) {
value = value * 10 + (get() - '0');
++digits;
}
if (value > 255) fail("decimal escape too large");
out += static_cast<char>(value);
} else {
fail(std::string("invalid escape sequence '\\") + e + "'");
}
}
}
t.kind = TokKind::String;
t.text = out;
return t;
}
Token Lexer::make_long_string(int level, int line) {
Token t;
t.line = line;
std::string out;
for (;;) {
if (eof()) fail("unfinished long string");
if (peek() == ']') {
size_t save = pos_;
int saveLine = line_;
get();
int l = 0;
while (peek() == '=') {
get();
++l;
}
if (peek() == ']' && l == level) {
get();
break;
}
pos_ = save;
line_ = saveLine;
out += get();
continue;
}
out += get();
}
if (!out.empty() && out[0] == '\n') out.erase(out.begin());
t.kind = TokKind::String;
t.text = out;
return t;
}
Token Lexer::next() {
skip_space_and_comments();
if (eof()) {
Token t;
t.kind = TokKind::Eof;
t.line = line_;
return t;
}
char c = peek();
if (is_name_start(c)) return make_name();
if (std::isdigit(static_cast<unsigned char>(c)) || (c == '.' && std::isdigit(static_cast<unsigned char>(peek(1)))))
return make_number();
if (c == '"' || c == '\'') return make_short_string(c);
if (c == '[') {
size_t save = pos_;
int saveLine = line_;
get();
int level = 0;
while (peek() == '=') {
get();
++level;
}
if (peek() == '[') {
get();
return make_long_string(level, saveLine);
}
pos_ = save;
line_ = saveLine;
}
Token t;
t.line = line_;
t.kind = TokKind::Op;
static const char* ops3[] = {"..."};
static const char* ops2[] = {"..", "//", "==", "~=", "<=", ">=", "<<", ">>", "::"};
for (const char* op : ops3) {
if (src_.compare(pos_, 3, op) == 0) {
pos_ += 3;
t.text = op;
return t;
}
}
for (const char* op : ops2) {
if (src_.compare(pos_, 2, op) == 0) {
pos_ += 2;
t.text = op;
return t;
}
}
static const std::string ops1 = "+-*/%^#&~|<>=(){}[];:,.";
if (ops1.find(c) != std::string::npos) {
get();
t.text = std::string(1, c);
return t;
}
fail(std::string("unexpected symbol '") + c + "'");
}
// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------
namespace {
class Parser {
public:
Parser(std::string source, std::string chunkname)
: lex_(std::move(source), std::move(chunkname)) {
cur_ = lex_.next();
}
BlockP parseChunk() {
BlockP b = block();
if (cur_.kind != TokKind::Eof) fail("'<eof>' expected");
return b;
}
private:
// ---- token helpers ----
void advance() {
if (hasAhead_) {
cur_ = ahead_;
hasAhead_ = false;
} else {
cur_ = lex_.next();
}
}
Token peekSecond() {
if (!hasAhead_) {
ahead_ = lex_.next();
hasAhead_ = true;
}
return ahead_;
}
bool is(const char* text) const { return cur_.text == text && cur_.kind != TokKind::String; }
bool isName() const { return cur_.kind == TokKind::Name; }
bool accept(const char* text) {
if (is(text)) {
advance();
return true;
}
return false;
}
void expect(const char* text) {
if (!is(text)) fail(std::string("'") + text + "' expected near '" + cur_.text + "'");
advance();
}
std::string expectName() {
if (!isName()) fail("name expected near '" + cur_.text + "'");
std::string s = cur_.text;
advance();
return s;
}
[[noreturn]] void fail(const std::string& msg) const { throw ParseError(msg, cur_.line); }
bool blockEnd() const {
return cur_.kind == TokKind::Eof || is("end") || is("else") || is("elseif") || is("until");
}
// ---- blocks / statements ----
BlockP block() {
auto b = std::make_unique<Block>();
while (!blockEnd()) {
if (accept(";")) continue;
if (is("return")) {
b->stmts.push_back(returnStat());
accept(";");
break;
}
b->stmts.push_back(statement());
}
return b;
}
StmtP returnStat() {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Return;
s->line = cur_.line;
advance();
if (!blockEnd() && !is(";")) s->values = exprList();
return s;
}
StmtP statement() {
int line = cur_.line;
if (accept(";")) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Expr;
s->line = line;
return s;
}
if (is("if")) return ifStat();
if (is("while")) return whileStat();
if (is("repeat")) return repeatStat();
if (is("do")) {
advance();
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Do;
s->line = line;
s->body = block();
expect("end");
return s;
}
if (is("for")) return forStat();
if (is("function")) return functionStat();
if (is("local")) return localStat();
if (accept("break")) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Break;
s->line = line;
return s;
}
if (accept("goto")) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Goto;
s->line = line;
s->name = expectName();
return s;
}
if (accept("::")) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Label;
s->line = line;
s->name = expectName();
expect("::");
return s;
}
return exprStat();
}
StmtP exprStat() {
int line = cur_.line;
ExprP first = suffixedExpr();
if (first->kind == ExprKind::Call || first->kind == ExprKind::Method) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Expr;
s->line = line;
s->values.push_back(std::move(first));
return s;
}
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Assign;
s->line = line;
s->targets.push_back(std::move(first));
while (accept(",")) s->targets.push_back(suffixedExpr());
expect("=");
s->values = exprList();
return s;
}
StmtP whileStat() {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::While;
s->line = cur_.line;
advance();
s->e1 = expr();
expect("do");
s->body = block();
expect("end");
return s;
}
StmtP repeatStat() {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Repeat;
s->line = cur_.line;
advance();
s->body = block();
expect("until");
s->values.push_back(expr());
return s;
}
StmtP ifStat() {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::If;
s->line = cur_.line;
advance();
for (;;) {
CondBlock cb;
cb.cond = expr();
expect("then");
cb.body = block();
s->conds.push_back(std::move(cb));
if (accept("elseif")) continue;
break;
}
if (accept("else")) s->elseBody = block();
expect("end");
return s;
}
StmtP forStat() {
auto s = std::make_unique<Stmt>();
s->line = cur_.line;
advance();
std::string first = expectName();
if (accept("=")) {
s->kind = StmtKind::NumFor;
s->name = first;
s->cells.assign(1, false);
s->e1 = expr();
expect(",");
s->e2 = expr();
if (accept(",")) s->e3 = expr();
expect("do");
s->body = block();
expect("end");
return s;
}
s->kind = StmtKind::GenFor;
s->names.push_back(first);
s->cells.assign(1, false);
while (accept(",")) {
s->names.push_back(expectName());
s->cells.push_back(false);
}
expect("in");
s->values = exprList();
expect("do");
s->body = block();
expect("end");
return s;
}
StmtP functionStat() {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Assign;
s->line = cur_.line;
advance();
std::string name = expectName();
ExprP target = makeName(name, s->line);
while (accept(".")) {
std::string field = expectName();
target = makeIndex(std::move(target), field, s->line);
}
bool method = false;
if (accept(":")) {
std::string field = expectName();
target = makeIndex(std::move(target), field, s->line);
method = true;
}
ExprP fn = funcBody();
if (method) {
fn->params.insert(fn->params.begin(), "self");
fn->paramCell.insert(fn->paramCell.begin(), false);
}
s->targets.push_back(std::move(target));
s->values.push_back(std::move(fn));
return s;
}
StmtP localStat() {
auto s = std::make_unique<Stmt>();
s->line = cur_.line;
advance();
if (accept("function")) {
s->kind = StmtKind::LocalFunction;
s->name = expectName();
s->cells.assign(1, false);
s->fn = funcBody();
return s;
}
s->kind = StmtKind::Local;
for (;;) {
s->names.push_back(expectName());
if (!accept(",")) break;
}
s->cells.assign(s->names.size(), false);
if (accept("=")) s->values = exprList();
return s;
}
// ---- expressions ----
ExprP funcBody() {
auto fn = std::make_unique<Expr>();
fn->kind = ExprKind::Function;
fn->line = cur_.line;
expect("(");
if (!is(")")) {
for (;;) {
if (accept("...")) {
fn->isVararg = true;
break;
}
fn->params.push_back(expectName());
if (!accept(",")) break;
}
}
expect(")");
fn->paramCell.assign(fn->params.size(), false);
fn->body = block();
expect("end");
return fn;
}
std::vector<ExprP> exprList() {
std::vector<ExprP> list;
list.push_back(expr());
while (accept(",")) list.push_back(expr());
return list;
}
static int binPrec(BinOp op) {
switch (op) {
case BinOp::Or: return 1;
case BinOp::And: return 2;
case BinOp::Lt:
case BinOp::Gt:
case BinOp::Le:
case BinOp::Ge:
case BinOp::Ne:
case BinOp::Eq: return 3;
case BinOp::BOr: return 4;
case BinOp::BXor: return 5;
case BinOp::BAnd: return 6;
case BinOp::Shl:
case BinOp::Shr: return 7;
case BinOp::Concat: return 8;
case BinOp::Add:
case BinOp::Sub: return 9;
case BinOp::Mul:
case BinOp::Div:
case BinOp::IDiv:
case BinOp::Mod: return 10;
case BinOp::Pow: return 12;
}
return 0;
}
static bool rightAssoc(BinOp op) { return op == BinOp::Concat || op == BinOp::Pow; }
bool curBinOp(BinOp& op) const {
if (cur_.kind != TokKind::Op && cur_.kind != TokKind::Keyword) return false;
static const std::pair<const char*, BinOp> table[] = {
{"+", BinOp::Add}, {"-", BinOp::Sub}, {"*", BinOp::Mul}, {"/", BinOp::Div},
{"//", BinOp::IDiv}, {"%", BinOp::Mod}, {"^", BinOp::Pow}, {"..", BinOp::Concat},
{"==", BinOp::Eq}, {"~=", BinOp::Ne}, {"<", BinOp::Lt}, {"<=", BinOp::Le},
{">", BinOp::Gt}, {">=", BinOp::Ge}, {"and", BinOp::And}, {"or", BinOp::Or},
{"&", BinOp::BAnd}, {"|", BinOp::BOr}, {"~", BinOp::BXor}, {"<<", BinOp::Shl},
{">>", BinOp::Shr}};
for (const auto& e : table) {
if (cur_.text == e.first) {
op = e.second;
return true;
}
}
return false;
}
ExprP expr(int limit = 1) {
ExprP left = unaryExpr();
for (;;) {
BinOp op;
if (!curBinOp(op)) break;
int prec = binPrec(op);
if (prec < limit) break;
int line = cur_.line;
advance();
ExprP right = expr(rightAssoc(op) ? prec : prec + 1);
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Bin;
e->line = line;
e->bop = op;
e->a = std::move(left);
e->b = std::move(right);
left = std::move(e);
}
return left;
}
ExprP unaryExpr() {
static const std::pair<const char*, UnOp> table[] = {
{"not", UnOp::Not}, {"-", UnOp::Neg}, {"#", UnOp::Len}, {"~", UnOp::BNot}};
for (const auto& e : table) {
if (is(e.first) && !(cur_.kind == TokKind::Op && e.first[0] == '-' && cur_.text != "-")) {
if (cur_.text == e.first) {
int line = cur_.line;
advance();
auto u = std::make_unique<Expr>();
u->kind = ExprKind::Un;
u->line = line;
u->uop = e.second;
u->a = expr(11);
return u;
}
}
}
return simpleExpr();
}
ExprP simpleExpr() {
int line = cur_.line;
if (cur_.kind == TokKind::Number) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Number;
e->line = line;
e->isInt = cur_.isInt;
e->ival = cur_.ival;
e->dval = cur_.dval;
advance();
return e;
}
if (cur_.kind == TokKind::String) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::String;
e->line = line;
e->str = cur_.text;
advance();
return e;
}
if (accept("nil")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Nil;
e->line = line;
return e;
}
if (accept("true")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::True;
e->line = line;
return e;
}
if (accept("false")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::False;
e->line = line;
return e;
}
if (accept("...")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Vararg;
e->line = line;
return e;
}
if (accept("function")) return funcBody();
if (is("{")) return tableCtor();
return suffixedExpr();
}
ExprP tableCtor() {
auto t = std::make_unique<Expr>();
t->kind = ExprKind::Table;
t->line = cur_.line;
expect("{");
while (!is("}")) {
TableField f;
if (accept("[")) {
f.hasKey = true;
f.key = expr();
expect("]");
expect("=");
f.value = expr();
} else if (isName() && peekSecond().text == "=" && peekSecond().kind == TokKind::Op) {
f.hasKey = true;
f.isName = true;
f.name = cur_.text;
advance(); // name
expect("=");
f.value = expr();
} else {
f.value = expr();
}
t->fields.push_back(std::move(f));
if (!accept(",") && !accept(";")) break;
}
expect("}");
return t;
}
ExprP makeName(const std::string& name, int line) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Name;
e->line = line;
e->str = name;
return e;
}
ExprP makeIndex(ExprP obj, const std::string& field, int line) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Index;
e->line = line;
e->field = field;
e->a = std::move(obj);
return e;
}
std::vector<ExprP> callArgs() {
std::vector<ExprP> args;
if (is("{")) {
args.push_back(tableCtor());
return args;
}
if (cur_.kind == TokKind::String) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::String;
e->line = cur_.line;
e->str = cur_.text;
advance();
args.push_back(std::move(e));
return args;
}
expect("(");
if (!is(")")) args = exprList();
expect(")");
return args;
}
ExprP suffixedExpr() {
ExprP e;
int line = cur_.line;
if (isName()) {
e = makeName(expectName(), line);
} else if (accept("(")) {
auto paren = std::make_unique<Expr>();
paren->kind = ExprKind::Paren;
paren->line = line;
paren->a = expr();
expect(")");
e = std::move(paren);
} else {
fail("unexpected symbol near '" + cur_.text + "'");
}
for (;;) {
if (accept(".")) {
e = makeIndex(std::move(e), expectName(), line);
} else if (accept("[")) {
auto idx = std::make_unique<Expr>();
idx->kind = ExprKind::Index;
idx->line = line;
idx->a = std::move(e);
idx->b = expr();
expect("]");
e = std::move(idx);
} else if (accept(":")) {
auto call = std::make_unique<Expr>();
call->kind = ExprKind::Method;
call->line = line;
call->field = expectName();
call->a = std::move(e);
call->args = callArgs();
e = std::move(call);
} else if (is("(") || is("{") || cur_.kind == TokKind::String) {
auto call = std::make_unique<Expr>();
call->kind = ExprKind::Call;
call->line = line;
call->a = std::move(e);
call->args = callArgs();
e = std::move(call);
} else {
break;
}
}
return e;
}
Lexer lex_;
Token cur_;
Token ahead_;
bool hasAhead_ = false;
};
} // namespace
BlockP parse_chunk(const std::string& source, const std::string& chunkname) {
Parser p(source, chunkname);
return p.parseChunk();
}
} // namespace lc
+188
View File
@@ -0,0 +1,188 @@
// Lua 5.4 lexer + parser producing a small AST used by the C++ back end.
#pragma once
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace lc {
class ParseError : public std::runtime_error {
public:
ParseError(const std::string& msg, int line) : std::runtime_error(format(msg, line)) {}
static std::string format(const std::string& msg, int line) {
return "line " + std::to_string(line) + ": " + msg;
}
};
enum class TokKind { Eof, Name, Number, String, Keyword, Op };
struct Token {
TokKind kind = TokKind::Eof;
std::string text; // name, keyword, operator text, or raw string bytes
int line = 0;
bool isInt = false;
long long ival = 0;
double dval = 0;
};
class Lexer {
public:
Lexer(std::string source, std::string chunkname);
Token next();
private:
bool eof() const { return pos_ >= src_.size(); }
char peek(size_t ahead = 0) const { return pos_ + ahead < src_.size() ? src_[pos_ + ahead] : '\0'; }
char get();
void skip_space_and_comments();
Token make_number();
Token make_short_string(char quote);
Token make_long_string(int level, int line);
Token make_name();
[[noreturn]] void fail(const std::string& msg) const;
std::string src_;
std::string chunkname_;
size_t pos_ = 0;
int line_ = 1;
};
struct Expr;
struct Block;
using ExprP = std::unique_ptr<Expr>;
using BlockP = std::unique_ptr<Block>;
enum class ExprKind {
Nil,
True,
False,
Number,
String,
Vararg,
Name,
Index,
Call,
Method,
Function,
Bin,
Un,
Table,
Paren
};
enum class BinOp {
Add,
Sub,
Mul,
Div,
IDiv,
Mod,
Pow,
Concat,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
And,
Or,
BAnd,
BOr,
BXor,
Shl,
Shr
};
enum class UnOp { Neg, Not, Len, BNot };
struct TableField {
bool hasKey = false;
bool isName = false;
std::string name;
ExprP key;
ExprP value;
};
struct Expr {
ExprKind kind = ExprKind::Nil;
int line = 0;
// literals
bool isInt = false;
long long ival = 0;
double dval = 0;
std::string str; // string bytes, name, field name or method name
// operands / operands of calls
ExprP a, b;
std::string field; // Index: a.field ; Method: a:field(args)
std::vector<ExprP> args;
BinOp bop{};
UnOp uop{};
// function
std::vector<std::string> params;
bool isVararg = false;
bool usesVararg = false;
BlockP body;
std::vector<std::string> upvalues; // filled by the analyser
std::vector<char> paramCell; // filled by the analyser
// table constructor
std::vector<TableField> fields;
};
struct Stmt;
using StmtP = std::unique_ptr<Stmt>;
struct Block {
std::vector<StmtP> stmts;
};
enum class StmtKind {
Expr, // function call statement (values[0])
Assign, // targets = values
Local, // local names = values
LocalFunction, // local function name() ... end
Do,
While, // e1 = condition
Repeat, // values = condition (single expr)
If, // conds + elseBody
NumFor, // name = e1, e2 [, e3]
GenFor, // names in values
Break,
Goto,
Label,
Return
};
struct CondBlock {
ExprP cond;
BlockP body;
};
struct Stmt {
StmtKind kind = StmtKind::Expr;
int line = 0;
std::string name;
std::vector<std::string> names;
std::vector<char> cells; // capture flags, filled by the analyser
std::vector<ExprP> targets;
std::vector<ExprP> values;
ExprP e1, e2, e3;
BlockP body;
std::vector<CondBlock> conds;
BlockP elseBody;
ExprP fn;
};
// Parses a Lua 5.4 chunk. Throws ParseError on invalid input.
BlockP parse_chunk(const std::string& source, const std::string& chunkname);
const char* binop_symbol(BinOp op);
} // namespace lc
+206
View File
@@ -0,0 +1,206 @@
// luacpp: Lua 5.4 -> C++ module compiler (command line front end).
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "codegen.hpp"
#include "frontend.hpp"
namespace fs = std::filesystem;
namespace {
const char* kVersion = "0.1.0";
struct Options {
fs::path root;
fs::path output = "generated";
std::string nsPrefix;
bool quiet = false;
std::vector<std::string> inputs;
};
void usage() {
std::cout <<
"luacpp " << kVersion << " - compile Lua 5.4 modules into C++ packages\n"
"\n"
"Usage: luacpp [options] <file.lua>...\n"
"\n"
"Options:\n"
" -r, --root <dir> root directory used to derive Lua module names\n"
" -o, --output <dir> output directory for the .hpp/.cpp pair (default: generated)\n"
" -n, --namespace <ns> C++ namespace prefix, also prefixes Lua module names\n"
" -q, --quiet do not print generated file names\n"
" -h, --help show this help\n"
" --version show the version\n"
"\n"
"Example:\n"
" luacpp --root lua --namespace demo -o build/gen lua/mathx.lua\n"
" # -> build/gen/mathx.hpp + mathx.cpp, Lua module \"demo.mathx\"\n"
" # C++ namespace demo::mathx\n";
}
std::string read_file(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("cannot open " + path.string());
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
void write_file(const fs::path& path, const std::string& data) {
fs::create_directories(path.parent_path());
std::ofstream out(path, std::ios::binary);
if (!out) throw std::runtime_error("cannot write " + path.string());
out.write(data.data(), static_cast<std::streamsize>(data.size()));
}
std::string cpp_component(const std::string& name) {
std::string out;
for (char c : name) {
unsigned char u = static_cast<unsigned char>(c);
out += (std::isalnum(u) || c == '_') ? c : '_';
}
if (out.empty()) out = "_";
if (std::isdigit(static_cast<unsigned char>(out[0]))) out = "_" + out;
static const char* keywords[] = {"and", "class", "delete", "for", "if", "int", "long", "new",
"not", "or", "private", "public", "return", "static",
"template", "this", "true", "false", "namespace", "using"};
for (const char* kw : keywords) {
if (out == kw) return "_" + out;
}
return out;
}
// "lua/pkg/foo.lua" relative to root "lua" -> "pkg.foo" (init.lua -> "pkg")
std::string derive_module_name(const fs::path& file, const fs::path& root) {
fs::path rel = fs::relative(fs::absolute(file), fs::absolute(root));
std::string stem = rel.generic_string();
if (stem.size() > 4 && stem.compare(stem.size() - 4, 4, ".lua") == 0) stem.erase(stem.size() - 4);
if (stem == "init") return "";
if (stem.size() > 5 && stem.compare(stem.size() - 5, 5, "/init") == 0) stem.erase(stem.size() - 5);
std::replace(stem.begin(), stem.end(), '/', '.');
return stem;
}
std::string join_ns(const std::string& dotted) {
std::string out;
std::string part;
for (char c : dotted) {
if (c == '.') {
if (!part.empty()) {
if (!out.empty()) out += "::";
out += cpp_component(part);
part.clear();
}
} else {
part += c;
}
}
if (!part.empty()) {
if (!out.empty()) out += "::";
out += cpp_component(part);
}
return out;
}
} // namespace
int main(int argc, char** argv) {
Options opt;
bool rootGiven = false;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
auto next = [&](const char* what) -> std::string {
if (i + 1 >= argc) {
std::cerr << "luacpp: missing value for " << what << "\n";
std::exit(2);
}
return argv[++i];
};
if (arg == "-h" || arg == "--help") {
usage();
return 0;
}
if (arg == "--version") {
std::cout << "luacpp " << kVersion << " (Lua 5.4)\n";
return 0;
}
if (arg == "-r" || arg == "--root") {
opt.root = next("--root");
rootGiven = true;
continue;
}
if (arg == "-o" || arg == "--output") {
opt.output = next("--output");
continue;
}
if (arg == "-n" || arg == "--namespace") {
opt.nsPrefix = next("--namespace");
continue;
}
if (arg == "-q" || arg == "--quiet") {
opt.quiet = true;
continue;
}
if (!arg.empty() && arg[0] == '-') {
std::cerr << "luacpp: unknown option '" << arg << "'\n";
return 2;
}
opt.inputs.push_back(arg);
}
if (opt.inputs.empty()) {
usage();
return 2;
}
if (!rootGiven) {
opt.root = fs::path(opt.inputs.front()).parent_path();
if (opt.root.empty()) opt.root = ".";
}
int failures = 0;
for (const std::string& input : opt.inputs) {
fs::path file(input);
try {
std::string module = derive_module_name(file, opt.root);
if (module.empty()) throw std::runtime_error("cannot derive a module name from " + input);
std::string luaName = opt.nsPrefix.empty() ? module : opt.nsPrefix + "." + module;
std::string ns = join_ns(luaName);
fs::path rel = fs::relative(fs::absolute(file), fs::absolute(opt.root));
fs::path stem = rel;
stem.replace_extension();
if (stem.filename() == "init.lua") stem = stem.parent_path().filename();
lc::ModuleOptions mod;
mod.moduleName = luaName;
mod.headerPath = stem.generic_string() + ".hpp";
mod.cppNamespace = ns;
std::string source = read_file(file);
lc::BlockP chunk = lc::parse_chunk(source, file.string());
lc::GeneratedModule gen = lc::generate_module(std::move(chunk), mod);
fs::path hpp = opt.output / (stem.generic_string() + ".hpp");
fs::path cpp = opt.output / (stem.generic_string() + ".cpp");
write_file(hpp, gen.header);
write_file(cpp, gen.source);
if (!opt.quiet) {
std::cout << "luacpp: " << input << " -> " << cpp.generic_string() << " (" << luaName
<< " / " << ns << ")\n";
}
} catch (const std::exception& e) {
std::cerr << "luacpp: " << input << ": " << e.what() << "\n";
++failures;
}
}
return failures == 0 ? 0 : 1;
}