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
14 changes: 0 additions & 14 deletions benchmark/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,6 @@ CPMAddPackage(
"BENCHMARK_ENABLE_INSTALL Off"
"BENCHMARK_ENABLE_LTO Off"
"BENCHMARK_ENABLE_NO_EXCEPTIONS Off"
"BENCHMARK_ENABLE_TESTING Off"
"BENCHMARK_ENABLE_TESTING Off"
"BENCHMARK_USE_LIBCXX Off"
"BENCHMARK_USE_LIBCXXABI Off"
"BENCHMARK_USE_SANITIZER Off"
"BENCHMARK_USE_VALGRIND Off"
"BENCHMARK_DOWNLOAD_DEPENDENCIES Off"
"BENCHMARK_ENABLE_GTEST_TESTS Off"
"BENCHMARK_ENABLE_EXCEPTIONS Off"
"BENCHMARK_ENABLE_INSTALL Off"
"BENCHMARK_ENABLE_LTO Off"
"BENCHMARK_ENABLE_NO_EXCEPTIONS Off"
"BENCHMARK_ENABLE_TESTING Off"
"BENCHMARK_ENABLE_TESTING Off"
"BENCHMARK_USE_LIBCXX Off"
"BENCHMARK_USE_LIBCXXABI Off"
"BENCHMARK_USE_SANITIZER Off"
Expand Down
152 changes: 83 additions & 69 deletions benchmark/README.md

Large diffs are not rendered by default.

152 changes: 83 additions & 69 deletions benchmark/README.zh.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions benchmark/benchmark_algo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1153,15 +1153,15 @@ static void BM_FakeLua_Vector3_INTERP(benchmark::State &state) {
static void BM_CPP_FloatPoly(benchmark::State &state) {
const int64_t n = state.range(0);
for ([[maybe_unused]] auto _: state) {
const double ret = CppFloatPoly(n);
double ret = CppFloatPoly(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_FloatPoly(benchmark::State &state) {
const int64_t n = state.range(0);
for ([[maybe_unused]] auto _: state) {
const double ret = CallLuaDouble(g_ctx.lua, "bench_float_poly", n);
double ret = CallLuaDouble(g_ctx.lua, "bench_float_poly", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down
5 changes: 3 additions & 2 deletions benchmark/benchmark_function.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,14 @@ constexpr const char *kMultiReturnScript = R"(
function bench_multi_return(n)
local total = 0
for i = 1, n do
total = total + inner_multi(i)
local a, b, c = inner_multi(i)
total = total + a + b + c
end
return total
end

function inner_multi(x)
return x + (x * 2) + (x * 3)
return x, x * 2, x * 3
end
)";

Expand Down
16 changes: 8 additions & 8 deletions benchmark/benchmark_math.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,15 @@ struct Ctx : RuntimeContext {
static void BM_CPP_MathTrig(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CppMathTrig(n);
double ret = CppMathTrig(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_MathTrig(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CallLuaDouble(g_ctx.lua, "bench_math_trig", n);
double ret = CallLuaDouble(g_ctx.lua, "bench_math_trig", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down Expand Up @@ -166,15 +166,15 @@ static void BM_FakeLua_MathTrig_INTERP(benchmark::State &state) {
static void BM_CPP_MathSqrt(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CppMathSqrt(n);
double ret = CppMathSqrt(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_MathSqrt(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CallLuaDouble(g_ctx.lua, "bench_math_sqrt", n);
double ret = CallLuaDouble(g_ctx.lua, "bench_math_sqrt", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down Expand Up @@ -211,15 +211,15 @@ static void BM_FakeLua_MathSqrt_INTERP(benchmark::State &state) {
static void BM_CPP_MathExpLog(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CppMathExpLog(n);
double ret = CppMathExpLog(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_MathExpLog(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CallLuaDouble(g_ctx.lua, "bench_math_exp_log", n);
double ret = CallLuaDouble(g_ctx.lua, "bench_math_exp_log", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down Expand Up @@ -256,15 +256,15 @@ static void BM_FakeLua_MathExpLog_INTERP(benchmark::State &state) {
static void BM_CPP_MathMinMax(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CppMathMinMax(n);
double ret = CppMathMinMax(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_MathMinMax(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const double ret = CallLuaDouble(g_ctx.lua, "bench_math_minmax", n);
double ret = CallLuaDouble(g_ctx.lua, "bench_math_minmax", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down
15 changes: 6 additions & 9 deletions benchmark/benchmark_string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -939,18 +939,15 @@ static void BM_FakeLua_ToNumber_INTERP(benchmark::State &state) {
static void BM_CPP_ToString(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
std::string total;
for (int64_t i = 1; i <= n; ++i) {
total += std::to_string(i);
}
benchmark::DoNotOptimize(total);
std::string ret = std::to_string(n);
benchmark::DoNotOptimize(ret);
}
}

static void BM_Lua_ToString(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
int64_t ret = CallLuaInt(g_ctx.lua, "bench_tostring", n);
std::string ret = CallLuaString(g_ctx.lua, "bench_tostring", n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down Expand Up @@ -987,7 +984,7 @@ static void BM_FakeLua_ToString_INTERP(benchmark::State &state) {
static void BM_CPP_StringFindPattern(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const int64_t ret = CppStringFindPattern(n);
int64_t ret = CppStringFindPattern(n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down Expand Up @@ -1031,7 +1028,7 @@ static void BM_FakeLua_StringFindPattern_INTERP(benchmark::State &state) {
int64_t ret = 0;
Call(g_ctx.flua, JIT_INTERP, "bench_string_find_pattern", ret, n);
benchmark::DoNotOptimize(ret);
VerifyEqual(ret, expected, "FakeLua GCC string.find pattern");
VerifyEqual(ret, expected, "FakeLua INTERP string.find pattern");
}
}

Expand All @@ -1040,7 +1037,7 @@ static void BM_FakeLua_StringFindPattern_INTERP(benchmark::State &state) {
static void BM_CPP_StringGmatch(benchmark::State &state) {
const int64_t n = state.range(0);
for (auto _: state) {
const int64_t ret = CppStringGmatch(n);
int64_t ret = CppStringGmatch(n);
benchmark::DoNotOptimize(ret);
}
}
Expand Down
6 changes: 1 addition & 5 deletions benchmark/benchmark_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,7 @@ end

constexpr const char *kTablePackScript = R"(
function bench_table_pack(n)
local t = {}
for i = 1, 10 do
t[i] = i
end
t.n = 10
local t = table.pack(n, 2, 3, 4, 5, 6, 7, 8, 9, 10)
return t.n
end
)";
Expand Down
5 changes: 2 additions & 3 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ endforeach ()
set(BOOST_CHARCONV_NO_QUADMATH ON)
# BOOST_INCLUDE_LIBRARIES 必须在 CPMAddPackage 之前 set:CPM OPTIONS 用 foreach(${OPTIONS})
# 展开,分号会被拆成多个参数。
set(BOOST_INCLUDE_LIBRARIES system charconv json regex stacktrace url uuid crc endian algorithm container filesystem serialization nowide hash2)
set(BOOST_INCLUDE_LIBRARIES system charconv json stacktrace url uuid crc endian algorithm container filesystem serialization nowide hash2)
CPMAddPackage(
NAME boost
GITHUB_REPOSITORY boostorg/boost
Expand Down Expand Up @@ -529,7 +529,6 @@ include_directories(${BOOST_SOURCE_DIR}/libs/system/include)
include_directories(${BOOST_SOURCE_DIR}/libs/assert/include)
include_directories(${BOOST_SOURCE_DIR}/libs/charconv/include)
include_directories(${BOOST_SOURCE_DIR}/libs/json/include)
include_directories(${BOOST_SOURCE_DIR}/libs/regex/include)
include_directories(${BOOST_SOURCE_DIR}/libs/stacktrace/include)
include_directories(${BOOST_SOURCE_DIR}/libs/url/include)
include_directories(${BOOST_SOURCE_DIR}/libs/uuid/include)
Expand Down Expand Up @@ -579,7 +578,7 @@ include_directories(${BOOST_SOURCE_DIR}/libs/pool/include)
include_directories(${BOOST_SOURCE_DIR}/libs/array/include)

# boost_charconv / boost_system / boost_json are compiled; other Boost libs are headers.
set(TARGET_LIB ${TARGET_LIB} OpenSSL::SSL OpenSSL::Crypto Threads::Threads event_core event_extra event_openssl hiredis ${FAKELUA_MYSQLCLIENT_LIB} boost_charconv boost_system boost_json Boost::regex Boost::stacktrace Boost::url Boost::uuid Boost::crc Boost::endian Boost::algorithm Boost::container Boost::filesystem Boost::serialization Boost::nowide Boost::hash2)
set(TARGET_LIB ${TARGET_LIB} OpenSSL::SSL OpenSSL::Crypto Threads::Threads event_core event_extra event_openssl hiredis ${FAKELUA_MYSQLCLIENT_LIB} boost_charconv boost_system boost_json Boost::stacktrace Boost::url Boost::uuid Boost::crc Boost::endian Boost::algorithm Boost::container Boost::filesystem Boost::serialization Boost::nowide Boost::hash2)
if (WIN32)
set(TARGET_LIB ${TARGET_LIB} crypt32 bcrypt ws2_32)
endif()
Expand Down
107 changes: 96 additions & 11 deletions src/native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Detailed API reference for all built-in native libraries. Each module lives in i
| utf8 | `utf8/` | UTF-8 encoding/decoding: `char`, `codepoint`, `codes`, `len`, `offset` |
| io | `io/` | File I/O: open, close, read, write, seek, popen, standard streams |
| net | `net/` | TCP/UDP networking: server/client with framed protocols, custom parsers, async event dispatch |
| http | `http/` | HTTP/1.1 client and server (Boost.Beast), driven by `runtime.tick()` |
| http | `http/` | HTTP/1.1 client and server (libevent), driven by `runtime.tick()` |
| url | `url/` | URL parse/format and percent-encoding (Boost.URL) |
| timer | `timer/` | Timers: one-shot, periodic heartbeat, driven by `runtime.tick()` |
| runtime | `runtime/` | Unified event loop pump: `runtime.tick()` drives every module that needs periodic progress |
Expand All @@ -29,12 +29,17 @@ Detailed API reference for all built-in native libraries. Each module lives in i
| crypto | `crypto/` | Cryptography: MD5/SHA1/SHA256, hex/base64, UUID, CRC-32, xxHash-64, AES/RC4/Blowfish/DES/3DES |
| csv | `csv/` | CSV decode/encode |
| json | `json/` | JSON encode/decode |
| yaml | `yaml/` | YAML decode/encode (yaml-cpp) |
| toml | `toml/` | TOML decode/encode (toml++) |
| xml | `xml/` | XML decode/encode (pugixml) |
| ini | `ini/` | INI decode/encode (inih) |
| mysql | `mysql/` | Async MySQL client: direct connect + connection pool |
| redis | `redis/` | Async Redis client (Boost.Redis) |
| redis | `redis/` | Async Redis client (hiredis + libevent) |
| sqlite | `sqlite/` | SQLite3 wrapper: exec, prepared statements, synchronous |
| process | `process/` | Subprocess spawn (Boost.Process v2); does not replace `os.execute` |
| process | `process/` | Subprocess spawn (POSIX `fork`/`execve`, Win32 `CreateProcessW`); does not replace `os.execute` |
| serialize | `serialize/` | Binary serialization with zigzag+varint encoding and string deduplication |
| protobuf | `protobuf/` | Runtime .proto parsing, standard protobuf3 wire encode/decode |
| log | `log/` | Per-State logging: `trace`, `debug`, `info`, `warn`, `error`, `critical`, `set_level`, `set_file` |
| object | `object/` | NativeObject Lua-side API: group management, object creation/lookup |

---
Expand All @@ -56,8 +61,8 @@ needed. Concretely:
registry are all per-`State`, so nothing registered in one `State` leaks into another;
- Reusable scratch buffers belong to whatever they serve: the linear staging areas used when
unpacking live on the `CircularBuffer` (`HeaderScratch` / `PayloadScratch`). WebSocket
uses Boost.Beast, which owns handshake and masking on the connection. Random number
generators that are only hit occasionally (temp file names) are plain locals.
runs on libevent (`bufferevent`), with handshake and frame masking owned per connection.
Random number generators that are only hit occasionally (temp file names) are plain locals.

The JIT error boundary chain (`jit_error_boundary.h`) lives on `State` too: the top of the chain
is `State::GetJitErrorBoundary()`, while the boundary objects themselves sit on the C++ stack.
Expand Down Expand Up @@ -130,11 +135,11 @@ There are no `thread_local` variables left.
| `math.ult(x, y)` | 2 | Unsigned less-than comparison |
| `math.random(...)` | vararg | Random number: 0-arg [0,1), 1-arg [1,u], 2-arg [l,u] |
| `math.randomseed(...)` | vararg | Seed the RNG |
| `math.erf(x)` | 1 | Error function (Boost.Math) |
| `math.erf(x)` | 1 | Error function |
| `math.erfc(x)` | 1 | Complementary error function |
| `math.gamma(x)` | 1 | Gamma function Γ(x) |
| `math.lgamma(x)` | 1 | Log-gamma ln Γ(x) |
| `math.clamp(x, lo, hi)` | 3 | Clamp `x` to `[lo, hi]` (Boost.Algorithm; all-integer args stay integer) |
| `math.clamp(x, lo, hi)` | 3 | Clamp `x` to `[lo, hi]` (all-integer args stay integer) |

**Constants:** `math.pi`, `math.huge`, `math.maxinteger`, `math.mininteger`

Expand Down Expand Up @@ -301,7 +306,7 @@ On Windows, `io.open` / `loadfile` / `dofile` / `os.getenv` / `os.tmpname` / Boo
| `line` | Newline delimited, auto-stripped |
| `fixed` | Fixed-length (requires `fixed_len = N`) |
| `raw` | Raw passthrough |
| `websocket` / `ws` | RFC 6455 WebSocket (text frames, Boost.Beast) |
| `websocket` / `ws` | RFC 6455 WebSocket (text frames, libevent) |

**Custom parser:** `parser = "Package.func"` (Lua) or `custom_parser_fn`/`custom_encoder_fn` (C++ `NetConfig`)

Expand Down Expand Up @@ -333,7 +338,7 @@ On Windows, `io.open` / `loadfile` / `dofile` / `os.getenv` / `os.tmpname` / Boo

**File:** `http/native_http.h` · **Registration:** `RegisterHttpLibraryApi`

HTTP/1.1 client and server on Boost.Beast, sharing the per-State Asio `io_context`. URLs are parsed with Boost.URL. `https://` uses TLS (OpenSSL); `http.get`/`http.post` verify the certificate by default. Drive completions with `runtime.tick()`.
HTTP/1.1 client and server on libevent (`bufferevent`), sharing the per-State libevent `event_base`. URLs are parsed with Boost.URL. `https://` uses TLS (OpenSSL); `http.get`/`http.post` verify the certificate by default. Drive completions with `runtime.tick()`.

**`http.request` config:** `{method, url, headers, body, timeout_ms, version, tls_verify, tls_ca}`

Expand Down Expand Up @@ -579,6 +584,67 @@ Boost.Container-backed structures stored on a NativeObject (C++ heap). They surv

---

## YAML

**File:** `yaml/native_yaml.h` · **Registration:** `RegisterYamlLibraryApi`

Backed by [yaml-cpp](https://github.com/jbeder/yaml-cpp). Scalar type inference covers integers, floats, booleans (`true`/`false`/`yes`/`no`/`on`/`off` and case variants), `null`/`~`, strings, sequences (arrays), and mappings (tables).

| Function | Args | Description |
|----------|------|-------------|
| `yaml.decode(str)` | 1 | YAML string → Lua value |
| `yaml.encode(value)` | 1 | Lua value → YAML string |

---

## TOML

**File:** `toml/native_toml.h` · **Registration:** `RegisterTomlLibraryApi`

Backed by [toml++](https://github.com/marzer/tomlplusplus) (header-only). Supports TOML strings, integers, floats, booleans, dates/times, arrays, and tables.

| Function | Args | Description |
|----------|------|-------------|
| `toml.decode(str)` | 1 | TOML string → Lua value |
| `toml.encode(value)` | 1 | Lua value → TOML string (top-level value must be a table) |

---

## XML

**File:** `xml/native_xml.h` · **Registration:** `RegisterXmlLibraryApi`

Backed by [pugixml](https://github.com/zeux/pugixml).

**Decoding conventions:**
- Element node → table
- Attributes → `table["_attr_<name>"] = value`
- Text content → `table["_text"] = value`
- Child elements grouped by tag name; repeated siblings with the same tag → array
- Plain text node → string directly

| Function | Args | Description |
|----------|------|-------------|
| `xml.decode(str)` | 1 | XML string → Lua value (root element table) |
| `xml.encode(value)` | 1 | Lua value → XML string |

---

## INI

**File:** `ini/native_ini.h` · **Registration:** `RegisterIniLibraryApi`

Backed by [inih](https://github.com/benhoyt/inih).

**Layout:** `ini.decode` returns `table[section][key] = value` with automatic number/boolean/null/string type inference. `ini.encode` treats each top-level subtable as a `[section]`.

| Function | Args | Description |
|----------|------|-------------|
| `ini.decode(str)` | 1 | INI string → Lua value |
| `ini.encode(value)` | 1 | Lua value → INI string (top-level table of section subtables) |

---

## MySQL

**Files:** `mysql/native_mysql.h`, `mysql/native_mysql_pool.h` · **Registration:** `RegisterMysqlLibraryApi`, `RegisterMysqlPoolApi`
Expand Down Expand Up @@ -655,7 +721,7 @@ number (0/1); convert as needed.

**File:** `redis/native_redis.h` · **Registration:** `RegisterRedisLibraryApi`

Async client on Boost.Redis. Reconnect and health-checks are off so a failed connect completes once. Drive with `runtime.tick()`.
Async client on hiredis with the libevent adapter (sharing the per-State `event_base`). Reconnect and health-checks are off so a failed connect completes once. Drive with `runtime.tick()`.

**`redis.connect` config:** `{host, port, user, password, db, timeout_ms}`

Expand Down Expand Up @@ -697,7 +763,7 @@ Connect does not send `HELLO 3`, so Redis 4+ works; AUTH/SELECT are issued when

**File:** `process/native_process.h` · **Registration:** `RegisterProcessLibraryApi`

Boost.Process v2. This does **not** replace `os.execute` (that still returns Lua's `(status, how, code)` triple).
Implemented with POSIX `fork`/`execve`/`waitpid` (and Win32 `CreateProcessW` on Windows). This does **not** replace `os.execute` (that still returns Lua's `(status, how, code)` triple).

| Function | Args | Description |
|----------|------|-------------|
Expand Down Expand Up @@ -744,6 +810,25 @@ Boost.Process v2. This does **not** replace `os.execute` (that still returns Lua

---

## Log

**File:** `log/native_log.h` · **Registration:** `RegisterLogLibraryApi`

Per-`State` structured logging tagged as `"script"`. Multiple arguments are tab-separated (like `print`). Level values follow `LogLevel`: `0` Trace, `1` Debug, `2` Info, `3` Warn, `4` Error, `5` Critical.

| Function | Args | Description |
|----------|------|-------------|
| `log.trace(msg, ...)` | vararg (≥1) | Log at Trace level |
| `log.debug(msg, ...)` | vararg (≥1) | Log at Debug level |
| `log.info(msg, ...)` | vararg (≥1) | Log at Info level |
| `log.warn(msg, ...)` | vararg (≥1) | Log at Warn level |
| `log.error(msg, ...)` | vararg (≥1) | Log at Error level |
| `log.critical(msg, ...)` | vararg (≥1) | Log at Critical level |
| `log.set_level(level)` | 1 | Set minimum log level for this `State` (integer `0`–`5`) |
| `log.set_file(path)` | 1 | Set rotating log file path for this `State` (empty string disables file output, console only) |

---

## NativeObject (Lua-side API)

**File:** `object/native_object.h` · **Registration:** `RegisterNativeObjectApi`
Expand Down
Loading
Loading