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.
446 lines
14 KiB
C++
446 lines
14 KiB
C++
// luacpp: Lua 5.4 -> C++ compiler (command line front end).
|
|
//
|
|
// luacpp run <script.lua> [args...] transpile, compile and execute the script
|
|
// luacpp <module.lua>... emit .hpp/.cpp packages for CMake
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <set>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "codegen.hpp"
|
|
#include "frontend.hpp"
|
|
#include "luacpp-config.hpp"
|
|
|
|
#if defined(_WIN32)
|
|
#define LUACPP_EXIT_STATUS(st) (st)
|
|
#else
|
|
#include <sys/wait.h>
|
|
#define LUACPP_EXIT_STATUS(st) (WIFEXITED(st) ? WEXITSTATUS(st) : 1)
|
|
#endif
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
namespace {
|
|
|
|
const char* kVersion = "0.2.0";
|
|
|
|
enum class Mode { Emit, Run };
|
|
|
|
struct Options {
|
|
Mode mode = Mode::Emit;
|
|
fs::path root;
|
|
fs::path output;
|
|
std::string nsPrefix;
|
|
bool quiet = false;
|
|
bool onlyBuild = false;
|
|
bool verbose = false;
|
|
std::string cxx = "c++";
|
|
std::vector<std::string> inputs;
|
|
std::vector<std::string> 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 to C++\n"
|
|
"\n"
|
|
"Usage:\n"
|
|
" luacpp run <script.lua> [args...] compile the script and run it\n"
|
|
" luacpp <file.lua>... emit .hpp/.cpp C++ packages\n"
|
|
"\n"
|
|
"Options:\n"
|
|
" -r, --root <dir> root directory used to derive Lua module names\n"
|
|
" -o, --output <dir> output directory (run: ./luacpp-build/<name>)\n"
|
|
" -n, --namespace <ns> C++ namespace prefix, also prefixes module names\n"
|
|
" --cxx <compiler> 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"
|
|
"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) {
|
|
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 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<char>(c);
|
|
} else if (c >= 32 && c < 127) {
|
|
out += static_cast<char>(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) {
|
|
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", "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 "lua" -> "pkg.foo" (init.lua -> "pkg")
|
|
std::string derive_module_name(const fs::path& file, const fs::path& 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 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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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 <luacpp/rt.hpp>\n\n";
|
|
s += "#include <cstdio>\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<fs::path> collect_lua_files(const fs::path& root) {
|
|
std::vector<fs::path> 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<fs::path> files = collect_lua_files(root);
|
|
if (files.empty()) {
|
|
std::cerr << "luacpp: no .lua file found under " << root.string() << "\n";
|
|
return 1;
|
|
}
|
|
|
|
std::vector<Job> jobs;
|
|
std::set<std::string> 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;
|
|
std::vector<std::string> args(argv + 1, argv + 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 args[++index];
|
|
};
|
|
|
|
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 = value("--root");
|
|
continue;
|
|
}
|
|
if (arg == "-o" || arg == "--output") {
|
|
opt.output = value("--output");
|
|
continue;
|
|
}
|
|
if (arg == "-n" || arg == "--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") {
|
|
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;
|
|
}
|
|
|
|
int failures = 0;
|
|
try {
|
|
if (opt.mode == Mode::Run) {
|
|
if (opt.inputs.size() != 1) {
|
|
std::cerr << "luacpp: run expects exactly one script\n";
|
|
return 2;
|
|
}
|
|
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;
|
|
}
|