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

+919
View File
@@ -0,0 +1,919 @@
#include "frontend.hpp"
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <set>
#include <string>
namespace lc {
namespace {
const std::set<std::string>& keywords() {
static const std::set<std::string> 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<unsigned char>(c)) || c == '_'; }
bool is_name_char(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }
void append_utf8(std::string& out, unsigned long cp) {
if (cp < 0x80) {
out += static_cast<char>(cp);
} else if (cp < 0x800) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(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<unsigned char>(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<unsigned char>(peek())) || peek() == '.')) get();
if (peek() == 'p' || peek() == 'P') {
get();
if (peek() == '+' || peek() == '-') get();
while (!eof() && std::isdigit(static_cast<unsigned char>(peek()))) get();
}
} else {
while (!eof() && (std::isdigit(static_cast<unsigned char>(peek())) || peek() == '.')) get();
if (peek() == 'e' || peek() == 'E') {
get();
if (peek() == '+' || peek() == '-') get();
while (!eof() && std::isdigit(static_cast<unsigned char>(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<unsigned char>(peek()))) {
char h = get();
value = value * 16 + (std::isdigit(static_cast<unsigned char>(h)) ? h - '0'
: std::tolower(h) - 'a' + 10);
++digits;
}
if (digits == 0) fail("invalid hexadecimal escape");
out += static_cast<char>(value);
break;
}
case 'z':
while (!eof() && std::isspace(static_cast<unsigned char>(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<unsigned char>(h))) fail("invalid UTF-8 escape");
cp = cp * 16 + (std::isdigit(static_cast<unsigned char>(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<unsigned char>(e))) {
int value = e - '0', digits = 1;
while (digits < 3 && !eof() && std::isdigit(static_cast<unsigned char>(peek()))) {
value = value * 10 + (get() - '0');
++digits;
}
if (value > 255) fail("decimal escape too large");
out += static_cast<char>(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<unsigned char>(c)) || (c == '.' && std::isdigit(static_cast<unsigned char>(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("'<eof>' 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<Block>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
s->kind = StmtKind::Break;
s->line = line;
return s;
}
if (accept("goto")) {
auto s = std::make_unique<Stmt>();
s->kind = StmtKind::Goto;
s->line = line;
s->name = expectName();
return s;
}
if (accept("::")) {
auto s = std::make_unique<Stmt>();
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<Stmt>();
s->kind = StmtKind::Expr;
s->line = line;
s->values.push_back(std::move(first));
return s;
}
auto s = std::make_unique<Stmt>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
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<Stmt>();
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<Expr>();
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<ExprP> exprList() {
std::vector<ExprP> 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<const char*, BinOp> 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<Expr>();
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<const char*, UnOp> 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<Expr>();
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<Expr>();
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<Expr>();
e->kind = ExprKind::String;
e->line = line;
e->str = cur_.text;
advance();
return e;
}
if (accept("nil")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::Nil;
e->line = line;
return e;
}
if (accept("true")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::True;
e->line = line;
return e;
}
if (accept("false")) {
auto e = std::make_unique<Expr>();
e->kind = ExprKind::False;
e->line = line;
return e;
}
if (accept("...")) {
auto e = std::make_unique<Expr>();
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<Expr>();
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<Expr>();
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<Expr>();
e->kind = ExprKind::Index;
e->line = line;
e->field = field;
e->a = std::move(obj);
return e;
}
std::vector<ExprP> callArgs() {
std::vector<ExprP> args;
if (is("{")) {
args.push_back(tableCtor());
return args;
}
if (cur_.kind == TokKind::String) {
auto e = std::make_unique<Expr>();
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<Expr>();
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<Expr>();
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<Expr>();
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<Expr>();
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