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

+1259
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
// C++ back end: turns a Lua AST into a .hpp/.cpp pair that rebuilds the module
// on top of the official Lua 5.4 VM.
#pragma once
#include <stdexcept>
#include <string>
#include "frontend.hpp"
namespace lc {
class CompileError : public std::runtime_error {
public:
explicit CompileError(const std::string& msg) : std::runtime_error(msg) {}
};
struct ModuleOptions {
std::string moduleName; // e.g. "pkg.mathx"
std::string headerPath; // path used by the generated #include, e.g. "pkg/mathx.hpp"
std::string cppNamespace; // e.g. "pkg::mathx"
};
struct GeneratedModule {
std::string header;
std::string source;
};
GeneratedModule generate_module(BlockP chunk, const ModuleOptions& options);
} // namespace lc
+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
+188
View File
@@ -0,0 +1,188 @@
// Lua 5.4 lexer + parser producing a small AST used by the C++ back end.
#pragma once
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace lc {
class ParseError : public std::runtime_error {
public:
ParseError(const std::string& msg, int line) : std::runtime_error(format(msg, line)) {}
static std::string format(const std::string& msg, int line) {
return "line " + std::to_string(line) + ": " + msg;
}
};
enum class TokKind { Eof, Name, Number, String, Keyword, Op };
struct Token {
TokKind kind = TokKind::Eof;
std::string text; // name, keyword, operator text, or raw string bytes
int line = 0;
bool isInt = false;
long long ival = 0;
double dval = 0;
};
class Lexer {
public:
Lexer(std::string source, std::string chunkname);
Token next();
private:
bool eof() const { return pos_ >= src_.size(); }
char peek(size_t ahead = 0) const { return pos_ + ahead < src_.size() ? src_[pos_ + ahead] : '\0'; }
char get();
void skip_space_and_comments();
Token make_number();
Token make_short_string(char quote);
Token make_long_string(int level, int line);
Token make_name();
[[noreturn]] void fail(const std::string& msg) const;
std::string src_;
std::string chunkname_;
size_t pos_ = 0;
int line_ = 1;
};
struct Expr;
struct Block;
using ExprP = std::unique_ptr<Expr>;
using BlockP = std::unique_ptr<Block>;
enum class ExprKind {
Nil,
True,
False,
Number,
String,
Vararg,
Name,
Index,
Call,
Method,
Function,
Bin,
Un,
Table,
Paren
};
enum class BinOp {
Add,
Sub,
Mul,
Div,
IDiv,
Mod,
Pow,
Concat,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
And,
Or,
BAnd,
BOr,
BXor,
Shl,
Shr
};
enum class UnOp { Neg, Not, Len, BNot };
struct TableField {
bool hasKey = false;
bool isName = false;
std::string name;
ExprP key;
ExprP value;
};
struct Expr {
ExprKind kind = ExprKind::Nil;
int line = 0;
// literals
bool isInt = false;
long long ival = 0;
double dval = 0;
std::string str; // string bytes, name, field name or method name
// operands / operands of calls
ExprP a, b;
std::string field; // Index: a.field ; Method: a:field(args)
std::vector<ExprP> args;
BinOp bop{};
UnOp uop{};
// function
std::vector<std::string> params;
bool isVararg = false;
bool usesVararg = false;
BlockP body;
std::vector<std::string> upvalues; // filled by the analyser
std::vector<char> paramCell; // filled by the analyser
// table constructor
std::vector<TableField> fields;
};
struct Stmt;
using StmtP = std::unique_ptr<Stmt>;
struct Block {
std::vector<StmtP> stmts;
};
enum class StmtKind {
Expr, // function call statement (values[0])
Assign, // targets = values
Local, // local names = values
LocalFunction, // local function name() ... end
Do,
While, // e1 = condition
Repeat, // values = condition (single expr)
If, // conds + elseBody
NumFor, // name = e1, e2 [, e3]
GenFor, // names in values
Break,
Goto,
Label,
Return
};
struct CondBlock {
ExprP cond;
BlockP body;
};
struct Stmt {
StmtKind kind = StmtKind::Expr;
int line = 0;
std::string name;
std::vector<std::string> names;
std::vector<char> cells; // capture flags, filled by the analyser
std::vector<ExprP> targets;
std::vector<ExprP> values;
ExprP e1, e2, e3;
BlockP body;
std::vector<CondBlock> conds;
BlockP elseBody;
ExprP fn;
};
// Parses a Lua 5.4 chunk. Throws ParseError on invalid input.
BlockP parse_chunk(const std::string& source, const std::string& chunkname);
const char* binop_symbol(BinOp op);
} // namespace lc
+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;
}