From 274daa7b1d94fc9f917321736566bcb9e7ce6b5b Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Wed, 18 Nov 2026 08:16:46 +0100 Subject: [PATCH] feat(cli): add a run mode that compiles and executes a Lua script Writing C++ or CMake to try a Lua file makes the compiler hard to evaluate, so one command now transpiles the script and its sibling modules, links them and runs the result. Literal require calls resolve against the compiled modules. --- Demo/hello.lua | 28 ++++ src/codegen.cpp | 17 +++ src/main.cpp | 367 +++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 348 insertions(+), 64 deletions(-) create mode 100644 Demo/hello.lua diff --git a/Demo/hello.lua b/Demo/hello.lua new file mode 100644 index 0000000..49ad7fa --- /dev/null +++ b/Demo/hello.lua @@ -0,0 +1,28 @@ +-- Script à lancer directement avec le compilateur : +-- ./build/luacpp run Demo/hello.lua +-- Aucun C++ nécessaire : luacpp traduit ce fichier en C++, le compile et l'exécute. +print("Bonjour depuis du Lua compile en C++ !") + +local function fib(n) + if n < 2 then + return n + end + return fib(n - 1) + fib(n - 2) +end + +local suite = {} +for i = 0, 12 do + suite[#suite + 1] = tostring(fib(i)) +end +print("fibonacci : " .. table.concat(suite, " ")) + +local langs = { "Lua", "C++" } +for i, name in ipairs(langs) do + print(string.format("%d. %s", i, name)) +end + +local t = { sum = 0 } +for _, v in ipairs({ 3, 4, 5 }) do + t.sum = t.sum + v +end +print("somme = " .. t.sum) diff --git a/src/codegen.cpp b/src/codegen.cpp index 4ce2ff3..d47f275 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -490,7 +490,24 @@ private: call_expr(e, LUA_MULTRET); } + // `require("pkg.name")` with a literal name is resolved against the registry + // of compiled modules instead of Lua's package.path. + bool is_require_call(const Expr& e) const { + if (e.kind != ExprKind::Call || !e.a || e.a->kind != ExprKind::Name) return false; + if (e.a->str != "require" || e.args.size() != 1) return false; + if (!e.args[0] || e.args[0]->kind != ExprKind::String) return false; + return resolve("require").kind == R_GLOBAL; + } + void call_expr(Expr& e, int nres) { + if (is_require_call(e)) { + int base = cur().top; + emit("luacpp::check_stack(L, 2);"); + emit("luacpp::require(L, " + c_escape(e.args[0]->str) + ");"); + if (nres == 0) emit("lua_settop(L, " + N(base) + ");"); + set_top(nres == LUA_MULTRET ? base + 1 : base + nres); + return; + } int fslot = cur().top + 1; emit("luacpp::check_stack(L, " + N(static_cast(e.args.size()) + 8) + ");"); if (e.kind == ExprKind::Method) { diff --git a/src/main.cpp b/src/main.cpp index 813ff07..939db1e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,48 +1,85 @@ -// luacpp: Lua 5.4 -> C++ module compiler (command line front end). +// luacpp: Lua 5.4 -> C++ compiler (command line front end). +// +// luacpp run [args...] transpile, compile and execute the script +// luacpp ... emit .hpp/.cpp packages for CMake #include #include +#include +#include +#include #include #include #include +#include #include #include #include #include "codegen.hpp" #include "frontend.hpp" +#include "luacpp-config.hpp" + +#if defined(_WIN32) +#define LUACPP_EXIT_STATUS(st) (st) +#else +#include +#define LUACPP_EXIT_STATUS(st) (WIFEXITED(st) ? WEXITSTATUS(st) : 1) +#endif namespace fs = std::filesystem; namespace { -const char* kVersion = "0.1.0"; +const char* kVersion = "0.2.0"; + +enum class Mode { Emit, Run }; struct Options { + Mode mode = Mode::Emit; fs::path root; - fs::path output = "generated"; + fs::path output; std::string nsPrefix; bool quiet = false; + bool onlyBuild = false; + bool verbose = false; + std::string cxx = "c++"; std::vector inputs; + std::vector programArgs; +}; + +struct Job { + fs::path source; + std::string moduleName; // Lua module name, namespace prefix included + std::string ns; // C++ namespace, e.g. "demo::mathx" + std::string headerPath; // relative #include used by the generated source + fs::path hpp; + fs::path cpp; }; void usage() { std::cout << - "luacpp " << kVersion << " - compile Lua 5.4 modules into C++ packages\n" + "luacpp " << kVersion << " - compile Lua 5.4 to C++\n" "\n" - "Usage: luacpp [options] ...\n" + "Usage:\n" + " luacpp run [args...] compile the script and run it\n" + " luacpp ... emit .hpp/.cpp C++ packages\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" + " -o, --output output directory (run: ./luacpp-build/)\n" + " -n, --namespace C++ namespace prefix, also prefixes module names\n" + " --cxx C++ compiler used by `run` (default: c++)\n" + " --only-build `run` compiles the executable but does not execute it\n" + " -v, --verbose print the C++ compile and run commands\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"; + "Examples:\n" + " ./build.sh\n" + " cd build && ./luacpp run ../Demo/hello.lua\n" + " ./luacpp run ../Demo/lua/report.lua -n demo\n" + " ./luacpp ../Demo/lua/todo.lua -n demo -o gen\n"; } std::string read_file(const fs::path& path) { @@ -60,6 +97,26 @@ void write_file(const fs::path& path, const std::string& data) { out.write(data.data(), static_cast(data.size())); } +std::string quoted(const std::string& s) { return "\"" + s + "\""; } + +std::string cpp_string(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; +} + std::string cpp_component(const std::string& name) { std::string out; for (char c : name) { @@ -68,21 +125,24 @@ std::string cpp_component(const std::string& name) { } 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"}; + static const char* keywords[] = {"and", "class", "delete", "for", "if", "int", + "long", "new", "not", "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") +// "lua/pkg/foo.lua" relative to "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::error_code ec; + fs::path rel = fs::relative(fs::absolute(file), fs::absolute(root), ec); + if (ec || rel.empty()) rel = file.filename(); 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 == "init") return fs::absolute(root).filename().string(); 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; @@ -109,21 +169,203 @@ std::string join_ns(const std::string& dotted) { return out; } +Job plan_job(const fs::path& file, const fs::path& root, const fs::path& outDir, + const std::string& nsPrefix) { + std::string module = derive_module_name(file, root); + if (module.empty()) throw std::runtime_error("cannot derive a module name from " + file.string()); + + std::error_code ec; + fs::path rel = fs::relative(fs::absolute(file), fs::absolute(root), ec); + if (ec || rel.empty()) rel = file.filename(); + fs::path stem = rel; + stem.replace_extension(); + if (stem.filename() == "init.lua") stem = stem.parent_path().filename(); + + Job job; + job.source = file; + job.moduleName = nsPrefix.empty() ? module : nsPrefix + "." + module; + job.ns = join_ns(job.moduleName); + job.headerPath = stem.generic_string() + ".hpp"; + job.hpp = outDir / (stem.generic_string() + ".hpp"); + job.cpp = outDir / (stem.generic_string() + ".cpp"); + return job; +} + +void generate_job(const Job& job, bool quiet) { + std::string source = read_file(job.source); + lc::BlockP chunk = lc::parse_chunk(source, job.source.string()); + + lc::ModuleOptions options; + options.moduleName = job.moduleName; + options.headerPath = job.headerPath; + options.cppNamespace = job.ns; + + lc::GeneratedModule generated = lc::generate_module(std::move(chunk), options); + write_file(job.hpp, generated.header); + write_file(job.cpp, generated.source); + if (!quiet) { + std::cout << "luacpp: " << job.source.string() << " -> " << job.cpp.generic_string() << " (" + << job.moduleName << " / " << job.ns << ")\n"; + } +} + +// Creates the C++ entry point for `luacpp run`: it exposes `arg`, executes the +// compiled chunk and turns Lua errors into a message plus exit code 1. +std::string driver_source(const std::string& entryModule) { + std::string s; + s += "// Generated by luacpp run. Do not edit.\n"; + s += "#include \n\n"; + s += "#include \n\n"; + s += "int main(int argc, char** argv) {\n"; + s += " try {\n"; + s += " luacpp::State state;\n"; + s += " lua_State* L = state.raw();\n"; + s += " lua_createtable(L, argc, 1);\n"; + s += " for (int i = 0; i < argc; ++i) {\n"; + s += " lua_pushstring(L, argv[i]);\n"; + s += " lua_rawseti(L, -2, i);\n"; + s += " }\n"; + s += " lua_setglobal(L, \"arg\");\n"; + s += " state.require(" + cpp_string(entryModule) + ");\n"; + s += " } catch (const std::exception& error) {\n"; + s += " std::fprintf(stderr, \"lua: %s\\n\", error.what());\n"; + s += " return 1;\n"; + s += " }\n"; + s += " return 0;\n"; + s += "}\n"; + return s; +} + +std::string lua_link_flags() { + std::string flags = LUACPP_LUA_CFLAGS; + std::string libs = LUACPP_LUA_LIBS; + if (!libs.empty()) return flags.empty() ? libs : flags + " " + libs; +#if !defined(_WIN32) + if (FILE* pipe = popen("pkg-config --cflags --libs lua5.4 2>/dev/null", "r")) { + char buffer[1024]; + std::string out; + while (std::fgets(buffer, sizeof buffer, pipe)) out += buffer; + pclose(pipe); + if (!out.empty()) return out; + } +#endif + return "-llua5.4 -lm"; +} + +std::vector collect_lua_files(const fs::path& root) { + std::vector files; + std::error_code ec; + for (fs::recursive_directory_iterator it(root, fs::directory_options::skip_permission_denied, ec), end; + it != end; it.increment(ec)) { + if (ec) break; + const fs::path& path = it->path(); + if (it->is_directory(ec)) { + std::string name = path.filename().string(); + if (name == "luacpp-build" || (!name.empty() && name[0] == '.')) it.disable_recursion_pending(); + continue; + } + if (path.extension() == ".lua") files.push_back(path); + } + std::sort(files.begin(), files.end()); + return files; +} + +int run_script(const Options& opt) { + fs::path entry = opt.inputs.front(); + if (!fs::exists(entry)) { + std::cerr << "luacpp: cannot find " << entry.string() << "\n"; + return 1; + } + + fs::path root = opt.root.empty() ? fs::absolute(entry).parent_path() : fs::absolute(opt.root); + fs::path outDir = opt.output.empty() ? fs::path("luacpp-build") / entry.stem() : opt.output; + + std::vector files = collect_lua_files(root); + if (files.empty()) { + std::cerr << "luacpp: no .lua file found under " << root.string() << "\n"; + return 1; + } + + std::vector jobs; + std::set seen; + for (const auto& file : files) { + Job job = plan_job(file, root, outDir, opt.nsPrefix); + if (!seen.insert(job.moduleName).second) continue; + jobs.push_back(job); + } + + for (const auto& job : jobs) generate_job(job, opt.quiet); + + std::string entryModule = derive_module_name(entry, root); + if (!opt.nsPrefix.empty()) entryModule = opt.nsPrefix + "." + entryModule; + + fs::path driver = outDir / "luacpp-main.cpp"; + write_file(driver, driver_source(entryModule)); + + fs::path exe = outDir / entry.stem(); +#if defined(_WIN32) + exe += ".exe"; +#endif + + std::string command = opt.cxx + " -std=c++17 -O2 -o " + quoted(exe.string()); + for (const auto& job : jobs) command += " " + quoted(job.cpp.string()); + command += " " + quoted(driver.string()); + command += " -I" + quoted(outDir.string()); + command += " -I" + quoted(LUACPP_RUNTIME_INCLUDE_DIR); + command += " " + lua_link_flags(); + + if (opt.verbose) std::cerr << "luacpp: compile: " << command << "\n"; + if (!opt.quiet) std::cout << "luacpp: building " << exe.string() << "\n"; + int compileStatus = std::system(command.c_str()); + if (LUACPP_EXIT_STATUS(compileStatus) != 0) { + std::cerr << "luacpp: C++ compilation failed\n"; + return 1; + } + + if (opt.onlyBuild) { + std::cout << exe.string() << "\n"; + return 0; + } + + std::string runCommand = quoted(exe.string()); + for (const auto& arg : opt.programArgs) runCommand += " " + quoted(arg); + if (opt.verbose) std::cerr << "luacpp: run: " << runCommand << "\n"; + int runStatus = std::system(runCommand.c_str()); // evaluated once: do not inline + return LUACPP_EXIT_STATUS(runStatus); +} + } // namespace int main(int argc, char** argv) { Options opt; - bool rootGiven = false; + std::vector args(argv + 1, argv + argc); - for (int i = 1; i < argc; ++i) { - std::string arg = argv[i]; - auto next = [&](const char* what) -> std::string { - if (i + 1 >= argc) { + if (args.empty()) { + usage(); + return 2; + } + + size_t index = 0; + if (args[0] == "run") { + opt.mode = Mode::Run; + index = 1; + } + + for (; index < args.size(); ++index) { + // Everything after the script name belongs to the compiled program. + if (opt.mode == Mode::Run && !opt.inputs.empty()) { + opt.programArgs.push_back(args[index]); + continue; + } + const std::string& arg = args[index]; + auto value = [&](const char* what) -> std::string { + if (index + 1 >= args.size()) { std::cerr << "luacpp: missing value for " << what << "\n"; std::exit(2); } - return argv[++i]; + return args[++index]; }; + if (arg == "-h" || arg == "--help") { usage(); return 0; @@ -133,16 +375,27 @@ int main(int argc, char** argv) { return 0; } if (arg == "-r" || arg == "--root") { - opt.root = next("--root"); - rootGiven = true; + opt.root = value("--root"); continue; } if (arg == "-o" || arg == "--output") { - opt.output = next("--output"); + opt.output = value("--output"); continue; } if (arg == "-n" || arg == "--namespace") { - opt.nsPrefix = next("--namespace"); + opt.nsPrefix = value("--namespace"); + continue; + } + if (arg == "--cxx") { + opt.cxx = value("--cxx"); + continue; + } + if (arg == "--only-build") { + opt.onlyBuild = true; + continue; + } + if (arg == "-v" || arg == "--verbose") { + opt.verbose = true; continue; } if (arg == "-q" || arg == "--quiet") { @@ -160,47 +413,33 @@ int main(int argc, char** argv) { 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"; + try { + if (opt.mode == Mode::Run) { + if (opt.inputs.size() != 1) { + std::cerr << "luacpp: run expects exactly one script\n"; + return 2; } - } catch (const std::exception& e) { - std::cerr << "luacpp: " << input << ": " << e.what() << "\n"; - ++failures; + return run_script(opt); } + + if (opt.root.empty()) { + opt.root = fs::path(opt.inputs.front()).parent_path(); + if (opt.root.empty()) opt.root = "."; + } + fs::path outDir = opt.output.empty() ? fs::path("generated") : opt.output; + for (const auto& input : opt.inputs) { + try { + generate_job(plan_job(input, opt.root, outDir, opt.nsPrefix), opt.quiet); + } catch (const std::exception& error) { + std::cerr << "luacpp: " << input << ": " << error.what() << "\n"; + ++failures; + } + } + } catch (const std::exception& error) { + std::cerr << "luacpp: " << error.what() << "\n"; + return 1; } return failures == 0 ? 0 : 1; }