feat(compiler): add a Lua 5.4 to C++ module transpiler

Each Lua module becomes a header/source pair exposing a C++ namespace, so Lua
code can be linked and consumed like any C++ package while keeping the exact
semantics of the official 5.4 VM.
This commit is contained in:
BlackAngelTV committed 2026-11-18 08:48:05 +01:00
1 parent 62e950dbc5
commit 517ed0bf4d
8 files changed
+3476

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
// luacpp: Lua 5.4 -> C++ module compiler (command line front end).
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "codegen.hpp"
#include "frontend.hpp"
namespace fs = std::filesystem;
namespace {
const char* kVersion = "0.1.0";
struct Options {
fs::path root;
fs::path output = "generated";
std::string nsPrefix;
bool quiet = false;
std::vector<std::string> inputs;
};
void usage() {
std::cout <<
"luacpp " << kVersion << " - compile Lua 5.4 modules into C++ packages\n"
"\n"
"Usage: luacpp [options] <file.lua>...\n"
"\n"
"Options:\n"
" -r, --root <dir> root directory used to derive Lua module names\n"
" -o, --output <dir> output directory for the .hpp/.cpp pair (default: generated)\n"
" -n, --namespace <ns> C++ namespace prefix, also prefixes Lua module names\n"
" -q, --quiet do not print generated file names\n"
" -h, --help show this help\n"
" --version show the version\n"
"\n"
"Example:\n"
" luacpp --root lua --namespace demo -o build/gen lua/mathx.lua\n"
" # -> build/gen/mathx.hpp + mathx.cpp, Lua module \"demo.mathx\"\n"
" # C++ namespace demo::mathx\n";
}
std::string read_file(const fs::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("cannot open " + path.string());
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
void write_file(const fs::path& path, const std::string& data) {
fs::create_directories(path.parent_path());
std::ofstream out(path, std::ios::binary);
if (!out) throw std::runtime_error("cannot write " + path.string());
out.write(data.data(), static_cast<std::streamsize>(data.size()));
}
std::string cpp_component(const std::string& name) {
std::string out;
for (char c : name) {
unsigned char u = static_cast<unsigned char>(c);
out += (std::isalnum(u) || c == '_') ? c : '_';
}
if (out.empty()) out = "_";
if (std::isdigit(static_cast<unsigned char>(out[0]))) out = "_" + out;
static const char* keywords[] = {"and", "class", "delete", "for", "if", "int", "long", "new",
"not", "or", "private", "public", "return", "static",
"template", "this", "true", "false", "namespace", "using"};
for (const char* kw : keywords) {
if (out == kw) return "_" + out;
}
return out;
}
// "lua/pkg/foo.lua" relative to root "lua" -> "pkg.foo" (init.lua -> "pkg")
std::string derive_module_name(const fs::path& file, const fs::path& root) {
fs::path rel = fs::relative(fs::absolute(file), fs::absolute(root));
std::string stem = rel.generic_string();
if (stem.size() > 4 && stem.compare(stem.size() - 4, 4, ".lua") == 0) stem.erase(stem.size() - 4);
if (stem == "init") return "";
if (stem.size() > 5 && stem.compare(stem.size() - 5, 5, "/init") == 0) stem.erase(stem.size() - 5);
std::replace(stem.begin(), stem.end(), '/', '.');
return stem;
}
std::string join_ns(const std::string& dotted) {
std::string out;
std::string part;
for (char c : dotted) {
if (c == '.') {
if (!part.empty()) {
if (!out.empty()) out += "::";
out += cpp_component(part);
part.clear();
}
} else {
part += c;
}
}
if (!part.empty()) {
if (!out.empty()) out += "::";
out += cpp_component(part);
}
return out;
}
} // namespace
int main(int argc, char** argv) {
Options opt;
bool rootGiven = false;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
auto next = [&](const char* what) -> std::string {
if (i + 1 >= argc) {
std::cerr << "luacpp: missing value for " << what << "\n";
std::exit(2);
}
return argv[++i];
};
if (arg == "-h" || arg == "--help") {
usage();
return 0;
}
if (arg == "--version") {
std::cout << "luacpp " << kVersion << " (Lua 5.4)\n";
return 0;
}
if (arg == "-r" || arg == "--root") {
opt.root = next("--root");
rootGiven = true;
continue;
}
if (arg == "-o" || arg == "--output") {
opt.output = next("--output");
continue;
}
if (arg == "-n" || arg == "--namespace") {
opt.nsPrefix = next("--namespace");
continue;
}
if (arg == "-q" || arg == "--quiet") {
opt.quiet = true;
continue;
}
if (!arg.empty() && arg[0] == '-') {
std::cerr << "luacpp: unknown option '" << arg << "'\n";
return 2;
}
opt.inputs.push_back(arg);
}
if (opt.inputs.empty()) {
usage();
return 2;
}
if (!rootGiven) {
opt.root = fs::path(opt.inputs.front()).parent_path();
if (opt.root.empty()) opt.root = ".";
}
int failures = 0;
for (const std::string& input : opt.inputs) {
fs::path file(input);
try {
std::string module = derive_module_name(file, opt.root);
if (module.empty()) throw std::runtime_error("cannot derive a module name from " + input);
std::string luaName = opt.nsPrefix.empty() ? module : opt.nsPrefix + "." + module;
std::string ns = join_ns(luaName);
fs::path rel = fs::relative(fs::absolute(file), fs::absolute(opt.root));
fs::path stem = rel;
stem.replace_extension();
if (stem.filename() == "init.lua") stem = stem.parent_path().filename();
lc::ModuleOptions mod;
mod.moduleName = luaName;
mod.headerPath = stem.generic_string() + ".hpp";
mod.cppNamespace = ns;
std::string source = read_file(file);
lc::BlockP chunk = lc::parse_chunk(source, file.string());
lc::GeneratedModule gen = lc::generate_module(std::move(chunk), mod);
fs::path hpp = opt.output / (stem.generic_string() + ".hpp");
fs::path cpp = opt.output / (stem.generic_string() + ".cpp");
write_file(hpp, gen.header);
write_file(cpp, gen.source);
if (!opt.quiet) {
std::cout << "luacpp: " << input << " -> " << cpp.generic_string() << " (" << luaName
<< " / " << ns << ")\n";
}
} catch (const std::exception& e) {
std::cerr << "luacpp: " << input << ": " << e.what() << "\n";
++failures;
}
}
return failures == 0 ? 0 : 1;
}