From 6ee14ba7ce5747f553f828d08b604c87c4be9c20 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 17:01:07 +0800 Subject: [PATCH 1/2] feat: add --mode=kernel and lock the host language contract Kernel mode rejects floating-point literals and '/' at compile time without changing the default JIT or the 16-byte CVar. Document why the host C runtime is not a bare-metal backend, and keep Lua decimal and hex string escapes. Co-authored-by: Cursor --- CHANGELOG.md | 7 + README.md | 56 ++++++ README.zh.md | 56 ++++++ cmd/main.cpp | 10 + include/fakelua.h | 9 + src/compile/semantic_analysis.cpp | 28 +++ src/compile/semantic_analysis.h | 3 + src/util/string_util.cpp | 29 ++- test/test_flua_host.cpp | 45 +++++ test/test_language_contract.cpp | 304 ++++++++++++++++++++++++++++++ 10 files changed, 544 insertions(+), 3 deletions(-) create mode 100644 test/test_language_contract.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index e6339c15..95c05e7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 14fb6d7c..acbd204c 100644 --- a/README.md +++ b/README.md @@ -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 `, 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. diff --git a/README.zh.md b/README.zh.md index d9825027..bd2604b1 100644 --- a/README.zh.md +++ b/README.zh.md @@ -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 建映射就 @@ -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 ` 开头,后面是一串依赖宿主 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、配置解析、日志、子进程等领域。 diff --git a/cmd/main.cpp b/cmd/main.cpp index 94f642e3..c337d75a 100644 --- a/cmd/main.cpp +++ b/cmd/main.cpp @@ -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. @@ -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(LogLevel::Warn), "min log level: 0=Trace 1=Debug 2=Info 3=Warn 4=Error 5=Critical 6=Off"); @@ -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" @@ -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(FLAGS_jit_type); cfg.disable_jit[JIT_TCC] = (chosen != JIT_TCC); diff --git a/include/fakelua.h b/include/fakelua.h index e0bcb54b..0685d447 100644 --- a/include/fakelua.h +++ b/include/fakelua.h @@ -366,6 +366,13 @@ inline JitTypeSpan CCodeJitTypes() { return span; } +// 语言 profile。Default 保持宿主 JIT 和浮点。Kernel 只在编译期拒绝浮点字面量和 `/`, +// 不改 CVar、运行时头文件,也不把 C 后端变成裸机后端。 +enum class CompileMode { + Default = 0, + Kernel, +}; + // 控制编译器的配置项 struct CompileConfig { // 跳过 JIT 编译。仅进行词法分析和语法解析。 @@ -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) { diff --git a/src/compile/semantic_analysis.cpp b/src/compile/semantic_analysis.cpp index 137aeecc..9a2fcdab 100644 --- a/src/compile/semantic_analysis.cpp +++ b/src/compile/semantic_analysis.cpp @@ -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(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(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); diff --git a/src/compile/semantic_analysis.h b/src/compile/semantic_analysis.h index 5b771fb9..56ba2dbf 100644 --- a/src/compile/semantic_analysis.h +++ b/src/compile/semantic_analysis.h @@ -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); diff --git a/src/util/string_util.cpp b/src/util/string_util.cpp index 6b80cc6d..54a2715e 100644 --- a/src/util/string_util.cpp +++ b/src/util/string_util.cpp @@ -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; @@ -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(*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(hex_val); + } else switch (esc) { case 'a': result += '\a'; break; diff --git a/test/test_flua_host.cpp b/test/test_flua_host.cpp index 74d8234f..9cc9c069 100644 --- a/test/test_flua_host.cpp +++ b/test/test_flua_host.cpp @@ -221,6 +221,51 @@ end EXPECT_EQ(result.err.find("update must not run"), std::string::npos) << result.err; } +TEST(flua_host, kernel_mode_rejects_float_division) { + const auto flua = FluaBinary(); + ASSERT_TRUE(std::filesystem::exists(flua)) << flua; + const auto dir = std::filesystem::temp_directory_path() / "fakelua_flua_host"; + const auto script = WriteScript(dir, "kernel_div.lua", R"(package "main" +function init() + local x = 1 / 2 + if x == 0.5 then return 0 end + return 1 +end +function update() + return 0 +end +function fini() + return 0 +end +)"); + const auto kernel = RunFlua(flua, {"--mode=kernel", "--once", "--jit_type=2", script.string()}); + EXPECT_EQ(kernel.code, 1) << kernel.err; + EXPECT_NE(kernel.err.find("float division '/' is forbidden in --mode=kernel"), std::string::npos) << kernel.err; + + const auto literal = WriteScript(dir, "kernel_lit.lua", R"(package "main" +function init() + local x = 3.14 + return 0 +end +function update() + return 0 +end +function fini() + return 0 +end +)"); + const auto lit = RunFlua(flua, {"--mode=kernel", "--once", "--jit_type=2", literal.string()}); + EXPECT_EQ(lit.code, 1) << lit.err; + EXPECT_NE(lit.err.find("floating-point literal is forbidden in --mode=kernel"), std::string::npos) << lit.err; + + const auto def = RunFlua(flua, {"--mode=default", "--once", "--jit_type=2", script.string()}); + EXPECT_EQ(def.code, 0) << def.err; + + const auto bad = RunFlua(flua, {"--mode=bare", "--once", "--jit_type=2", script.string()}); + EXPECT_EQ(bad.code, 1) << bad.err; + EXPECT_NE(bad.err.find("invalid --mode="), std::string::npos) << bad.err; +} + TEST(flua_host, empty_directory_exits) { const auto flua = FluaBinary(); ASSERT_TRUE(std::filesystem::exists(flua)) << flua; diff --git a/test/test_language_contract.cpp b/test/test_language_contract.cpp new file mode 100644 index 00000000..ff5a2027 --- /dev/null +++ b/test/test_language_contract.cpp @@ -0,0 +1,304 @@ +#include "fakelua.h" +#include "gtest/gtest.h" + +#include + +using namespace fakelua; + +namespace { + +CompileConfig QuietConfig() { + CompileConfig cfg; + cfg.debug_mode = false; + return cfg; +} + +CompileConfig KernelConfig() { + CompileConfig cfg = QuietConfig(); + cfg.mode = CompileMode::Kernel; + return cfg; +} + +FakeluaStateGuard QuietState() { + FakeluaStateGuard sg; + SetDebugLogLevel(sg.GetState(), LogLevel::Off); + return sg; +} + +void ExpectCompileFails(const std::string &src, const std::string &needle, const CompileConfig &cfg = QuietConfig()) { + auto sg = QuietState(); + try { + CompileString(sg.GetState(), src, cfg); + FAIL() << "expected compile failure containing \"" << needle << "\"\n" << src; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find(needle), std::string::npos) << e.what(); + } +} + +void ExpectRuns(const std::string &src, const char *fn, int expected, const CompileConfig &cfg = QuietConfig()) { + auto sg = QuietState(); + ASSERT_NO_THROW(CompileString(sg.GetState(), src, cfg)) << src; + for (const auto jit: AllJitTypes()) { + int ret = -1; + Call(sg.GetState(), jit, fn, ret); + EXPECT_EQ(ret, expected) << static_cast(jit); + } +} + +}// namespace + +TEST(language_contract, package_forms_and_cross_package_call) { + auto sg = QuietState(); + auto *s = sg.GetState(); + const auto cfg = QuietConfig(); + ASSERT_NO_THROW(CompileString(s, R"( +package "Left" +function add(a, b) + return a + b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +package = "Right" +function add(a, b) + return a - b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +package("Mid") +function add(a, b) + return a * b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +function use() + if Left.add(2, 3) ~= 5 then return 1 end + if Right.add(5, 1) ~= 4 then return 2 end + if Mid.add(3, 4) ~= 12 then return 3 end + return 0 +end +)", cfg)); + for (const auto jit: AllJitTypes()) { + int ret = -1; + Call(s, jit, "use", ret); + EXPECT_EQ(ret, 0) << static_cast(jit); + } +} + +TEST(language_contract, missing_package_still_compiles) { + ExpectRuns(R"( +function bare() + return 1 +end +)", "bare", 1); +} + +TEST(language_contract, package_must_be_first_when_present) { + ExpectCompileFails(R"( +local x = 1 +package "Late" +function f() + return x +end +)", "unsupported file-level statement"); +} + +TEST(language_contract, file_level_executable_statements_fail) { + ExpectCompileFails("function f() return 1 end\nf()\n", "unsupported file-level statement"); + ExpectCompileFails("a = 1\n", "unsupported file-level statement"); + ExpectCompileFails("return 1\n", "unsupported file-level statement"); + ExpectCompileFails("if true then end\n", "unsupported file-level statement"); + ExpectCompileFails("while false do end\n", "unsupported file-level statement"); +} + +TEST(language_contract, file_level_local_cannot_be_reassigned) { + ExpectCompileFails(R"( +local a = 1 +function f() + a = 2 + return a +end +)", "cannot reassign file-level constant"); +} + +TEST(language_contract, no_implicit_globals) { + ExpectCompileFails(R"( +function main() + x = 1 + return x +end +)", "no implicit globals"); + ExpectCompileFails(R"( +function main() + return x +end +)", "no implicit globals"); +} + +TEST(language_contract, direct_call_arity_is_compile_time) { + const char *header = R"( +local function g(a, b) + return a +end +local function h(...) + return 7 +end +)"; + ExpectCompileFails(std::string(header) + "function few() return g(1) end\n", "wrong number of arguments"); + ExpectCompileFails(std::string(header) + "function many() return g(1, 2, 3) end\n", "wrong number of arguments"); + ExpectRuns(std::string(header) + "function ok() return h(1, 2, 3) end\n", "ok", 7); +} + +TEST(language_contract, named_call_arity_is_runtime) { + auto sg = QuietState(); + auto *s = sg.GetState(); + const auto cfg = QuietConfig(); + ASSERT_NO_THROW(CompileString(s, R"( +package "Lib" +function g(a, b) + return a +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +function call_few() + return Lib.g(1) +end +function call_many() + return Lib.g(1, 2, 3) +end +function call_ok() + return Lib.g(4, 5) +end +)", cfg)); + for (const auto jit: AllJitTypes()) { + int ret = 0; + EXPECT_THROW(Call(s, jit, "call_few", ret), std::exception); + EXPECT_THROW(Call(s, jit, "call_many", ret), std::exception); + ret = 0; + Call(s, jit, "call_ok", ret); + EXPECT_EQ(ret, 4); + } +} + +TEST(language_contract, no_implicit_numeric_conversion) { + const char *src = R"( +function bad() + return "10" + 1 +end +)"; + auto sg = QuietState(); + ASSERT_NO_THROW(CompileString(sg.GetState(), src, QuietConfig())); + for (const auto jit: AllJitTypes()) { + int ret = 0; + try { + Call(sg.GetState(), jit, "bad", ret); + FAIL() << "\"10\" + 1 must not become 11"; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("non-numeric"), std::string::npos) << e.what(); + EXPECT_EQ(ret, 0); + } + } +} + +TEST(language_contract, colon_call_inserts_receiver) { + ExpectRuns(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 +)", "colon_ok", 0); + ExpectCompileFails("function T:f(x)\n return x\nend\n", "Unsupported function name with method definition"); + ExpectCompileFails(R"( +local function f(self, x) + return x +end +function missing() + return f() +end +)", "wrong number of arguments"); +} + +TEST(language_contract, truth_and_precedence) { + ExpectRuns(R"( +function truth() + 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 + return 0 +end +)", "truth", 0); + ExpectRuns(R"( +function prec() + local a, b, c, d = 2, 5, 9, 4 + if a + b % 7 ~= 7 then return 1 end + if a * b + c // d ~= 12 then return 2 end + if 2 ^ 3 ^ 2 ~= 512 then return 3 end + if ("a" .. "b" .. "c") ~= "abc" then return 4 end + if (1 | 2 & 1) ~= 1 then return 5 end + return 0 +end +)", "prec", 0); +} + +TEST(language_contract, string_escapes_are_lua_not_c) { + ExpectRuns(R"( +function escapes() + if string.byte("\033") ~= 33 then return 1 end + if string.byte("\027") ~= 27 then return 2 end + if string.byte("\x1b") ~= 27 then return 3 end + if string.byte("\x1B") ~= 27 then return 4 end + return 0 +end +)", "escapes", 0); + ExpectCompileFails("function f() return \"\\x\" end\n", "invalid hexadecimal escape"); + ExpectCompileFails("function f() return \"\\x1\" end\n", "invalid hexadecimal escape"); + ExpectCompileFails("function f() return \"\\xzz\" end\n", "invalid hexadecimal escape"); + ExpectCompileFails("function f() return \"\\256\" end\n", "decimal escape too large"); +} + +TEST(language_contract, kernel_mode_rejects_float_literal_and_division) { + const auto kernel = KernelConfig(); + ExpectCompileFails("function f() return 3.14 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1.0 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1e2 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return -1.5 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1 / 2 end\n", "float division '/' is forbidden in --mode=kernel", kernel); + ExpectCompileFails(R"( +function f(a, b) + return a / b +end +)", "float division '/' is forbidden in --mode=kernel", kernel); + ExpectRuns(R"( +function half() + local x = 1 / 2 + local y = 3.14 + if x == 0.5 and y > 3 then return 1 end + return 0 +end +)", "half", 1); + ExpectRuns(R"( +function k() + local n = 1 + 2 * 3 + local q = 7 // 2 + local s = "3.14" + if #s ~= 4 then return 0 end + if 0x10 ~= 16 then return 0 end + return n + q +end +)", "k", 10, kernel); +} + +TEST(language_contract, kernel_mode_allows_slash_inside_a_string) { + ExpectRuns(R"( +function slash_text() + local s = "1 / 2" + if s ~= "1 / 2" then return 0 end + return 1 +end +)", "slash_text", 1, KernelConfig()); +} From 41b7d2f28d3913a6d8f14d57b6ffae7c08c47cd5 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 19:43:09 +0800 Subject: [PATCH 2/2] test: move the language contract cases into the module suites Co-authored-by: Cursor --- test/test_basic.cpp | 46 +++++ test/test_exception.cpp | 166 +++++++++++++++++ test/test_language_contract.cpp | 304 -------------------------------- test/test_package.cpp | 65 +++++++ test/test_string.cpp | 39 ++++ 5 files changed, 316 insertions(+), 304 deletions(-) delete mode 100644 test/test_language_contract.cpp diff --git a/test/test_basic.cpp b/test/test_basic.cpp index 38930461..6914f13f 100644 --- a/test/test_basic.cpp +++ b/test/test_basic.cpp @@ -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", {}); diff --git a/test/test_exception.cpp b/test/test_exception.cpp index 0ea0d6c7..f6be716b 100644 --- a/test/test_exception.cpp +++ b/test/test_exception.cpp @@ -2302,3 +2302,169 @@ TEST(exception, cross_engine_closure_throw_merges_gcc_and_interp_frames) { EXPECT_TRUE(e.Loc().ends_with(":2")) << e.Loc() << "\n" << e.what(); } } + +namespace { + +CompileConfig QuietConfig() { + CompileConfig cfg; + cfg.debug_mode = false; + return cfg; +} + +CompileConfig KernelConfig() { + CompileConfig cfg = QuietConfig(); + cfg.mode = CompileMode::Kernel; + return cfg; +} + +void ExpectCompileFails(const std::string &src, const std::string &needle, const CompileConfig &cfg = QuietConfig()) { + FakeluaStateGuard sg; + SetDebugLogLevel(sg.GetState(), LogLevel::Off); + try { + CompileString(sg.GetState(), src, cfg); + FAIL() << "expected compile failure containing \"" << needle << "\"\n" << src; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find(needle), std::string::npos) << e.what(); + } +} + +void ExpectRuns(const std::string &src, const char *fn, int expected, const CompileConfig &cfg = QuietConfig()) { + FakeluaStateGuard sg; + SetDebugLogLevel(sg.GetState(), LogLevel::Off); + ASSERT_NO_THROW(CompileString(sg.GetState(), src, cfg)) << src; + for (const auto jit: AllJitTypes()) { + int ret = -1; + Call(sg.GetState(), jit, fn, ret); + EXPECT_EQ(ret, expected) << static_cast(jit); + } +} + +}// namespace + +TEST(exception, file_level_executable_statements_fail) { + ExpectCompileFails("function f() return 1 end\nf()\n", "unsupported file-level statement"); + ExpectCompileFails("a = 1\n", "unsupported file-level statement"); + ExpectCompileFails("return 1\n", "unsupported file-level statement"); + ExpectCompileFails("if true then end\n", "unsupported file-level statement"); + ExpectCompileFails("while false do end\n", "unsupported file-level statement"); +} + +TEST(exception, file_level_local_cannot_be_reassigned) { + ExpectCompileFails(R"( +local a = 1 +function f() + a = 2 + return a +end +)", "cannot reassign file-level constant"); +} + +TEST(exception, implicit_global_read_and_write_fail) { + ExpectCompileFails("function main()\n x = 1\n return x\nend\n", "no implicit globals"); + ExpectCompileFails("function main()\n return x\nend\n", "no implicit globals"); +} + +TEST(exception, direct_call_arity_is_compile_time) { + const char *header = R"( +local function g(a, b) + return a +end +local function h(...) + return 7 +end +)"; + ExpectCompileFails(std::string(header) + "function few() return g(1) end\n", "wrong number of arguments"); + ExpectCompileFails(std::string(header) + "function many() return g(1, 2, 3) end\n", "wrong number of arguments"); + ExpectRuns(std::string(header) + "function vararg_ok() return h(1, 2, 3) end\n", "vararg_ok", 7); +} + +TEST(exception, named_call_arity_is_runtime) { + FakeluaStateGuard sg; + auto *s = sg.GetState(); + SetDebugLogLevel(s, LogLevel::Off); + const auto cfg = QuietConfig(); + ASSERT_NO_THROW(CompileString(s, "package \"Lib\"\nfunction g(a, b)\n return a\nend\n", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +function call_few() + return Lib.g(1) +end +function call_many() + return Lib.g(1, 2, 3) +end +function call_ok() + return Lib.g(4, 5) +end +)", cfg)); + for (const auto jit: AllJitTypes()) { + int ret = 0; + EXPECT_THROW(Call(s, jit, "call_few", ret), std::exception); + EXPECT_THROW(Call(s, jit, "call_many", ret), std::exception); + ret = 0; + Call(s, jit, "call_ok", ret); + EXPECT_EQ(ret, 4); + } +} + +TEST(exception, string_arithmetic_is_not_coerced) { + const char *src = "function bad()\n return \"10\" + 1\nend\n"; + FakeluaStateGuard sg; + SetDebugLogLevel(sg.GetState(), LogLevel::Off); + ASSERT_NO_THROW(CompileString(sg.GetState(), src, QuietConfig())); + for (const auto jit: AllJitTypes()) { + int ret = 0; + try { + Call(sg.GetState(), jit, "bad", ret); + FAIL() << "\"10\" + 1 must not become 11"; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("non-numeric"), std::string::npos) << e.what(); + EXPECT_EQ(ret, 0); + } + } +} + +TEST(exception, method_definition_and_missing_self_fail) { + ExpectCompileFails("function T:f(x)\n return x\nend\n", "Unsupported function name with method definition"); + ExpectCompileFails(R"( +local function f(self, x) + return x +end +function missing() + return f() +end +)", "wrong number of arguments"); +} + +TEST(exception, kernel_mode_rejects_float_literal_and_division) { + const auto kernel = KernelConfig(); + ExpectCompileFails("function f() return 3.14 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1.0 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1e2 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return -1.5 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f() return 1 / 2 end\n", "float division '/' is forbidden in --mode=kernel", kernel); + ExpectCompileFails("function f(a, b)\n return a / b\nend\n", "float division '/' is forbidden in --mode=kernel", kernel); + ExpectRuns(R"( +function half() + local x = 1 / 2 + local y = 3.14 + if x == 0.5 and y > 3 then return 1 end + return 0 +end +)", "half", 1); + ExpectRuns(R"( +function kernel_int() + local n = 1 + 2 * 3 + local q = 7 // 2 + local s = "3.14" + if #s ~= 4 then return 0 end + if 0x10 ~= 16 then return 0 end + return n + q +end +)", "kernel_int", 10, kernel); + ExpectRuns(R"( +function slash_text() + local s = "1 / 2" + if s ~= "1 / 2" then return 0 end + return 1 +end +)", "slash_text", 1, kernel); +} diff --git a/test/test_language_contract.cpp b/test/test_language_contract.cpp deleted file mode 100644 index ff5a2027..00000000 --- a/test/test_language_contract.cpp +++ /dev/null @@ -1,304 +0,0 @@ -#include "fakelua.h" -#include "gtest/gtest.h" - -#include - -using namespace fakelua; - -namespace { - -CompileConfig QuietConfig() { - CompileConfig cfg; - cfg.debug_mode = false; - return cfg; -} - -CompileConfig KernelConfig() { - CompileConfig cfg = QuietConfig(); - cfg.mode = CompileMode::Kernel; - return cfg; -} - -FakeluaStateGuard QuietState() { - FakeluaStateGuard sg; - SetDebugLogLevel(sg.GetState(), LogLevel::Off); - return sg; -} - -void ExpectCompileFails(const std::string &src, const std::string &needle, const CompileConfig &cfg = QuietConfig()) { - auto sg = QuietState(); - try { - CompileString(sg.GetState(), src, cfg); - FAIL() << "expected compile failure containing \"" << needle << "\"\n" << src; - } catch (const std::exception &e) { - EXPECT_NE(std::string(e.what()).find(needle), std::string::npos) << e.what(); - } -} - -void ExpectRuns(const std::string &src, const char *fn, int expected, const CompileConfig &cfg = QuietConfig()) { - auto sg = QuietState(); - ASSERT_NO_THROW(CompileString(sg.GetState(), src, cfg)) << src; - for (const auto jit: AllJitTypes()) { - int ret = -1; - Call(sg.GetState(), jit, fn, ret); - EXPECT_EQ(ret, expected) << static_cast(jit); - } -} - -}// namespace - -TEST(language_contract, package_forms_and_cross_package_call) { - auto sg = QuietState(); - auto *s = sg.GetState(); - const auto cfg = QuietConfig(); - ASSERT_NO_THROW(CompileString(s, R"( -package "Left" -function add(a, b) - return a + b -end -)", cfg)); - ASSERT_NO_THROW(CompileString(s, R"( -package = "Right" -function add(a, b) - return a - b -end -)", cfg)); - ASSERT_NO_THROW(CompileString(s, R"( -package("Mid") -function add(a, b) - return a * b -end -)", cfg)); - ASSERT_NO_THROW(CompileString(s, R"( -function use() - if Left.add(2, 3) ~= 5 then return 1 end - if Right.add(5, 1) ~= 4 then return 2 end - if Mid.add(3, 4) ~= 12 then return 3 end - return 0 -end -)", cfg)); - for (const auto jit: AllJitTypes()) { - int ret = -1; - Call(s, jit, "use", ret); - EXPECT_EQ(ret, 0) << static_cast(jit); - } -} - -TEST(language_contract, missing_package_still_compiles) { - ExpectRuns(R"( -function bare() - return 1 -end -)", "bare", 1); -} - -TEST(language_contract, package_must_be_first_when_present) { - ExpectCompileFails(R"( -local x = 1 -package "Late" -function f() - return x -end -)", "unsupported file-level statement"); -} - -TEST(language_contract, file_level_executable_statements_fail) { - ExpectCompileFails("function f() return 1 end\nf()\n", "unsupported file-level statement"); - ExpectCompileFails("a = 1\n", "unsupported file-level statement"); - ExpectCompileFails("return 1\n", "unsupported file-level statement"); - ExpectCompileFails("if true then end\n", "unsupported file-level statement"); - ExpectCompileFails("while false do end\n", "unsupported file-level statement"); -} - -TEST(language_contract, file_level_local_cannot_be_reassigned) { - ExpectCompileFails(R"( -local a = 1 -function f() - a = 2 - return a -end -)", "cannot reassign file-level constant"); -} - -TEST(language_contract, no_implicit_globals) { - ExpectCompileFails(R"( -function main() - x = 1 - return x -end -)", "no implicit globals"); - ExpectCompileFails(R"( -function main() - return x -end -)", "no implicit globals"); -} - -TEST(language_contract, direct_call_arity_is_compile_time) { - const char *header = R"( -local function g(a, b) - return a -end -local function h(...) - return 7 -end -)"; - ExpectCompileFails(std::string(header) + "function few() return g(1) end\n", "wrong number of arguments"); - ExpectCompileFails(std::string(header) + "function many() return g(1, 2, 3) end\n", "wrong number of arguments"); - ExpectRuns(std::string(header) + "function ok() return h(1, 2, 3) end\n", "ok", 7); -} - -TEST(language_contract, named_call_arity_is_runtime) { - auto sg = QuietState(); - auto *s = sg.GetState(); - const auto cfg = QuietConfig(); - ASSERT_NO_THROW(CompileString(s, R"( -package "Lib" -function g(a, b) - return a -end -)", cfg)); - ASSERT_NO_THROW(CompileString(s, R"( -function call_few() - return Lib.g(1) -end -function call_many() - return Lib.g(1, 2, 3) -end -function call_ok() - return Lib.g(4, 5) -end -)", cfg)); - for (const auto jit: AllJitTypes()) { - int ret = 0; - EXPECT_THROW(Call(s, jit, "call_few", ret), std::exception); - EXPECT_THROW(Call(s, jit, "call_many", ret), std::exception); - ret = 0; - Call(s, jit, "call_ok", ret); - EXPECT_EQ(ret, 4); - } -} - -TEST(language_contract, no_implicit_numeric_conversion) { - const char *src = R"( -function bad() - return "10" + 1 -end -)"; - auto sg = QuietState(); - ASSERT_NO_THROW(CompileString(sg.GetState(), src, QuietConfig())); - for (const auto jit: AllJitTypes()) { - int ret = 0; - try { - Call(sg.GetState(), jit, "bad", ret); - FAIL() << "\"10\" + 1 must not become 11"; - } catch (const std::exception &e) { - EXPECT_NE(std::string(e.what()).find("non-numeric"), std::string::npos) << e.what(); - EXPECT_EQ(ret, 0); - } - } -} - -TEST(language_contract, colon_call_inserts_receiver) { - ExpectRuns(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 -)", "colon_ok", 0); - ExpectCompileFails("function T:f(x)\n return x\nend\n", "Unsupported function name with method definition"); - ExpectCompileFails(R"( -local function f(self, x) - return x -end -function missing() - return f() -end -)", "wrong number of arguments"); -} - -TEST(language_contract, truth_and_precedence) { - ExpectRuns(R"( -function truth() - 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 - return 0 -end -)", "truth", 0); - ExpectRuns(R"( -function prec() - local a, b, c, d = 2, 5, 9, 4 - if a + b % 7 ~= 7 then return 1 end - if a * b + c // d ~= 12 then return 2 end - if 2 ^ 3 ^ 2 ~= 512 then return 3 end - if ("a" .. "b" .. "c") ~= "abc" then return 4 end - if (1 | 2 & 1) ~= 1 then return 5 end - return 0 -end -)", "prec", 0); -} - -TEST(language_contract, string_escapes_are_lua_not_c) { - ExpectRuns(R"( -function escapes() - if string.byte("\033") ~= 33 then return 1 end - if string.byte("\027") ~= 27 then return 2 end - if string.byte("\x1b") ~= 27 then return 3 end - if string.byte("\x1B") ~= 27 then return 4 end - return 0 -end -)", "escapes", 0); - ExpectCompileFails("function f() return \"\\x\" end\n", "invalid hexadecimal escape"); - ExpectCompileFails("function f() return \"\\x1\" end\n", "invalid hexadecimal escape"); - ExpectCompileFails("function f() return \"\\xzz\" end\n", "invalid hexadecimal escape"); - ExpectCompileFails("function f() return \"\\256\" end\n", "decimal escape too large"); -} - -TEST(language_contract, kernel_mode_rejects_float_literal_and_division) { - const auto kernel = KernelConfig(); - ExpectCompileFails("function f() return 3.14 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); - ExpectCompileFails("function f() return 1.0 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); - ExpectCompileFails("function f() return 1e2 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); - ExpectCompileFails("function f() return -1.5 end\n", "floating-point literal is forbidden in --mode=kernel", kernel); - ExpectCompileFails("function f() return 1 / 2 end\n", "float division '/' is forbidden in --mode=kernel", kernel); - ExpectCompileFails(R"( -function f(a, b) - return a / b -end -)", "float division '/' is forbidden in --mode=kernel", kernel); - ExpectRuns(R"( -function half() - local x = 1 / 2 - local y = 3.14 - if x == 0.5 and y > 3 then return 1 end - return 0 -end -)", "half", 1); - ExpectRuns(R"( -function k() - local n = 1 + 2 * 3 - local q = 7 // 2 - local s = "3.14" - if #s ~= 4 then return 0 end - if 0x10 ~= 16 then return 0 end - return n + q -end -)", "k", 10, kernel); -} - -TEST(language_contract, kernel_mode_allows_slash_inside_a_string) { - ExpectRuns(R"( -function slash_text() - local s = "1 / 2" - if s ~= "1 / 2" then return 0 end - return 1 -end -)", "slash_text", 1, KernelConfig()); -} diff --git a/test/test_package.cpp b/test/test_package.cpp index 251b6c11..ee366730 100644 --- a/test/test_package.cpp +++ b/test/test_package.cpp @@ -40,3 +40,68 @@ TEST(package, test_package_edge) { ASSERT_EQ(ret, 5000); }); } + +TEST(package, three_declaration_forms_cross_call) { + FakeluaStateGuard sg; + auto *s = sg.GetState(); + SetDebugLogLevel(s, LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + ASSERT_NO_THROW(CompileString(s, R"( +package "Left" +function add(a, b) + return a + b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +package = "Right" +function add(a, b) + return a - b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +package("Mid") +function add(a, b) + return a * b +end +)", cfg)); + ASSERT_NO_THROW(CompileString(s, R"( +function use_packages() + if Left.add(2, 3) ~= 5 then return 1 end + if Right.add(5, 1) ~= 4 then return 2 end + if Mid.add(3, 4) ~= 12 then return 3 end + return 0 +end +)", cfg)); + for (const auto jit: AllJitTypes()) { + int ret = -1; + Call(s, jit, "use_packages", ret); + EXPECT_EQ(ret, 0) << static_cast(jit); + } +} + +TEST(package, missing_declaration_still_compiles) { + FakeluaStateGuard sg; + auto *s = sg.GetState(); + SetDebugLogLevel(s, LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + ASSERT_NO_THROW(CompileString(s, "function bare() return 1 end\n", cfg)); + for (const auto jit: AllJitTypes()) { + int ret = 0; + Call(s, jit, "bare", ret); + EXPECT_EQ(ret, 1) << static_cast(jit); + } +} + +TEST(package, declaration_must_be_first) { + FakeluaStateGuard sg; + auto *s = sg.GetState(); + SetDebugLogLevel(s, LogLevel::Off); + try { + CompileString(s, "local x = 1\npackage \"Late\"\nfunction f() return x end\n", {.debug_mode = false}); + FAIL() << "a package declaration after another statement should fail"; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("unsupported file-level statement"), std::string::npos) << e.what(); + } +} diff --git a/test/test_string.cpp b/test/test_string.cpp index 572790b0..7b2ad18a 100644 --- a/test/test_string.cpp +++ b/test/test_string.cpp @@ -1035,6 +1035,45 @@ TEST(test_string, dump_load_preserves_scalar_captures_and_loaded_error_handlers) } } +TEST(test_string, decimal_and_hex_escapes_follow_lua) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + ASSERT_NO_THROW(CompileString(state.GetState(), R"( +function escapes() + if string.byte("\033") ~= 33 then return 1 end + if string.byte("\027") ~= 27 then return 2 end + if string.byte("\x1b") ~= 27 then return 3 end + if string.byte("\x1B") ~= 27 then return 4 end + return 0 +end +)", cfg)); + for (auto backend: AllJitTypes()) { + int64_t result = -1; + Call(state.GetState(), backend, "escapes", result); + EXPECT_EQ(result, 0) << JitTypeName(backend); + } + for (const char *src: {"function f() return \"\\x\" end\n", "function f() return \"\\x1\" end\n", "function f() return \"\\xzz\" end\n"}) { + FakeluaStateGuard bad; + SetDebugLogLevel(bad.GetState(), LogLevel::Off); + try { + CompileString(bad.GetState(), src, cfg); + FAIL() << src; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("invalid hexadecimal escape"), std::string::npos) << e.what(); + } + } + FakeluaStateGuard decimal; + SetDebugLogLevel(decimal.GetState(), LogLevel::Off); + try { + CompileString(decimal.GetState(), "function f() return \"\\256\" end\n", cfg); + FAIL() << "\\256 should be too large"; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("decimal escape too large"), std::string::npos) << e.what(); + } +} + TEST(test_string, alignment_lookahead_zero_hex_and_position_capture_replacements) { FakeluaStateGuard state; CompileFile(state.GetState(), "./string/test_string_binary_boundaries.lua", {});