Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased

### Language

- `flua --mode=kernel` (`CompileConfig::mode = CompileMode::Kernel`) rejects floating-point literals and `/` at compile time. The default profile, float specialization, and the 16-byte `CVar` stay as they are.
- Short-string `\xHH` escapes follow Lua (exactly two hex digits). `\ddd` stays decimal, so `\033` is byte 33.

## 2.1.0

This release covers the work after v2.0.0. The public ABI stays at `SOVERSION` 2.
Expand Down
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,66 @@ FL_SPEC(Table_Spec_1, point, x) = NativeAdd(FL_SPEC(Table_Spec_1, point, x), (CV
- **Implicit type coercion**: No string→number conversion in arithmetic (`"10" + 1` errors).
- **Implicit globals**: Local variables must be declared with `local`; implicit global declarations are rejected.
- **File-level locals are const bindings**: no whole-slot reassign after init; tables from `__fakelua_init` are deep-const; use NativeObject / `new_global_obj` for mutable cross-frame state.
- **File-level statements are declarations**: an optional package declaration (`package "Name"`, `package = "Name"`, or `package("Name")`) is the first statement when present. The other file-level forms are `local`, `local function`, and `function`. A top-level call, assignment, `return`, `if`, or `while` is a compile error (`unsupported file-level statement`). Omitting the package declaration is legal; `require` and `module` are not the module system. Cross-package calls are `pkg.func(...)`.
- **Only `nil` and `false` are false**: `0` is true, and `not false` is true.
- **Operator precedence matches Lua 5.4**. `^` and `..` are right-associative; every other binary operator is left-associative. `//` binds with `*` `/` `%`, so `a + b % 7` is `a + (b % 7)` and `a * b + c // d` is `(a * b) + (c // d)`.

| precedence | operators |
|---|---|
| 1 | `or` |
| 2 | `and` |
| 3 | `<` `>` `<=` `>=` `~=` `==` |
| 4 | `\|` |
| 5 | `~` |
| 6 | `&` |
| 7 | `<<` `>>` |
| 8 | `..` |
| 9 | `+` `-` |
| 10 | `*` `/` `//` `%` |
| 12 | `^` |

- **String escapes match Lua, not C**: `\ddd` is a decimal byte, at most three digits, so `\033` is byte 33. `\xHH` is exactly two hex digits. ESC is `\x1b` or `\027`.
- **Colon calls insert the receiver**: `obj:f(1)` passes the same two arguments as `obj.f(obj, 1)`. A direct call that does not supply every parameter is a compile error. A call resolved by name, including a cross-package `pkg.func(...)`, is rejected at runtime when the count differs. `function T:f(...)` method definitions are rejected (`Unsupported function name with method definition`).
- **`json.encode` rejects array holes**: integer keys mean array intent, so a table whose keys are positive integers but not contiguous from 1 (`t[1]="a"; t[3]="c"`, or even `{[1001]=...}`) is an error instead of an object with `"1"`/`"3"` keys — the wire shape must not change silently. Keep protocol arrays gap-free (use `""` or `{}` placeholders, not nil), and use string keys (or `container.map`) for id-keyed maps. `#t` still stops at the first nil, like standard Lua; `serialize.encode/decode` keeps non-contiguous keys.
- **Syntax diagnostics preserve their own source location**: filename, line and column remain attached to nested compilation errors; multiline strings and Lua newline forms are counted correctly, and unfinished short strings have a clear reason.
- **Runtime errors carry the Lua source location and call stack**: `attempt to perform arithmetic on non-numeric value at main.lua:4` on all three backends, followed by `stack traceback:` (most recent call first, with file, line, and function name), including native errors raised as `FakeluaException`. Arbitrary C++ exceptions retain existing backend-specific propagation behavior. `stacktrace` remains the C++ stack. Interpreter tail calls reuse the current frame.

### Kernel profile

`CompileConfig::mode` selects the language profile. The default is `CompileMode::Default`. `flua --mode=kernel` sets `CompileMode::Kernel`.

In kernel mode the compiler rejects:

- floating-point literals, such as `3.14`, `1.0`, and `1e2`
- the `/` operator; integer division is written `//`

The diagnostics are `floating-point literal is forbidden in --mode=kernel` and `float division '/' is forbidden in --mode=kernel`. The same file still compiles `3.14` and `1 / 2` in the default profile. Float specialization and the `double` stored in `CVar` stay on that path. Kernel mode does not save XMM registers and does not turn the C backend into a bare-metal backend.

### Host `CVar` is not a kernel value

Every JIT translation unit embeds `src/compile/c_runtime_cov.h` (the string lives behind `src/compile/c_runtime_header.h`). That header is a host runtime: it starts with `#include <math.h>`, then a run of `FL_*` macros that depend on the host JIT and a frame-arena `State`. fakecc has no preprocessor and cannot compile this C++. Do not wire the header into a kernel.

The value layout is 16 bytes, the union contains `double`, and a compile-time assert locks the size:

```c
typedef struct CVar {
int type_;
int flag_;
union {
bool b;
int64_t i;
double f;
VarString *s;
VarTable *t;
VarMulti *m;
VarClosure *cl;
} data_;
} CVar;
typedef char check_cvar_size[sizeof(CVar) == 16 ? 1 : -1];
```

Leave the size, the field order, and that assert in place. A kernel value is a different representation, defined by fakeos `flrt`: one register-width `u64` whose low 3 bits are a tag (`nil`, small int, full `i64`, bool, string, table, closure, multi-return), with no `double` in the union. The two representations stay separate.

## Built-in Standard Libraries

FakeLua provides 30+ independent C++ native modules under `src/native/` (registered automatically on each `State`), covering math, string, table, IO, networking, timers, events, random, containers, compression, cryptography, serialization, databases, protobuf, config formats, logging, and subprocesses.
Expand Down
56 changes: 56 additions & 0 deletions README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,26 @@ FL_SPEC(Table_Spec_1, point, x) = NativeAdd(FL_SPEC(Table_Spec_1, point, x), (CV
- **隐式类型转换**:算术中不做字符串→数字的隐式转换(`"10" + 1` 会报错)。
- **隐式全局变量**:局部变量必须使用 `local` 声明,不支持隐式全局赋值。
- **文件级 local 为 const 绑定**:初始化后不可整槽再赋,`__fakelua_init` 创建的 Table 深 const;跨帧可变状态请用 NativeObject / `new_global_obj`。
- **文件级只有声明**:包声明可以不写;写了就必须是第一条语句,三种写法都认:`package "Name"`、`package = "Name"`、`package("Name")`。其余文件级形式是 `local`、`local function` 和 `function`。顶层调用、赋值、`return`、`if`、`while` 编译失败(`unsupported file-level statement`)。没有 `require` / `module`。跨包调用写成 `pkg.func(...)`。
- **只有 `nil` 和 `false` 为假**:`0` 为真,`not false` 为真。
- **运算符优先级与 Lua 5.4 一致**。`^` 和 `..` 右结合,其余二元运算符左结合。`//` 与 `*` `/` `%` 同级,所以 `a + b % 7` 是 `a + (b % 7)`,`a * b + c // d` 是 `(a * b) + (c // d)`。

| 优先级 | 运算符 |
|---|---|
| 1 | `or` |
| 2 | `and` |
| 3 | `<` `>` `<=` `>=` `~=` `==` |
| 4 | `\|` |
| 5 | `~` |
| 6 | `&` |
| 7 | `<<` `>>` |
| 8 | `..` |
| 9 | `+` `-` |
| 10 | `*` `/` `//` `%` |
| 12 | `^` |

- **字符串转义跟 Lua,不跟 C**:`\ddd` 是十进制,最多三位,`\033` 是字节 33。`\xHH` 是正好两位的十六进制。ESC 写成 `\x1b` 或 `\027`。
- **冒号调用插入接收者**:`obj:f(1)` 与 `obj.f(obj, 1)` 都是两个实参。直接调用少传或多传在编译期拒绝。按名字解析的调用,包括跨包 `pkg.func(...)`,实参数不对时在运行期拒绝。`function T:f(...)` 这种方法定义会编译失败(`Unsupported function name with method definition`)。
- **`json.encode` 拒绝数组空洞**:整数键就代表数组意图——键都是正整数但不从 1 起连续的表
(`t[1]="a"; t[3]="c"`,甚至 `{[1001]=...}`)一律报错,不再退化成 `{"1":"a","3":"c"}`:上线的
数据形状不许静默改变。协议数组请保持无洞(用 `""` 或 `{}` 占位,别留 nil);要按 id 建映射就
Expand All @@ -161,6 +181,42 @@ FL_SPEC(Table_Spec_1, point, x) = NativeAdd(FL_SPEC(Table_Spec_1, point, x), (CV
- **语法诊断保留自身源码位置**:嵌套编译失败仍报告其自身文件名、行和列;正确计算长字符串和 Lua 各种换行形式,短字符串未闭合时明确提示原因。
- **运行期错误带 Lua 源码位置和调用栈**:三个后端都会输出形如 `attempt to perform arithmetic on non-numeric value at main.lua:4` 的消息,后面跟着 `stack traceback:`(最近的调用在前,含文件、行和函数名)。原生函数显式抛出的 `FakeluaException` 也可定位。其他 C++ 异常保留各后端现有传播行为。`stacktrace` 仍是 C++ 堆栈。解释器的尾调用复用当前帧,不另占一帧。

### 内核 profile

`CompileConfig::mode` 选择语言 profile。默认是 `CompileMode::Default`。`flua --mode=kernel` 设为 `CompileMode::Kernel`。

内核模式在编译期拒绝:

- 浮点字面量,例如 `3.14`、`1.0`、`1e2`
- `/` 运算符;整除写成 `//`

诊断是 `floating-point literal is forbidden in --mode=kernel` 和 `float division '/' is forbidden in --mode=kernel`。同一个文件在默认 profile 里仍然可以编译 `3.14` 和 `1 / 2`。浮点特化以及 `CVar` 里的 `double` 留在默认路径。内核模式不为这个开关去保存 XMM,也不把 C 后端变成裸机后端。

### 宿主 `CVar` 不是内核值

每个 JIT 翻译单元嵌入 `src/compile/c_runtime_cov.h`(字符串挂在 `src/compile/c_runtime_header.h` 后面)。这份头文件是宿主运行时:以 `#include <math.h>` 开头,后面是一串依赖宿主 JIT 和带帧 arena 的 `State` 的 `FL_*` 宏。fakecc 没有预处理器,也编不了这套 C++。不要把它接到内核上。

布局是 16 字节,联合体里有 `double`,并用编译期断言锁住大小:

```c
typedef struct CVar {
int type_;
int flag_;
union {
bool b;
int64_t i;
double f;
VarString *s;
VarTable *t;
VarMulti *m;
VarClosure *cl;
} data_;
} CVar;
typedef char check_cvar_size[sizeof(CVar) == 16 ? 1 : -1];
```

大小、字段顺序和这条断言保持不动。内核值是另一套表示,由 fakeos 的 `flrt` 定义:一个寄存器宽的 `u64`,低 3 位是标签(`nil`、小整数、完整 `i64`、布尔、字符串、表、闭包、多返回值),联合体里没有 `double`。两套表示不要合成同一种。

## 标准内置扩展库

FakeLua 在 `src/native/` 下提供 30+ 个独立 C++ 原生模块(每个 `State` 创建时自动注册),覆盖数学、字符串、表、IO、网络、定时器、事件、随机数、容器、压缩、加密、序列化、数据库、Protobuf、配置解析、日志、子进程等领域。
Expand Down
10 changes: 10 additions & 0 deletions cmd/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
// --once run init + fini only, without the update loop
// (one-shot script / self-check)
// --jit_type=n 0=tcc 1=gcc 2=interp (default 0)
// --mode=kernel reject float literals and '/' at compile time
// --debug enable debug mode
//
// Services whose logic is entirely in Lua can use flua's built-in modules (e.g.
Expand All @@ -54,6 +55,7 @@ using namespace fakelua;
DEFINE_bool(debug, false, "enable debug mode");
DEFINE_bool(once, false, "run init + fini only, without the update loop (one-shot script)");
DEFINE_int32(jit_type, 0, "jit type: 0=tcc, 1=gcc, 2=interp");
DEFINE_string(mode, "default", "language profile: default, or kernel (reject float literals and '/')");
// 常驻服务会把 stdout 当日志用,编译期的 INFO 噪音盖掉真实错误,所以宿主默认只到 Warn。
DEFINE_int32(log_level, static_cast<int>(LogLevel::Warn), "min log level: 0=Trace 1=Debug 2=Info 3=Warn 4=Error 5=Critical 6=Off");

Expand Down Expand Up @@ -213,6 +215,8 @@ int main(int argc, char **argv) {
"\n"
"update is called back-to-back; the script paces itself if it needs\n"
"to (os.sleep takes milliseconds). --once runs init + fini only.\n"
"--mode=kernel rejects floating-point literals and '/' at compile time.\n"
"The default profile is unchanged.\n"
"\n"
"Graceful exit, runs fini first:\n"
" return a non-zero code from update\n"
Expand Down Expand Up @@ -247,6 +251,12 @@ int main(int argc, char **argv) {
}
CompileConfig cfg;
cfg.debug_mode = FLAGS_debug;
if (FLAGS_mode == "kernel") {
cfg.mode = CompileMode::Kernel;
} else if (FLAGS_mode != "default") {
std::cerr << "flua: invalid --mode=" << FLAGS_mode << " (expected default or kernel)" << std::endl;
return 1;
}
// 只编译并初始化实际选中的那一个后端,避免 __fakelua_init 在多个后端重复执行副作用。
const auto chosen = static_cast<JITType>(FLAGS_jit_type);
cfg.disable_jit[JIT_TCC] = (chosen != JIT_TCC);
Expand Down
9 changes: 9 additions & 0 deletions include/fakelua.h
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,13 @@ inline JitTypeSpan CCodeJitTypes() {
return span;
}

// 语言 profile。Default 保持宿主 JIT 和浮点。Kernel 只在编译期拒绝浮点字面量和 `/`,
// 不改 CVar、运行时头文件,也不把 C 后端变成裸机后端。
enum class CompileMode {
Default = 0,
Kernel,
};

// 控制编译器的配置项
struct CompileConfig {
// 跳过 JIT 编译。仅进行词法分析和语法解析。
Expand All @@ -377,6 +384,8 @@ struct CompileConfig {
// 记录生成的 C 代码(全局变量、函数声明、函数实现,不含公共头部)。
// 开启后可通过 GetLastRecordedCCode(State*) 获取最近一次编译产生的代码片段。
bool record_c_code = false;
// flua 的 `--mode=kernel` 对应 CompileMode::Kernel。默认值不要改成 Kernel。
CompileMode mode = CompileMode::Default;
};

inline void DisableAllJit(CompileConfig &cfg) {
Expand Down
28 changes: 28 additions & 0 deletions src/compile/semantic_analysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,36 @@ void SemanticAnalysis::CheckFileLevelStmts(const ParseResult &pr) {
}
}

void SemanticAnalysis::CheckKernelProfile(const SyntaxTreeInterfacePtr &chunk) {
WalkSyntaxTree(chunk, [this](const SyntaxTreeInterfacePtr &node) {
if (!node) {
return;
}
if (node->Type() == SyntaxTreeType::Binop) {
const auto op = std::dynamic_pointer_cast<SyntaxTreeBinop>(node);
if (op && op->GetOpKind() == BinOpKind::kSlash) {
ThrowError("float division '/' is forbidden in --mode=kernel", node);
}
return;
}
if (node->Type() != SyntaxTreeType::Exp) {
return;
}
const auto exp = std::dynamic_pointer_cast<SyntaxTreeExp>(node);
if (!exp || exp->GetExpKind() != ExpKind::kNumber) {
return;
}
if (!IsInteger(exp->ExpValue())) {
ThrowError("floating-point literal is forbidden in --mode=kernel", node);
}
});
}

AnalysisResult SemanticAnalysis::Analyze(const ParseResult &pr, const CompileConfig &cfg) {
file_name_ = pr.file_name;
if (cfg.mode == CompileMode::Kernel) {
CheckKernelProfile(pr.chunk);
}

AnalysisResult ar;
AnalyzeGlobalConstNames(pr.chunk, ar);
Expand Down
3 changes: 3 additions & 0 deletions src/compile/semantic_analysis.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ class SemanticAnalysis {
// 之后就分辨不出哪些是用户写在文件级的语句、哪些是编译器生成的初始化赋值了。
void CheckFileLevelStmts(const ParseResult &pr);

// CompileMode::Kernel:编译期拒绝浮点字面量和 `/`。Default 不调用。
void CheckKernelProfile(const SyntaxTreeInterfacePtr &chunk);

// 运行语义分析
AnalysisResult Analyze(const ParseResult &pr, const CompileConfig &cfg);

Expand Down
29 changes: 26 additions & 3 deletions src/util/string_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ void TrimInplace(std::string &str) {
\": 在字符串中插入双引号而不被特殊解释。
\': 在字符串中插入单引号而不被特殊解释。
\z: 跳过后续的空格序列
\digit: 从缓冲区读取数字
*/
\ddd: 十进制字节,最多三位。\033 是 33,不是 C 的八进制 ESC。
\xHH: 十六进制字节,必须正好两位。ESC 写成 \x1b 或 \027。
*/

std::string ReplaceEscapeChars(const std::string &str) {
std::string result;
Expand All @@ -54,7 +55,29 @@ std::string ReplaceEscapeChars(const std::string &str) {
} else {
char esc = *it;
++it;
switch (esc) {
if (esc == 'x') {
int hex_val = 0;
for (int i = 0; i < 2; ++i) {
if (it == str.end()) {
ThrowFakeluaException("ReplaceEscapeChars failed, invalid hexadecimal escape \\x");
}
const unsigned char h = static_cast<unsigned char>(*it);
int digit = -1;
if (h >= '0' && h <= '9') {
digit = h - '0';
} else if (h >= 'a' && h <= 'f') {
digit = h - 'a' + 10;
} else if (h >= 'A' && h <= 'F') {
digit = h - 'A' + 10;
}
if (digit < 0) {
ThrowFakeluaException("ReplaceEscapeChars failed, invalid hexadecimal escape \\x");
}
hex_val = hex_val * 16 + digit;
++it;
}
result += static_cast<char>(hex_val);
} else switch (esc) {
case 'a':
result += '\a';
break;
Expand Down
46 changes: 46 additions & 0 deletions test/test_basic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1622,6 +1622,52 @@ TEST(basic, host_exceptions_and_failing_xpcall_handlers_are_contained) {
}
}

TEST(basic, colon_call_inserts_receiver) {
FakeluaStateGuard state;
SetDebugLogLevel(state.GetState(), LogLevel::Off);
CompileString(state.GetState(), R"(
function colon_ok()
local T = {}
T.f = function(self, x)
return x
end
if T:f(1) ~= 1 then return 1 end
if T.f(T, 1) ~= 1 then return 2 end
return 0
end
)", {.debug_mode = false});
for (auto backend: AllJitTypes()) {
int64_t result = -1;
Call(state.GetState(), backend, "colon_ok", result);
EXPECT_EQ(result, 0) << JitTypeName(backend);
}
}

TEST(basic, zero_is_true_and_operator_precedence_matches_lua) {
FakeluaStateGuard state;
SetDebugLogLevel(state.GetState(), LogLevel::Off);
CompileString(state.GetState(), R"(
function truth_and_prec()
if not 0 then return 1 end
if not (not false) then return 2 end
if nil then return 3 end
if false then return 4 end
local a, b, c, d = 2, 5, 9, 4
if a + b % 7 ~= 7 then return 5 end
if a * b + c // d ~= 12 then return 6 end
if 2 ^ 3 ^ 2 ~= 512 then return 7 end
if ("a" .. "b" .. "c") ~= "abc" then return 8 end
if (1 | 2 & 1) ~= 1 then return 9 end
return 0
end
)", {.debug_mode = false});
for (auto backend: AllJitTypes()) {
int64_t result = -1;
Call(state.GetState(), backend, "truth_and_prec", result);
EXPECT_EQ(result, 0) << JitTypeName(backend);
}
}

TEST(basic, tonumber_rejects_fractional_bases_and_overflowing_custom_hex) {
FakeluaStateGuard state;
CompileFile(state.GetState(), "./basic/test_basic_tonumber_edge.lua", {});
Expand Down
Loading
Loading