Save bytecode to file through CLI (#170)

Using --compile=binary it's now possible to produce binary bytecode so that it can be compiled offline and loaded into the VM.
This commit is contained in:
NotDSF 2021-11-09 22:54:53 +00:00 committed by GitHub
parent fe1bf43b54
commit 3ba0bdf708
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -13,6 +13,17 @@
#include <memory>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
enum class CompileFormat
{
Default,
Binary
};
static int lua_loadstring(lua_State* L)
{
size_t l = 0;
@ -370,7 +381,7 @@ static void reportError(const char* name, const Luau::CompileError& error)
report(name, error.getLocation(), "CompileError", error.what());
}
static bool compileFile(const char* name)
static bool compileFile(const char* name, CompileFormat format)
{
std::optional<std::string> source = readFile(name);
if (!source)
@ -387,7 +398,20 @@ static bool compileFile(const char* name)
Luau::compileOrThrow(bcb, *source);
printf("%s", bcb.dumpEverything().c_str());
switch (format)
{
case CompileFormat::Default:
printf("%s", bcb.dumpEverything().c_str());
break;
case CompileFormat::Binary:
#ifdef _WIN32
_setmode(_fileno(stdout), _O_BINARY);
#endif
std::string Bytecode = bcb.getBytecode();
fwrite(Bytecode.c_str(), 1, Bytecode.size(), stdout);
break;
}
return true;
}
@ -412,7 +436,7 @@ static void displayHelp(const char* argv0)
printf("\n");
printf("Available modes:\n");
printf(" omitted: compile and run input files one by one\n");
printf(" --compile: compile input files and output resulting bytecode\n");
printf(" --compile[=format]: compile input files and output resulting formatted bytecode (binary or text)\n");
printf("\n");
printf("Available options:\n");
printf(" --profile[=N]: profile the code using N Hz sampling (default 10000) and output results to profile.out\n");
@ -444,8 +468,16 @@ int main(int argc, char** argv)
return 0;
}
if (argc >= 2 && strcmp(argv[1], "--compile") == 0)
{
if (argc >= 2 && strncmp(argv[1], "--compile", strlen("--compile")) == 0)
{
CompileFormat format = CompileFormat::Default;
if (strcmp(argv[1], "--compile=binary") == 0)
{
format = CompileFormat::Binary;
}
int failed = 0;
for (int i = 2; i < argc; ++i)
@ -457,12 +489,12 @@ int main(int argc, char** argv)
{
traverseDirectory(argv[i], [&](const std::string& name) {
if (name.length() > 4 && name.rfind(".lua") == name.length() - 4)
failed += !compileFile(name.c_str());
failed += !compileFile(name.c_str(), format);
});
}
else
{
failed += !compileFile(argv[i]);
failed += !compileFile(argv[i], format);
}
}