From 517ed0bf4dd62280d3a9469b878e27a5f4f228e9 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Wed, 18 Nov 2026 08:05:41 +0100 Subject: [PATCH] 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. --- CMakeLists.txt | 51 ++ cmake/lua-package.cmake | 70 +++ include/luacpp/rt.hpp | 753 +++++++++++++++++++++++ src/codegen.cpp | 1259 +++++++++++++++++++++++++++++++++++++++ src/codegen.hpp | 30 + src/frontend.cpp | 919 ++++++++++++++++++++++++++++ src/frontend.hpp | 188 ++++++ src/main.cpp | 206 +++++++ 8 files changed, 3476 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 cmake/lua-package.cmake create mode 100644 include/luacpp/rt.hpp create mode 100644 src/codegen.cpp create mode 100644 src/codegen.hpp create mode 100644 src/frontend.cpp create mode 100644 src/frontend.hpp create mode 100644 src/main.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..8f73445 --- /dev/null +++ b/CMakeLists.txt @@ -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() diff --git a/cmake/lua-package.cmake b/cmake/lua-package.cmake new file mode 100644 index 0000000..e6d54fc --- /dev/null +++ b/cmake/lua-package.cmake @@ -0,0 +1,70 @@ +# add_lua_package( +# ROOT # directory the Lua module names are relative to +# MODULES [b.lua ...] +# [OUTPUT_DIR ] # where the .hpp/.cpp files are generated +# [NAMESPACE ]) # C++ namespace prefix, also prefixes Lua module names +# +# Creates an OBJECT library 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}" $ + 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() diff --git a/include/luacpp/rt.hpp b/include/luacpp/rt.hpp new file mode 100644 index 0000000..4adc8ec --- /dev/null +++ b/include/luacpp/rt.hpp @@ -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 + +#if LUA_VERSION_NUM != 504 +#error "luacpp requires Lua 5.4 (LUA_VERSION_NUM == 504)" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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_rawlen(L, slot)); + check_stack(L, static_cast(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_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& module_registry() { + static std::unordered_map 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(v)); } +inline void push_arg(lua_State* L, long long v) { lua_pushinteger(L, static_cast(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(v)); } +inline void push_arg(lua_State* L, float v) { lua_pushnumber(L, static_cast(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(v)) {} + Value(long long v) : kind_(Kind::Integer), int_(static_cast(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(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(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(num_); + } + case Kind::String: { + double d = parse_number(); + if (std::floor(d) != d) throw Error("string has no integer representation"); + return static_cast(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(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(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(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 + Value call(Args&&... args) const { + lua_State* L = require_state(); + int base = lua_gettop(L); + detail::need_stack(L, static_cast(sizeof...(Args)) + 4); + push(L); + (push_arg(L, std::forward(args)), ...); + if (lua_pcall(L, static_cast(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 + std::vector call_multi(Args&&... args) const { + lua_State* L = require_state(); + int base = lua_gettop(L); + detail::need_stack(L, static_cast(sizeof...(Args)) + 4); + push(L); + (push_arg(L, std::forward(args)), ...); + if (lua_pcall(L, static_cast(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 out; + out.reserve(n > 0 ? static_cast(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_; +}; + +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 becomes a Lua array (1-based). +inline void push_arg(lua_State* L, const std::vector& values) { + check_stack(L, static_cast(values.size()) + 1); + lua_createtable(L, static_cast(values.size()), 0); + for (size_t i = 0; i < values.size(); ++i) { + values[i].push(L); + lua_rawseti(L, -2, static_cast(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 + Value call(const std::string& fn, Args&&... args) const { + return get(fn).call(std::forward(args)...); + } + + template + std::vector call_multi(const std::string& fn, Args&&... args) const { + return get(fn).call_multi(std::forward(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 diff --git a/src/codegen.cpp b/src/codegen.cpp new file mode 100644 index 0000000..4ce2ff3 --- /dev/null +++ b/src/codegen.cpp @@ -0,0 +1,1259 @@ +#include "codegen.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace lc { +namespace { + +std::string N(int v) { return std::to_string(v); } + +std::string c_escape(const std::string& s) { + std::string out = "\""; + for (unsigned char c : s) { + if (c == '"' || c == '\\') { + out += '\\'; + out += static_cast(c); + } else if (c >= 32 && c < 127) { + out += static_cast(c); + } else { + char buf[8]; + std::snprintf(buf, sizeof buf, "\\%03o", c); + out += buf; + } + } + out += '"'; + return out; +} + +const std::set& cpp_keywords() { + static const std::set kw = { + "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", + "bitor", "bool", "break", "case", "catch", "char", "char8_t", + "char16_t", "char32_t", "class", "co_await", "co_return", "co_yield", "compl", + "concept", "const", "consteval", "constexpr", "constinit", "const_cast", "continue", + "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", + "enum", "explicit", "export", "extern", "false", "float", "for", + "friend", "goto", "if", "inline", "int", "long", "mutable", + "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", + "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", + "requires", "return", "short", "signed", "sizeof", "static", "static_assert", + "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", + "true", "try", "typedef", "typeid", "typename", "union", "unsigned", + "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", + "xor_eq"}; + return kw; +} + +std::string sanitize_ident(const std::string& name) { + std::string out; + for (char c : name) { + unsigned char u = static_cast(c); + out += (std::isalnum(u) || c == '_') ? c : '_'; + } + if (out.empty()) out = "_"; + if (out[0] >= '0' && out[0] <= '9') out = "_" + out; + if (cpp_keywords().count(out)) out = "_" + out; + return out; +} + +std::string float_literal(double d) { + if (std::isnan(d)) return "(lua_Number)NAN"; + if (std::isinf(d)) return d > 0 ? "(lua_Number)HUGE_VAL" : "(lua_Number)(-HUGE_VAL)"; + char buf[64]; + std::snprintf(buf, sizeof buf, "%a", d); + return std::string("(lua_Number)") + buf; +} + +std::string int_literal(long long v) { + if (v == std::numeric_limits::min()) return "(lua_Integer)LUA_MININTEGER"; + return "(lua_Integer)(" + std::to_string(v) + "LL)"; +} + +// --------------------------------------------------------------------------- +// Analysis: resolves locals/upvalues and marks the locals captured by nested +// functions (they are then boxed in a one-slot table, a "cell"). +// --------------------------------------------------------------------------- + +class Analyzer { +public: + void run_function(Expr& fn) { (void)analyze_fn(fn); } + +private: + struct Local { + std::string name; + char* cell; + }; + using FreeSet = std::vector; + + static void add_unique(FreeSet& set, const std::string& name) { + if (std::find(set.begin(), set.end(), name) == set.end()) set.push_back(name); + } + + static bool has_upvalue(const Expr& fn, const std::string& name) { + return std::find(fn.upvalues.begin(), fn.upvalues.end(), name) != fn.upvalues.end(); + } + + Local* find(const std::string& name) const { + for (size_t i = scopes_.size(); i-- > 0;) { + for (auto it = scopes_[i].rbegin(); it != scopes_[i].rend(); ++it) { + if ((*it)->name == name) return it->get(); + } + } + return nullptr; + } + + Local* find_in_current(const std::string& name) const { + for (size_t i = scopes_.size(); i-- > fn_base_;) { + for (auto it = scopes_[i].rbegin(); it != scopes_[i].rend(); ++it) { + if ((*it)->name == name) return it->get(); + } + } + return nullptr; + } + + void declare(const std::string& name, char* cell) { + scopes_.back().push_back(std::make_unique(Local{name, cell})); + } + + FreeSet analyze_fn(Expr& fn) { + FreeSet free; + size_t savedBase = fn_base_; + Expr* savedCur = cur_; + fn_base_ = scopes_.size(); + cur_ = &fn; + scopes_.push_back({}); + for (size_t i = 0; i < fn.params.size(); ++i) { + declare(fn.params[i], i < fn.paramCell.size() ? &fn.paramCell[i] : nullptr); + } + analyze_block(*fn.body, free); + scopes_.resize(fn_base_); + fn_base_ = savedBase; + cur_ = savedCur; + return free; + } + + void analyze_block(Block& b, FreeSet& free) { + scopes_.push_back({}); + for (auto& s : b.stmts) analyze_stmt(*s, free); + scopes_.pop_back(); + } + + void resolve_nested(Expr& fnExpr, const FreeSet& innerFree, FreeSet& outerFree) { + for (const auto& name : innerFree) { + Local* local = find(name); + if (local) { + if (local->cell) *local->cell = true; + if (!has_upvalue(fnExpr, name)) fnExpr.upvalues.push_back(name); + } else if (cur_ && has_upvalue(*cur_, name)) { + if (!has_upvalue(fnExpr, name)) fnExpr.upvalues.push_back(name); + } else if (cur_) { + add_unique(outerFree, name); + } + } + } + + void analyze_expr(Expr& e, FreeSet& free) { + switch (e.kind) { + case ExprKind::Vararg: + if (cur_) cur_->usesVararg = true; + break; + case ExprKind::Name: + if (cur_ && !find_in_current(e.str) && !has_upvalue(*cur_, e.str)) add_unique(free, e.str); + break; + case ExprKind::Index: + analyze_expr(*e.a, free); + if (e.b) analyze_expr(*e.b, free); + break; + case ExprKind::Call: + case ExprKind::Method: + analyze_expr(*e.a, free); + for (auto& a : e.args) analyze_expr(*a, free); + break; + case ExprKind::Function: { + FreeSet inner = analyze_fn(e); + resolve_nested(e, inner, free); + break; + } + case ExprKind::Bin: + analyze_expr(*e.a, free); + analyze_expr(*e.b, free); + break; + case ExprKind::Un: + case ExprKind::Paren: + analyze_expr(*e.a, free); + break; + case ExprKind::Table: + for (auto& f : e.fields) { + if (f.key) analyze_expr(*f.key, free); + analyze_expr(*f.value, free); + } + break; + default: + break; + } + } + + void analyze_stmt(Stmt& s, FreeSet& free) { + switch (s.kind) { + case StmtKind::Expr: + for (auto& v : s.values) analyze_expr(*v, free); + break; + case StmtKind::Assign: + for (auto& t : s.targets) { + if (t->kind == ExprKind::Index) { + analyze_expr(*t->a, free); + if (t->b) analyze_expr(*t->b, free); + } + } + for (auto& v : s.values) analyze_expr(*v, free); + break; + case StmtKind::Local: + for (auto& v : s.values) analyze_expr(*v, free); + for (size_t i = 0; i < s.names.size(); ++i) { + declare(s.names[i], i < s.cells.size() ? &s.cells[i] : nullptr); + } + break; + case StmtKind::LocalFunction: { + declare(s.name, s.cells.empty() ? nullptr : &s.cells[0]); + FreeSet inner = analyze_fn(*s.fn); + resolve_nested(*s.fn, inner, free); + break; + } + case StmtKind::Do: + analyze_block(*s.body, free); + break; + case StmtKind::While: + analyze_expr(*s.e1, free); + analyze_block(*s.body, free); + break; + case StmtKind::Repeat: + scopes_.push_back({}); + for (auto& st : s.body->stmts) analyze_stmt(*st, free); + analyze_expr(*s.values[0], free); + scopes_.pop_back(); + break; + case StmtKind::If: + for (auto& cb : s.conds) { + analyze_expr(*cb.cond, free); + analyze_block(*cb.body, free); + } + if (s.elseBody) analyze_block(*s.elseBody, free); + break; + case StmtKind::NumFor: + analyze_expr(*s.e1, free); + analyze_expr(*s.e2, free); + if (s.e3) analyze_expr(*s.e3, free); + scopes_.push_back({}); + declare(s.name, s.cells.empty() ? nullptr : &s.cells[0]); + analyze_block(*s.body, free); + scopes_.pop_back(); + break; + case StmtKind::GenFor: + for (auto& v : s.values) analyze_expr(*v, free); + scopes_.push_back({}); + for (size_t i = 0; i < s.names.size(); ++i) { + declare(s.names[i], i < s.cells.size() ? &s.cells[i] : nullptr); + } + analyze_block(*s.body, free); + scopes_.pop_back(); + break; + case StmtKind::Return: + for (auto& v : s.values) analyze_expr(*v, free); + break; + default: + break; + } + } + + std::vector>> scopes_; + Expr* cur_ = nullptr; + size_t fn_base_ = 0; +}; + +// --------------------------------------------------------------------------- +// Code generation +// --------------------------------------------------------------------------- + +class Gen { +public: + explicit Gen(ModuleOptions options) : options_(std::move(options)) {} + + GeneratedModule run(BlockP chunk) { + Expr chunkFn; + chunkFn.kind = ExprKind::Function; + chunkFn.isVararg = true; + chunkFn.body = std::move(chunk); + + Analyzer analyzer; + analyzer.run_function(chunkFn); + + int chunkId = next_id_++; + std::string chunkDef = function_def(chunkFn, chunkId); + functions_.push_back(chunkDef); + chunk_fn_id_ = chunkId; + + collect_facades(*chunkFn.body); + + GeneratedModule out; + out.header = header_text(); + out.source = source_text(); + return out; + } + +private: + enum ResKind { R_LOCAL, R_LOCAL_CELL, R_UPVAL, R_GLOBAL }; + enum TargetKind { T_LOCAL, T_LOCAL_CELL, T_UPVAL, T_GLOBAL, T_FIELD, T_INDEX }; + + struct Res { + ResKind kind; + int slot; + std::string name; + }; + + struct Target { + TargetKind kind; + int slot = 0; + int key = 0; + std::string name; + }; + + struct LocalVar { + std::string name; + int slot; + bool cell; + }; + + struct LoopCtx { + std::string brk; + int level; + }; + + struct LabelInfo { + std::string cpp; + std::string placeholder; + int level = -1; + }; + + struct FnCtx { + const Expr* fn = nullptr; + std::vector> scopes; + int top = 0; + int maxTop = 0; + int vargSlot = 0; + std::vector loops; + std::map labels; + std::string prologue; + std::string body; + }; + + struct Facade { + std::string luaName; + std::string cppName; + bool vararg = false; + int nparams = 0; + }; + + // ---- output helpers ---- + FnCtx& cur() { return stack_.back(); } + const FnCtx& cur() const { return stack_.back(); } + + void emit(const std::string& line) { cur().body += " " + line + "\n"; } + + void set_top(int t) { + cur().top = t; + if (t > cur().maxTop) cur().maxTop = t; + } + + void bump(int n) { set_top(cur().top + n); } + + std::string new_label() { return "lc_L" + N(label_counter_++); } + + std::string placeholder(int id) { return "@@LVL" + N(id) + "@@"; } + + // ---- name resolution ---- + Res resolve(const std::string& name) const { + const FnCtx& c = cur(); + for (size_t i = c.scopes.size(); i-- > 0;) { + for (auto it = c.scopes[i].rbegin(); it != c.scopes[i].rend(); ++it) { + if (it->name == name) return {it->cell ? R_LOCAL_CELL : R_LOCAL, it->slot, name}; + } + } + if (c.fn) { + for (size_t i = 0; i < c.fn->upvalues.size(); ++i) { + if (c.fn->upvalues[i] == name) return {R_UPVAL, static_cast(i) + 1, name}; + } + } + return {R_GLOBAL, 0, name}; + } + + void declare(const std::string& name, int slot, bool cell) { + cur().scopes.back().push_back(LocalVar{name, slot, cell}); + } + + // ---- expressions ---- + static bool is_multi(const Expr& e) { + return e.kind == ExprKind::Call || e.kind == ExprKind::Method || e.kind == ExprKind::Vararg; + } + + void push_name(const std::string& name) { + Res r = resolve(name); + switch (r.kind) { + case R_LOCAL: + emit("lua_pushvalue(L, " + N(r.slot) + ");"); + break; + case R_LOCAL_CELL: + emit("lua_rawgeti(L, " + N(r.slot) + ", 1);"); + break; + case R_UPVAL: + emit("lua_rawgeti(L, lua_upvalueindex(" + N(r.slot) + "), 1);"); + break; + case R_GLOBAL: + emit("lua_getglobal(L, " + c_escape(name) + ");"); + break; + } + bump(1); + } + + void push_upvalue_source(const std::string& name) { + Res r = resolve(name); + if (r.kind == R_LOCAL_CELL) { + emit("lua_pushvalue(L, " + N(r.slot) + ");"); + } else if (r.kind == R_UPVAL) { + emit("lua_pushvalue(L, lua_upvalueindex(" + N(r.slot) + "));"); + } else { + throw CompileError("internal error: upvalue '" + name + "' is not a captured local"); + } + bump(1); + } + + void store(const Target& t, int valueIndex) { + const std::string vi = N(valueIndex); + switch (t.kind) { + case T_LOCAL: + emit("lua_copy(L, " + vi + ", " + N(t.slot) + ");"); + break; + case T_LOCAL_CELL: + emit("lua_pushvalue(L, " + vi + ");"); + emit("lua_rawseti(L, " + N(t.slot) + ", 1);"); + break; + case T_UPVAL: + emit("lua_pushvalue(L, " + vi + ");"); + emit("lua_rawseti(L, lua_upvalueindex(" + N(t.slot) + "), 1);"); + break; + case T_GLOBAL: + emit("lua_pushvalue(L, " + vi + ");"); + emit("lua_setglobal(L, " + c_escape(t.name) + ");"); + break; + case T_FIELD: + emit("lua_pushvalue(L, " + vi + ");"); + emit("lua_setfield(L, " + N(t.slot) + ", " + c_escape(t.name) + ");"); + break; + case T_INDEX: + emit("lua_pushvalue(L, " + N(t.key) + ");"); + emit("lua_pushvalue(L, " + vi + ");"); + emit("lua_settable(L, " + N(t.slot) + ");"); + break; + } + } + + void expr_list(const std::vector& exprs, int want) { + int base = cur().top; + for (size_t i = 0; i < exprs.size(); ++i) { + bool last = i + 1 == exprs.size(); + if (last && is_multi(*exprs[i])) { + multi_raw(*exprs[i]); + } else { + expr(*exprs[i]); + } + } + emit("luacpp::adjust(L, " + N(base) + ", " + N(want) + ");"); + set_top(base + want); + } + + void multi_raw(Expr& e) { + if (e.kind == ExprKind::Vararg) { + if (cur().vargSlot == 0) throw CompileError("cannot use '...' outside a vararg function"); + emit("luacpp::push_varargs(L, " + N(cur().vargSlot) + ");"); + return; + } + call_expr(e, LUA_MULTRET); + } + + void call_expr(Expr& e, int nres) { + int fslot = cur().top + 1; + emit("luacpp::check_stack(L, " + N(static_cast(e.args.size()) + 8) + ");"); + if (e.kind == ExprKind::Method) { + expr(*e.a); + emit("lua_pushvalue(L, " + N(fslot) + ");"); + bump(1); + emit("lua_getfield(L, " + N(fslot + 1) + ", " + c_escape(e.field) + ");"); + bump(1); + emit("lua_remove(L, " + N(fslot + 1) + ");"); + set_top(fslot + 1); + emit("lua_insert(L, " + N(fslot) + ");"); + } else { + expr(*e.a); + } + for (size_t i = 0; i < e.args.size(); ++i) { + bool last = i + 1 == e.args.size(); + if (last && is_multi(*e.args[i])) { + multi_raw(*e.args[i]); + } else { + expr(*e.args[i]); + } + } + std::string results = nres == LUA_MULTRET ? "LUA_MULTRET" : N(nres); + emit("lua_call(L, lua_gettop(L) - " + N(fslot) + ", " + results + ");"); + if (nres == LUA_MULTRET) { + set_top(fslot); + } else { + set_top(fslot - 1 + nres); + } + } + + void expr(Expr& e) { + switch (e.kind) { + case ExprKind::Nil: + emit("lua_pushnil(L);"); + bump(1); + break; + case ExprKind::True: + emit("lua_pushboolean(L, 1);"); + bump(1); + break; + case ExprKind::False: + emit("lua_pushboolean(L, 0);"); + bump(1); + break; + case ExprKind::Number: + if (e.isInt) { + emit("lua_pushinteger(L, " + int_literal(e.ival) + ");"); + } else { + emit("lua_pushnumber(L, " + float_literal(e.dval) + ");"); + } + bump(1); + break; + case ExprKind::String: + emit("lua_pushlstring(L, " + c_escape(e.str) + ", " + N(static_cast(e.str.size())) + ");"); + bump(1); + break; + case ExprKind::Vararg: + if (cur().vargSlot == 0) throw CompileError("cannot use '...' outside a vararg function"); + emit("lua_rawgeti(L, " + N(cur().vargSlot) + ", 1);"); + bump(1); + break; + case ExprKind::Name: + push_name(e.str); + break; + case ExprKind::Index: { + expr(*e.a); + int a = cur().top; + if (!e.field.empty()) { + emit("lua_getfield(L, " + N(a) + ", " + c_escape(e.field) + ");"); + bump(1); + } else { + expr(*e.b); + emit("lua_gettable(L, " + N(a) + ");"); + set_top(a + 1); + } + emit("lua_remove(L, " + N(a) + ");"); + set_top(a); + break; + } + case ExprKind::Call: + case ExprKind::Method: + call_expr(e, 1); + break; + case ExprKind::Function: + closure(e); + break; + case ExprKind::Bin: + binary(e); + break; + case ExprKind::Un: + unary(e); + break; + case ExprKind::Table: + table_ctor(e); + break; + case ExprKind::Paren: + expr(*e.a); + break; + } + } + + void binary(Expr& e) { + if (e.bop == BinOp::And || e.bop == BinOp::Or) { + expr(*e.a); + int a = cur().top; + emit(e.bop == BinOp::And ? "if (lua_toboolean(L, " + N(a) + ")) {" + : "if (!lua_toboolean(L, " + N(a) + ")) {"); + emit(" lua_pop(L, 1);"); + set_top(a - 1); + expr(*e.b); + cur().body += "}\n"; + set_top(a); + return; + } + expr(*e.a); + expr(*e.b); + int a = cur().top - 1; + switch (e.bop) { + case BinOp::Add: emit("lua_arith(L, LUA_OPADD);"); set_top(a); return; + case BinOp::Sub: emit("lua_arith(L, LUA_OPSUB);"); set_top(a); return; + case BinOp::Mul: emit("lua_arith(L, LUA_OPMUL);"); set_top(a); return; + case BinOp::Div: emit("lua_arith(L, LUA_OPDIV);"); set_top(a); return; + case BinOp::IDiv: emit("lua_arith(L, LUA_OPIDIV);"); set_top(a); return; + case BinOp::Mod: emit("lua_arith(L, LUA_OPMOD);"); set_top(a); return; + case BinOp::Pow: emit("lua_arith(L, LUA_OPPOW);"); set_top(a); return; + case BinOp::BAnd: emit("lua_arith(L, LUA_OPBAND);"); set_top(a); return; + case BinOp::BOr: emit("lua_arith(L, LUA_OPBOR);"); set_top(a); return; + case BinOp::BXor: emit("lua_arith(L, LUA_OPBXOR);"); set_top(a); return; + case BinOp::Shl: emit("lua_arith(L, LUA_OPSHL);"); set_top(a); return; + case BinOp::Shr: emit("lua_arith(L, LUA_OPSHR);"); set_top(a); return; + case BinOp::Concat: emit("lua_concat(L, 2);"); set_top(a); return; + case BinOp::Eq: + case BinOp::Ne: + case BinOp::Lt: + case BinOp::Le: + case BinOp::Gt: + case BinOp::Ge: { + const char* op = "LUA_OPEQ"; + bool negate = false; + switch (e.bop) { + case BinOp::Eq: op = "LUA_OPEQ"; break; + case BinOp::Ne: op = "LUA_OPEQ"; negate = true; break; + case BinOp::Lt: op = "LUA_OPLT"; break; + case BinOp::Le: op = "LUA_OPLE"; break; + case BinOp::Gt: op = "LUA_OPLT"; break; // b < a + case BinOp::Ge: op = "LUA_OPLE"; break; // b <= a + default: break; + } + bool swapped = e.bop == BinOp::Gt || e.bop == BinOp::Ge; + int left = a; // index of the left operand + std::string lhs = N(swapped ? left + 1 : left); + std::string rhs = N(swapped ? left : left + 1); + std::string call = "lua_compare(L, " + lhs + ", " + rhs + ", " + op + ")"; + emit(std::string("lua_pushboolean(L, ") + (negate ? "!" : "") + call + ");"); + bump(1); + emit("lua_remove(L, " + N(left) + ");"); + set_top(left + 1); + emit("lua_remove(L, " + N(left) + ");"); + set_top(left); + return; + } + default: + break; + } + } + + void unary(Expr& e) { + expr(*e.a); + int a = cur().top; + switch (e.uop) { + case UnOp::Neg: emit("lua_arith(L, LUA_OPUNM);"); break; + case UnOp::BNot: emit("lua_arith(L, LUA_OPBNOT);"); break; + case UnOp::Not: + emit("lua_pushboolean(L, !lua_toboolean(L, " + N(a) + "));"); + bump(1); + emit("lua_remove(L, " + N(a) + ");"); + set_top(a); + break; + case UnOp::Len: + emit("lua_len(L, " + N(a) + ");"); + bump(1); + emit("lua_remove(L, " + N(a) + ");"); + set_top(a); + break; + } + } + + void table_ctor(Expr& e) { + int positional = 0; + int keyed = 0; + for (auto& f : e.fields) (f.hasKey ? keyed : positional)++; + int t = cur().top + 1; + emit("lua_createtable(L, " + N(positional) + ", " + N(keyed) + ");"); + bump(1); + int arrayIndex = 0; + for (size_t i = 0; i < e.fields.size(); ++i) { + TableField& f = e.fields[i]; + if (!f.hasKey) { + bool last = i + 1 == e.fields.size(); + if (last && is_multi(*f.value)) { + multi_raw(*f.value); + emit("luacpp::append_all(L, " + N(t) + ");"); + set_top(t); + continue; + } + expr(*f.value); + emit("lua_rawseti(L, " + N(t) + ", " + N(++arrayIndex) + ");"); + set_top(t); + } else if (f.isName) { + expr(*f.value); + emit("lua_setfield(L, " + N(t) + ", " + c_escape(f.name) + ");"); + set_top(t); + } else { + expr(*f.key); + expr(*f.value); + emit("lua_settable(L, " + N(t) + ");"); + set_top(t); + } + } + } + + void closure(Expr& fn) { + int id = next_id_++; + int nup = static_cast(fn.upvalues.size()); + int before = cur().top; + for (auto& name : fn.upvalues) push_upvalue_source(name); + emit("lua_pushcclosure(L, lc_fn_" + N(id) + ", " + N(nup) + ");"); + set_top(before + 1); + functions_.push_back(function_def(fn, id)); + } + + std::string fn_prologue(Expr& fn) { + std::string s; + int np = static_cast(fn.params.size()); + bool usesVararg = fn.isVararg && fn.usesVararg; + if (fn.usesVararg && !fn.isVararg) { + throw CompileError("cannot use '...' outside a vararg function"); + } + if (usesVararg) { + cur().vargSlot = np + 1; + s += " luacpp::pack_varargs(L, " + N(np) + ", " + N(np + 1) + ");\n"; + cur().top = np + 1; + } else { + s += " lua_settop(L, " + N(np) + ");\n"; + cur().top = np; + } + for (int i = 1; i <= np; ++i) { + if (i - 1 < static_cast(fn.paramCell.size()) && fn.paramCell[i - 1]) { + s += " lua_createtable(L, 1, 0);\n"; + s += " lua_pushvalue(L, " + N(i) + ");\n"; + s += " lua_rawseti(L, -2, 1);\n"; + s += " lua_replace(L, " + N(i) + ");\n"; + } + } + cur().maxTop = cur().top; + return s; + } + + std::string function_def(Expr& fn, int id) { + FnCtx ctx; + ctx.fn = &fn; + stack_.push_back(std::move(ctx)); + + std::string fnPrologue = fn_prologue(fn); + collect_labels(*fn.body); + cur().scopes.push_back({}); + for (size_t i = 0; i < fn.params.size(); ++i) { + declare(fn.params[i], static_cast(i) + 1, + i < fn.paramCell.size() && fn.paramCell[i] != 0); + } + block(*fn.body); + cur().scopes.pop_back(); + + std::string body = cur().body; + int maxTop = cur().maxTop; + + // Resolve label placeholders now that every level is known. + for (auto& entry : cur().labels) { + const LabelInfo& info = entry.second; + if (info.level < 0) throw CompileError("no visible label '" + entry.first + "' for goto"); + std::string token = info.placeholder; + std::string value = N(info.level); + size_t pos = 0; + while ((pos = body.find(token, pos)) != std::string::npos) { + body.replace(pos, token.size(), value); + pos += value.size(); + } + } + + stack_.pop_back(); + + std::string text; + text += "static int lc_fn_" + N(id) + "(lua_State* L) {\n"; + text += " luacpp::check_stack(L, " + N(maxTop + 16) + ");\n"; + text += fnPrologue; + text += body; + text += " return 0;\n}\n"; + return text; + } + + // ---- labels ---- + void collect_labels(Block& b) { + for (auto& s : b.stmts) { + switch (s->kind) { + case StmtKind::Label: { + LabelInfo info; + info.cpp = "lc_user_" + N(label_counter_++); + info.placeholder = placeholder(label_counter_++); + cur().labels[s->name] = info; + break; + } + case StmtKind::Do: + case StmtKind::While: + case StmtKind::Repeat: + collect_labels(*s->body); + break; + case StmtKind::If: + for (auto& cb : s->conds) collect_labels(*cb.body); + if (s->elseBody) collect_labels(*s->elseBody); + break; + case StmtKind::NumFor: + case StmtKind::GenFor: + collect_labels(*s->body); + break; + default: + break; + } + } + } + + // ---- statements ---- + void block(Block& b) { + int base = cur().top; + cur().scopes.push_back({}); + for (auto& s : b.stmts) stmt(*s); + cur().scopes.pop_back(); + if (cur().top != base) { + emit("lua_settop(L, " + N(base) + ");"); + set_top(base); + } + } + + void stmt(Stmt& s) { + switch (s.kind) { + case StmtKind::Expr: { + if (s.values.empty()) return; + int base = cur().top; + call_expr(*s.values[0], 0); + set_top(base); + emit("lua_settop(L, " + N(base) + ");"); + return; + } + case StmtKind::Assign: + assign(s); + return; + case StmtKind::Local: + local_decl(s); + return; + case StmtKind::LocalFunction: + local_function(s); + return; + case StmtKind::Do: + block(*s.body); + return; + case StmtKind::While: + while_stmt(s); + return; + case StmtKind::Repeat: + repeat_stmt(s); + return; + case StmtKind::If: + if_stmt(s); + return; + case StmtKind::NumFor: + num_for(s); + return; + case StmtKind::GenFor: + gen_for(s); + return; + case StmtKind::Break: { + if (cur().loops.empty()) throw CompileError("break outside a loop"); + const LoopCtx& l = cur().loops.back(); + emit("lua_settop(L, " + N(l.level) + ");"); + emit("goto " + l.brk + ";"); + set_top(l.level); + return; + } + case StmtKind::Goto: { + auto it = cur().labels.find(s.name); + if (it == cur().labels.end()) throw CompileError("no visible label '" + s.name + "' for goto"); + emit("lua_settop(L, " + it->second.placeholder + ");"); + emit("goto " + it->second.cpp + ";"); + return; + } + case StmtKind::Label: { + auto it = cur().labels.find(s.name); + if (it == cur().labels.end()) return; + it->second.level = cur().top; + cur().body += it->second.cpp + ":;\n"; + return; + } + case StmtKind::Return: + return_stmt(s); + return; + } + } + + void assign(Stmt& s) { + int base = cur().top; + int n = static_cast(s.targets.size()); + std::vector targets; + targets.reserve(n); + for (auto& t : s.targets) { + Target target; + if (t->kind == ExprKind::Name) { + Res r = resolve(t->str); + switch (r.kind) { + case R_LOCAL: target.kind = T_LOCAL; break; + case R_LOCAL_CELL: target.kind = T_LOCAL_CELL; break; + case R_UPVAL: target.kind = T_UPVAL; break; + default: target.kind = T_GLOBAL; break; + } + target.slot = r.slot; + target.name = t->str; + } else if (t->kind == ExprKind::Index) { + target.slot = cur().top + 1; + expr(*t->a); + if (!t->field.empty()) { + target.kind = T_FIELD; + target.name = t->field; + } else { + target.kind = T_INDEX; + target.key = cur().top + 1; + expr(*t->b); + } + } else { + throw CompileError("cannot assign to this expression"); + } + targets.push_back(target); + } + int vstart = cur().top + 1; + expr_list(s.values, n); + for (int i = 0; i < n; ++i) store(targets[i], vstart + i); + set_top(base); + emit("lua_settop(L, " + N(base) + ");"); + } + + void local_decl(Stmt& s) { + int n = static_cast(s.names.size()); + int base = cur().top; + if (s.values.empty()) { + for (int i = 0; i < n; ++i) { + if (s.cells[i]) { + emit("lua_createtable(L, 0, 0);"); + } else { + emit("lua_pushnil(L);"); + } + bump(1); + } + } else { + expr_list(s.values, n); + for (int i = 0; i < n; ++i) { + if (!s.cells[i]) continue; + int slot = base + 1 + i; + emit("lua_createtable(L, 1, 0);"); + emit("lua_pushvalue(L, " + N(slot) + ");"); + emit("lua_rawseti(L, -2, 1);"); + emit("lua_replace(L, " + N(slot) + ");"); + } + } + for (int i = 0; i < n; ++i) declare(s.names[i], base + 1 + i, s.cells[i]); + set_top(base + n); + } + + void local_function(Stmt& s) { + int slot = cur().top + 1; + bool cell = !s.cells.empty() && s.cells[0]; + if (cell) { + emit("lua_createtable(L, 0, 0);"); + bump(1); + } + declare(s.name, slot, cell); + int id = next_id_++; + int nup = static_cast(s.fn->upvalues.size()); + for (auto& name : s.fn->upvalues) push_upvalue_source(name); + emit("lua_pushcclosure(L, lc_fn_" + N(id) + ", " + N(nup) + ");"); + if (cell) { + emit("lua_rawseti(L, " + N(slot) + ", 1);"); + } + set_top(slot); + functions_.push_back(function_def(*s.fn, id)); + } + + void if_stmt(Stmt& s) { + int base = cur().top; + std::string lend = new_label(); + std::string lelse = new_label(); + int n = static_cast(s.conds.size()); + for (int i = 0; i < n; ++i) { + CondBlock& cb = s.conds[i]; + expr(*cb.cond); + std::string next = (i + 1 < n) ? new_label() : lelse; + emit("if (!luacpp::pop_bool(L)) goto " + next + ";"); + set_top(base); + block(*cb.body); + emit("goto " + lend + ";"); + if (i + 1 < n) cur().body += next + ":;\n"; + } + cur().body += lelse + ":;\n"; + if (s.elseBody) block(*s.elseBody); + cur().body += lend + ":;\n"; + set_top(base); + } + + void while_stmt(Stmt& s) { + int entry = cur().top; + std::string lcond = new_label(); + std::string lend = new_label(); + cur().body += lcond + ":;\n"; + expr(*s.e1); + emit("if (!luacpp::pop_bool(L)) goto " + lend + ";"); + set_top(entry); + cur().loops.push_back({lend, entry}); + block(*s.body); + cur().loops.pop_back(); + emit("goto " + lcond + ";"); + cur().body += lend + ":;\n"; + set_top(entry); + } + + void repeat_stmt(Stmt& s) { + int entry = cur().top; + std::string lstart = new_label(); + std::string lend = new_label(); + cur().body += lstart + ":;\n"; + cur().scopes.push_back({}); + cur().loops.push_back({lend, entry}); + for (auto& st : s.body->stmts) stmt(*st); + int before = cur().top; + expr(*s.values[0]); + emit("if (!lua_toboolean(L, " + N(before + 1) + ")) { lua_settop(L, " + N(entry) + "); goto " + lstart + + "; }"); + emit("lua_pop(L, 1);"); + set_top(before); + cur().loops.pop_back(); + cur().scopes.pop_back(); + emit("lua_settop(L, " + N(entry) + ");"); + set_top(entry); + cur().body += lend + ":;\n"; + } + + void num_for(Stmt& s) { + int entry = cur().top; + int idx = entry + 1; + int lim = entry + 2; + int stp = entry + 3; + int var = entry + 4; + expr(*s.e1); + expr(*s.e2); + if (s.e3) { + expr(*s.e3); + } else { + emit("lua_pushinteger(L, 1);"); + bump(1); + } + emit("lua_pushvalue(L, " + N(idx) + ");"); + bump(1); + set_top(var); + std::string lloop = new_label(); + std::string lend = new_label(); + emit("if (!luacpp::numeric_for_prep(L, " + N(idx) + ", " + N(lim) + ", " + N(stp) + ")) goto " + lend + + ";"); + cur().body += lloop + ":;\n"; + emit("lua_copy(L, " + N(idx) + ", " + N(var) + ");"); + cur().scopes.push_back({}); + declare(s.name, var, !s.cells.empty() && s.cells[0]); + cur().loops.push_back({lend, entry}); + block(*s.body); + cur().loops.pop_back(); + cur().scopes.pop_back(); + set_top(var); + emit("if (!luacpp::numeric_for_next(L, " + N(idx) + ", " + N(lim) + ", " + N(stp) + ")) goto " + lend + + ";"); + emit("goto " + lloop + ";"); + cur().body += lend + ":;\n"; + emit("lua_settop(L, " + N(entry) + ");"); + set_top(entry); + } + + void gen_for(Stmt& s) { + int entry = cur().top; + int f = entry + 1; + int state = entry + 2; + int ctl = entry + 3; + int nvars = static_cast(s.names.size()); + int vars = entry + 4; + expr_list(s.values, 3); + for (int i = 0; i < nvars; ++i) { + emit("lua_pushnil(L);"); + bump(1); + } + set_top(vars + nvars - 1); + std::string lloop = new_label(); + std::string lend = new_label(); + std::string call = "luacpp::generic_next(L, " + N(f) + ", " + N(state) + ", " + N(ctl) + ", " + N(vars) + + ", " + N(nvars) + ")"; + emit("if (!" + call + ") goto " + lend + ";"); + cur().body += lloop + ":;\n"; + cur().scopes.push_back({}); + for (int i = 0; i < nvars; ++i) { + declare(s.names[i], vars + i, i < static_cast(s.cells.size()) && s.cells[i]); + } + cur().loops.push_back({lend, entry}); + block(*s.body); + cur().loops.pop_back(); + cur().scopes.pop_back(); + set_top(vars + nvars - 1); + emit("if (!" + call + ") goto " + lend + ";"); + emit("goto " + lloop + ";"); + cur().body += lend + ":;\n"; + emit("lua_settop(L, " + N(entry) + ");"); + set_top(entry); + } + + void return_stmt(Stmt& s) { + int base = cur().top; + size_t n = s.values.size(); + for (size_t i = 0; i < n; ++i) { + bool last = i + 1 == n; + if (last && is_multi(*s.values[i])) { + multi_raw(*s.values[i]); + } else { + expr(*s.values[i]); + } + } + emit("return lua_gettop(L) - " + N(base) + ";"); + } + + // ---- exported function facades ---- + void collect_facades(Block& body) { + std::set seen; + for (auto& s : body.stmts) { + if (s->kind != StmtKind::Assign) continue; + if (s->targets.size() != 1 || s->values.size() != 1) continue; + Expr& target = *s->targets[0]; + Expr& value = *s->values[0]; + if (value.kind != ExprKind::Function) continue; + std::string name; + if (target.kind == ExprKind::Name) { + name = target.str; + } else if (target.kind == ExprKind::Index && !target.field.empty()) { + name = target.field; + } else { + continue; + } + if (name.empty() || seen.count(name)) continue; + seen.insert(name); + Facade f; + f.luaName = name; + f.cppName = sanitize_ident(name); + f.vararg = value.isVararg; + f.nparams = static_cast(value.params.size()); + facades_.push_back(std::move(f)); + } + } + + // ---- file assembly ---- + std::string header_text() const { + std::string h; + h += "// Generated by luacpp from Lua module '" + options_.moduleName + "'. Do not edit.\n"; + h += "#pragma once\n\n"; + h += "#include \n\n"; + h += "#include \n\n"; + h += "namespace " + options_.cppNamespace + " {\n\n"; + h += "inline constexpr const char* kModuleName = " + c_escape(options_.moduleName) + ";\n\n"; + h += "// Runs the compiled module chunk and pushes the value it exports.\n"; + h += "void open(lua_State* L);\n\n"; + h += "// Returns the module table bound to a Lua state (runs `require`).\n"; + h += "inline luacpp::Module module(luacpp::State& state) {\n"; + h += " return state.module(kModuleName);\n"; + h += "}\n\n"; + if (!facades_.empty()) { + h += "// Typed-ish facade generated from the functions the chunk exports.\n"; + h += "// Values stay dynamically typed (luacpp::Value); the names and arities are C++.\n"; + h += "class api {\n"; + h += "public:\n"; + h += " explicit api(luacpp::Module mod) : mod_(std::move(mod)) {}\n\n"; + h += " luacpp::Module& raw() { return mod_; }\n"; + h += " const luacpp::Module& raw() const { return mod_; }\n\n"; + for (auto& f : facades_) { + if (f.vararg) { + h += " template \n"; + h += " luacpp::Value " + f.cppName + "(Args&&... args) const {\n"; + h += " return mod_.call(" + c_escape(f.luaName) + ", std::forward(args)...);\n"; + h += " }\n\n"; + continue; + } + h += " luacpp::Value " + f.cppName + "("; + for (int i = 0; i < f.nparams; ++i) { + if (i) h += ", "; + h += "luacpp::Value a" + N(i); + } + h += ") const {\n"; + h += " return mod_.call(" + c_escape(f.luaName); + for (int i = 0; i < f.nparams; ++i) h += ", std::move(a" + N(i) + ")"; + h += ");\n }\n\n"; + } + h += "private:\n"; + h += " luacpp::Module mod_;\n"; + h += "};\n\n"; + h += "inline api bind(luacpp::State& state) { return api(module(state)); }\n"; + } + h += "\n} // namespace " + options_.cppNamespace + "\n"; + return h; + } + + std::string source_text() const { + std::string s; + s += "// Generated by luacpp from Lua module '" + options_.moduleName + "'. Do not edit.\n"; + s += "#include \"" + options_.headerPath + "\"\n\n"; + s += "#include \n\n"; + s += "namespace " + options_.cppNamespace + " {\n\n"; + s += "namespace {\n\n"; + for (auto& def : functions_) { + s += def; + s += "\n"; + } + s += "} // namespace\n\n"; + s += "void open(lua_State* L) {\n"; + s += " lua_pushcfunction(L, lc_fn_" + N(chunk_fn_id_) + ");\n"; + s += " lua_call(L, 0, 1);\n"; + s += " if (lua_isnil(L, -1)) {\n"; + s += " lua_pop(L, 1);\n"; + s += " lua_pushboolean(L, 1);\n"; + s += " }\n"; + s += "}\n\n"; + s += "} // namespace " + options_.cppNamespace + "\n\n"; + s += "namespace {\n\n"; + s += "int lc_open_thunk(lua_State* L) {\n"; + s += " " + options_.cppNamespace + "::open(L);\n"; + s += " return 1;\n"; + s += "}\n\n"; + s += "[[maybe_unused]] const luacpp::AutoModule lc_module_registration(" + c_escape(options_.moduleName) + + ", &lc_open_thunk);\n\n"; + s += "} // namespace\n"; + return s; + } + + ModuleOptions options_; + std::vector stack_; + std::vector functions_; + std::vector facades_; + int next_id_ = 0; + int label_counter_ = 0; + int chunk_fn_id_ = 0; +}; + +} // namespace + +GeneratedModule generate_module(BlockP chunk, const ModuleOptions& options) { + Gen gen(options); + return gen.run(std::move(chunk)); +} + +} // namespace lc diff --git a/src/codegen.hpp b/src/codegen.hpp new file mode 100644 index 0000000..faf8f45 --- /dev/null +++ b/src/codegen.hpp @@ -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 +#include + +#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 diff --git a/src/frontend.cpp b/src/frontend.cpp new file mode 100644 index 0000000..398c1ee --- /dev/null +++ b/src/frontend.cpp @@ -0,0 +1,919 @@ +#include "frontend.hpp" + +#include +#include +#include +#include +#include +#include + +namespace lc { +namespace { + +const std::set& keywords() { + static const std::set 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(c)) || c == '_'; } +bool is_name_char(char c) { return std::isalnum(static_cast(c)) || c == '_'; } + +void append_utf8(std::string& out, unsigned long cp) { + if (cp < 0x80) { + out += static_cast(cp); + } else if (cp < 0x800) { + out += static_cast(0xC0 | (cp >> 6)); + out += static_cast(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + out += static_cast(0xE0 | (cp >> 12)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } else { + out += static_cast(0xF0 | (cp >> 18)); + out += static_cast(0x80 | ((cp >> 12) & 0x3F)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(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(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(peek())) || peek() == '.')) get(); + if (peek() == 'p' || peek() == 'P') { + get(); + if (peek() == '+' || peek() == '-') get(); + while (!eof() && std::isdigit(static_cast(peek()))) get(); + } + } else { + while (!eof() && (std::isdigit(static_cast(peek())) || peek() == '.')) get(); + if (peek() == 'e' || peek() == 'E') { + get(); + if (peek() == '+' || peek() == '-') get(); + while (!eof() && std::isdigit(static_cast(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(peek()))) { + char h = get(); + value = value * 16 + (std::isdigit(static_cast(h)) ? h - '0' + : std::tolower(h) - 'a' + 10); + ++digits; + } + if (digits == 0) fail("invalid hexadecimal escape"); + out += static_cast(value); + break; + } + case 'z': + while (!eof() && std::isspace(static_cast(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(h))) fail("invalid UTF-8 escape"); + cp = cp * 16 + (std::isdigit(static_cast(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(e))) { + int value = e - '0', digits = 1; + while (digits < 3 && !eof() && std::isdigit(static_cast(peek()))) { + value = value * 10 + (get() - '0'); + ++digits; + } + if (value > 255) fail("decimal escape too large"); + out += static_cast(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(c)) || (c == '.' && std::isdigit(static_cast(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("'' 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(); + 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(); + 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(); + 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(); + 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(); + s->kind = StmtKind::Break; + s->line = line; + return s; + } + if (accept("goto")) { + auto s = std::make_unique(); + s->kind = StmtKind::Goto; + s->line = line; + s->name = expectName(); + return s; + } + if (accept("::")) { + auto s = std::make_unique(); + 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(); + s->kind = StmtKind::Expr; + s->line = line; + s->values.push_back(std::move(first)); + return s; + } + auto s = std::make_unique(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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 exprList() { + std::vector 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 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(); + 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 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(); + 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(); + 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(); + e->kind = ExprKind::String; + e->line = line; + e->str = cur_.text; + advance(); + return e; + } + if (accept("nil")) { + auto e = std::make_unique(); + e->kind = ExprKind::Nil; + e->line = line; + return e; + } + if (accept("true")) { + auto e = std::make_unique(); + e->kind = ExprKind::True; + e->line = line; + return e; + } + if (accept("false")) { + auto e = std::make_unique(); + e->kind = ExprKind::False; + e->line = line; + return e; + } + if (accept("...")) { + auto e = std::make_unique(); + 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(); + 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(); + 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(); + e->kind = ExprKind::Index; + e->line = line; + e->field = field; + e->a = std::move(obj); + return e; + } + + std::vector callArgs() { + std::vector args; + if (is("{")) { + args.push_back(tableCtor()); + return args; + } + if (cur_.kind == TokKind::String) { + auto e = std::make_unique(); + 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(); + 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(); + 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(); + 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(); + 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 diff --git a/src/frontend.hpp b/src/frontend.hpp new file mode 100644 index 0000000..cb2bce6 --- /dev/null +++ b/src/frontend.hpp @@ -0,0 +1,188 @@ +// Lua 5.4 lexer + parser producing a small AST used by the C++ back end. +#pragma once + +#include +#include +#include +#include +#include + +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; +using BlockP = std::unique_ptr; + +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 args; + BinOp bop{}; + UnOp uop{}; + + // function + std::vector params; + bool isVararg = false; + bool usesVararg = false; + BlockP body; + std::vector upvalues; // filled by the analyser + std::vector paramCell; // filled by the analyser + + // table constructor + std::vector fields; +}; + +struct Stmt; +using StmtP = std::unique_ptr; + +struct Block { + std::vector 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 names; + std::vector cells; // capture flags, filled by the analyser + std::vector targets; + std::vector values; + ExprP e1, e2, e3; + BlockP body; + std::vector 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 diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..813ff07 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,206 @@ +// luacpp: Lua 5.4 -> C++ module compiler (command line front end). +#include +#include +#include +#include +#include +#include +#include +#include + +#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 inputs; +}; + +void usage() { + std::cout << + "luacpp " << kVersion << " - compile Lua 5.4 modules into C++ packages\n" + "\n" + "Usage: luacpp [options] ...\n" + "\n" + "Options:\n" + " -r, --root root directory used to derive Lua module names\n" + " -o, --output output directory for the .hpp/.cpp pair (default: generated)\n" + " -n, --namespace 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(data.size())); +} + +std::string cpp_component(const std::string& name) { + std::string out; + for (char c : name) { + unsigned char u = static_cast(c); + out += (std::isalnum(u) || c == '_') ? c : '_'; + } + if (out.empty()) out = "_"; + if (std::isdigit(static_cast(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; +}