From e1e7a6126bb7626481bffb25b206ec46ae141822 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 02:53:21 +0000 Subject: [PATCH] chore: remove Boost::regex, fix benchmarks/warnings, and refresh docs Co-authored-by: esrrhs --- benchmark/CMakeLists.txt | 14 --- benchmark/README.md | 152 +++++++++++++++++-------------- benchmark/README.zh.md | 152 +++++++++++++++++-------------- benchmark/benchmark_algo.cpp | 4 +- benchmark/benchmark_function.cpp | 5 +- benchmark/benchmark_math.cpp | 16 ++-- benchmark/benchmark_string.cpp | 15 ++- benchmark/benchmark_table.cpp | 6 +- src/CMakeLists.txt | 5 +- src/native/README.md | 107 +++++++++++++++++++--- src/native/README.zh.md | 42 ++++++--- src/util/string_util.cpp | 115 ++++++++++++++++++++++- test/test_common.cpp | 53 +++++++++++ test/test_jitter.cpp | 4 +- test/test_net.cpp | 7 +- 15 files changed, 486 insertions(+), 211 deletions(-) diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index 21ee4aa5..a63e3df3 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -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" diff --git a/benchmark/README.md b/benchmark/README.md index 0ca2309d..7379911d 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -1,102 +1,116 @@ # Benchmark results -These CPU times were measured on 2026-11-30 with `build/bin/bench_mark` built Release (`-O3 -DNDEBUG`). They replace the older notes that said the interpreter had no tail calls and that `string.gsub` used an ECMAScript Boost.Regex engine. +These CPU times were measured on 2026-12-02 with `bench_mark` built Release (`-O3 -DNDEBUG`) after the pattern engine (PR #68), native call-site fast path (PR #70), and zero-copy `string.find` / class-prefix scan (PR #71) optimizations, plus benchmark fixes for `MultiReturn`, `TablePack`, and `ToString`. ## Environment -- Date: 2026-11-30 -- Machine: AMD EPYC 7551 32-Core Processor, 16 vCPU, 2.0 GHz -- Build: GCC 16.2.0, Release `-O3 -DNDEBUG` -- Lua: 5.4.7 -- Command: `./build/bin/bench_mark --benchmark_min_time=0.2s --benchmark_repetitions=1` +- Date: 2026-12-02 +- Machine: Intel(R) Xeon(R) Processor, 4 vCPU, 2.4 GHz (pinned to core 0) +- Build: GCC 13.3.0, Release `-O3 -DNDEBUG` +- Lua: 5.4.8 +- Command: `taskset -c 0 ./bench_mark --benchmark_min_time=0.2s --benchmark_repetitions=1` -Each row uses the largest registered argument. `INTERP/Lua` is interpreter time divided by Lua time, so a value above 1 means the interpreter is slower. `GCC/Lua` and `TCC/Lua` are Lua time divided by that backend, so a value above 1 means FakeLua is faster. C++ empty loops that the compiler deletes are not used as a GCC comparison. +Each row uses the largest registered argument. `INTERP/Lua` is interpreter time divided by Lua time, so a value above 1 means the interpreter is slower and a value below 1 means the interpreter is faster. `GCC/Lua` and `TCC/Lua` are Lua time divided by that backend, so a value above 1 means FakeLua is faster. C++ empty loops that the compiler deletes are not used as a GCC comparison. ## What this run shows -1. **Named calls and closures are close to Lua.** Interpreter EmptyCall takes 1.67x Lua, Closure 1.03x, and Recursion 1.96x. The old 6–8x gap is gone. A call site caches the resolved interpreter prototype, so the hot path does not hash the name on every call, and a closure with a few upvalues no longer heap-allocates the upvalue pointer array. -2. **An exact self tail call reuses the current frame.** The TailRecursion benchmark was removed from the suite, so it has no row here. Non-tail recursion still costs more: Fibonacci n=32 takes 3.09x Lua on the interpreter. Variadic calls take 4.21x because the extra arguments are still packed into a `Multi`. -3. **Patterns are Lua 5.4 patterns, not ECMAScript.** Interpreter `StringGsub` takes 1.33x Lua, and GCC does not beat Lua there (0.78x). `StringFindPattern` is still slower: 3.29x on the interpreter, and GCC reaches only 0.35x Lua's speed. The next string hotspot is the pattern engine, not another pass on GCC Fibonacci. -4. **GCC still leads numeric hotspots; use these ratios.** Fibonacci is 53.48x Lua, FloatPoly is 24.40x and matches handwritten C++. Sum is 16.73x, not the 30x figure from the old write-up. -5. **Allocation without GC can beat Lua on the interpreter.** TableChurn, StringChurn, and MixedAlloc are all faster than Lua. +1. **GCC beats Lua 5.4.8 on 50 of 51 Lua-compared benchmarks.** Numeric hotspots lead by **12x–53x** (`Recursion` 53.15x, `Fibonacci` 45.06x, `Popcount` 24.08x, `MathSqrt` 16.27x, `FloatPoly` 16.02x and matching handwritten C++, `Sum` 13.17x, `Vector3` 12.00x). The only scenario where GCC trails Lua is single-call `TablePack` (`247 ns` vs `211 ns`, 0.85x), which now invokes real variadic `table.pack` with 10 arguments. +2. **String search and Lua 5.4 pattern matching now beat Lua across the board on GCC.** Zero-copy `string.find`, `memchr`+`memcmp` plain scanning, literal-prefix fast scan, and first-byte character-class bitmaps lifted `StringFind` (`plain=true`) to **3.22x** on GCC (and **2.56x** on TCC), `StringFindLiteral` to **2.77x** on GCC (**2.28x** TCC, **0.42x** INTERP), `StringGmatch` to **1.65x** on GCC, `StringGsub` to **1.12x** on GCC, and `StringFindPattern` to **1.06x** on GCC. Delegating TCC's byte-loop helpers to `-O3` host code lifted TCC `StringLower`/`StringUpper` to **7.58x** / **6.87x** Lua. +3. **Native call-site caching closed the interpreter's native-call gap.** Caching `NativeFuncEntry` in the interpreter and avoiding redundant vararg boxing brought `MathTrig`/`MathSqrt`/`MathExpLog`/`MathMinMax` down to **1.22x–1.38x** Lua, `TableInsert` to **1.22x**, `Variadic` to **2.45x**, and pushed `TableRemove` (**0.91x**), `StringFormat` (**0.73x**), `StringByte` (**0.74x**), and `ToString` (**0.93x**) faster than Lua 5.4.8 on the interpreter. +4. **Remaining interpreter gaps are table-access and loop dispatch heavy.** `Vector3` (3.42x), `NestedTable` (2.97x), `Fibonacci` (2.82x), `BubbleSort` (2.59x), `InsertionSort` (2.35x), and `BinarySearch` (2.21x) are the main remaining >2x scenarios on INTERP. +5. **Fixed benchmarks reflect real costs.** `MultiReturn` now actually returns and unpacks 3 values (`x, x * 2, x * 3`) instead of summing inside the callee (GCC 3.30x, INTERP 2.39x); `TablePack` now calls `table.pack(...)` directly instead of manually building a table; `BM_CPP_ToString` now converts once instead of looping `n` times (`5.4 ns`). +6. **Allocation without GC beats Lua on all three backends, and `NativeObject` field ops stay around 7–14 ns.** `TableChurn`, `StringChurn`, and `MixedAlloc` are 0.40x–0.56x Lua on INTERP and 7.56x–12.64x on GCC. Deep 8-level `NativeObject` leaf writes (`11.6 ns`) match shallow `SetInt` (`10.9 ns`). ### Algorithms -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| Fibonacci | 32 | 290.1 ms | 896.3 ms | 3.09x | 5.4 ms | 53.48x | 222.4 ms | 1.30x | -| Sum | 5000000 | 33.8 ms | 76.6 ms | 2.27x | 2.0 ms | 16.73x | 16.2 ms | 2.08x | -| Popcount | 100000 | 17.5 ms | 58.6 ms | 3.35x | 1.0 ms | 16.91x | 3.2 ms | 5.55x | -| FloatPoly | 1000000 | 91.2 ms | 131.1 ms | 1.44x | 3.7 ms | 24.40x | 13.8 ms | 6.59x | -| BubbleSort | 200 | 1.5 ms | 4.2 ms | 2.73x | 159.7 μs | 9.60x | 1.5 ms | 1.04x | -| Sieve | 5000 | 334.1 μs | 828.2 μs | 2.48x | 62.9 μs | 5.31x | 467.2 μs | 0.72x | -| InsertionSort | 200 | 712.5 μs | 2.9 ms | 4.12x | 91.5 μs | 7.79x | 1.1 ms | 0.66x | -| BinarySearch | 1000 | 621.6 μs | 1.8 ms | 2.96x | 273.5 μs | 2.27x | 874.3 μs | 0.71x | -| Vector3 | 1000000 | 213.3 ms | 603.5 ms | 2.83x | 12.1 ms | 17.66x | 147.1 ms | 1.45x | -| MatMul | — | 4.4 μs | 7.5 μs | 1.71x | 1.5 μs | 2.92x | 4.0 μs | 1.10x | -| GCD | 832040/514229 | 551 ns | 1.8 μs | 3.23x | 354 ns | 1.56x | 806 ns | 0.68x | -| PowMod | 2/1000/1000000007 | 681 ns | 1.5 μs | 2.23x | 312 ns | 2.18x | 824 ns | 0.83x | -| FastPow | 2/1000/1000000007 | 753 ns | 1.5 μs | 2.05x | 322 ns | 2.34x | 541 ns | 1.39x | +| Fibonacci | 32 | 112.9 ms | 318.9 ms | 2.82x | 2.51 ms | 45.06x | 63.6 ms | 1.77x | +| Sum | 5000000 | 16.9 ms | 37.0 ms | 2.20x | 1.28 ms | 13.17x | 6.00 ms | 2.81x | +| Popcount | 100000 | 7.50 ms | 13.9 ms | 1.85x | 311.5 μs | 24.08x | 1.11 ms | 6.73x | +| FloatPoly | 1000000 | 24.5 ms | 38.4 ms | 1.57x | 1.53 ms | 16.02x | 22.3 ms | 1.10x | +| BubbleSort | 200 | 387.1 μs | 1.00 ms | 2.59x | 68.0 μs | 5.69x | 551.4 μs | 0.70x | +| Sieve | 5000 | 143.6 μs | 286.5 μs | 2.00x | 30.7 μs | 4.68x | 158.6 μs | 0.91x | +| InsertionSort | 200 | 273.8 μs | 642.2 μs | 2.35x | 39.5 μs | 6.93x | 426.7 μs | 0.64x | +| BinarySearch | 1000 | 210.0 μs | 464.8 μs | 2.21x | 90.1 μs | 2.33x | 356.9 μs | 0.59x | +| Vector3 | 1000000 | 43.6 ms | 149.2 ms | 3.42x | 3.63 ms | 12.00x | 81.3 ms | 0.54x | +| MatMul | — | 1.20 μs | 2.01 μs | 1.68x | 310 ns | 3.86x | 1.27 μs | 0.94x | +| GCD | 2147483647/1073741823 | 45.7 ns | 85.9 ns | 1.88x | 44.5 ns | 1.03x | 67.9 ns | 0.67x | +| PowMod | 1234567/7654321/1000000007 | 383 ns | 588 ns | 1.54x | 198 ns | 1.94x | 320 ns | 1.20x | +| FastPow | 1234567/7654321/1000000007 | 364 ns | 552 ns | 1.52x | 201 ns | 1.81x | 258 ns | 1.41x | ### Calls -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| EmptyCall | 100000 | 4.7 ms | 7.8 ms | 1.67x | 384.8 μs | 12.20x | 6.4 ms | 0.74x | -| Recursion | 25 | 15.7 ms | 30.9 ms | 1.96x | 176.4 μs | 89.22x | 8.4 ms | 1.88x | -| Closure | 1000 | 250.5 μs | 257.2 μs | 1.03x | 12.7 μs | 19.76x | 215.0 μs | 1.16x | -| MultiReturn | 10000 | 721.8 μs | 1.1 ms | 1.51x | 31.4 μs | 23.01x | 388.1 μs | 1.86x | -| Variadic | 1 | 661 ns | 2.8 μs | 4.21x | 267 ns | 2.48x | 771 ns | 0.86x | +| EmptyCall | 100000 | 2.23 ms | 3.22 ms | 1.45x | 127.6 μs | 17.45x | 2.59 ms | 0.86x | +| Recursion | 25 | 4.85 ms | 10.9 ms | 2.25x | 91.2 μs | 53.15x | 2.21 ms | 2.19x | +| Closure | 1000 | 89.8 μs | 97.0 μs | 1.08x | 6.26 μs | 14.34x | 79.9 μs | 1.12x | +| MultiReturn | 10000 | 277.3 μs | 663.8 μs | 2.39x | 83.9 μs | 3.30x | 984.7 μs | 0.28x | +| Variadic | 1 | 204 ns | 499 ns | 2.45x | 85.1 ns | 2.39x | 319 ns | 0.64x | ### Strings -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| StringLen | 10000 | 2.4 μs | 1.0 μs | 0.44x | 964 ns | 2.45x | 1.0 μs | 2.31x | -| StringSub | 10000 | 3.7 μs | 2.0 μs | 0.53x | 1.9 μs | 1.95x | 1.9 μs | 1.96x | -| StringLower | 10000 | 15.9 μs | 2.9 μs | 0.18x | 2.2 μs | 7.08x | 50.5 μs | 0.31x | -| StringUpper | 10000 | 15.8 μs | 2.7 μs | 0.17x | 2.2 μs | 7.20x | 50.9 μs | 0.31x | -| StringFind | 10000 | 2.6 μs | 2.3 μs | 0.90x | 3.2 μs | 0.81x | 19.7 μs | 0.13x | -| StringGsub | 1000 | 43.6 μs | 57.8 μs | 1.33x | 55.7 μs | 0.78x | 55.8 μs | 0.78x | -| StringFindPattern | 1000 | 872.6 μs | 2.9 ms | 3.29x | 2.5 ms | 0.35x | 2.4 ms | 0.36x | -| StringGmatch | 1000 | 1.2 ms | 2.4 ms | 1.96x | 1.6 ms | 0.77x | 1.8 ms | 0.67x | -| StringFormat | 500 | 186.0 μs | 259.3 μs | 1.39x | 6.6 μs | 27.98x | 44.0 μs | 4.23x | -| StringRep | 1000 | 5.3 μs | 4.7 μs | 0.88x | 4.5 μs | 1.18x | 5.4 μs | 0.98x | -| StringReverse | 10000 | 12.8 μs | 11.2 μs | 0.87x | 8.2 μs | 1.56x | 44.2 μs | 0.29x | -| StringByte | 1000 | 751 ns | 1.0 μs | 1.36x | 455 ns | 1.65x | 540 ns | 1.39x | -| StringChar | 500 | 81.6 μs | 157.7 μs | 1.93x | 12.0 μs | 6.79x | 80.4 μs | 1.02x | -| ToNumber | 1 | 213 ns | 570 ns | 2.68x | 234 ns | 0.91x | 537 ns | 0.40x | -| ToString | 500 | 515 ns | 577 ns | 1.12x | 207 ns | 2.48x | 311 ns | 1.66x | +| StringLen | 10000 | 781 ns | 217 ns | 0.28x | 199 ns | 3.93x | 218 ns | 3.58x | +| StringSub | 10000 | 1.21 μs | 412 ns | 0.34x | 338 ns | 3.60x | 382 ns | 3.18x | +| StringLower | 10000 | 5.32 μs | 779 ns | 0.15x | 699 ns | 7.61x | 701 ns | 7.58x | +| StringUpper | 10000 | 5.27 μs | 770 ns | 0.15x | 709 ns | 7.42x | 767 ns | 6.87x | +| StringFind | 10000 | 785 ns | 330 ns | 0.42x | 244 ns | 3.22x | 306 ns | 2.56x | +| StringFindLiteral | 10000 | 793 ns | 337 ns | 0.42x | 287 ns | 2.77x | 348 ns | 2.28x | +| StringGsub | 1000 | 16.0 μs | 14.4 μs | 0.90x | 14.4 μs | 1.12x | 14.0 μs | 1.14x | +| StringFindPattern | 1000 | 311.1 μs | 441.6 μs | 1.42x | 294.5 μs | 1.06x | 463.0 μs | 0.67x | +| StringGmatch | 1000 | 429.6 μs | 523.1 μs | 1.22x | 260.3 μs | 1.65x | 352.2 μs | 1.22x | +| StringFormat | 500 | 48.0 μs | 35.2 μs | 0.73x | 3.29 μs | 14.56x | 21.4 μs | 2.25x | +| StringRep | 1000 | 2.70 μs | 1.41 μs | 0.52x | 2.18 μs | 1.24x | 3.40 μs | 0.80x | +| StringReverse | 10000 | 4.37 μs | 3.08 μs | 0.71x | 2.92 μs | 1.50x | 5.39 μs | 0.81x | +| StringByte | 1000 | 186 ns | 138 ns | 0.74x | 82.8 ns | 2.25x | 107 ns | 1.74x | +| StringChar | 500 | 27.3 μs | 29.7 μs | 1.09x | 5.67 μs | 4.82x | 31.8 μs | 0.86x | +| ToNumber | 1 | 69.6 ns | 101 ns | 1.45x | 68.0 ns | 1.02x | 119 ns | 0.59x | +| ToString | 500 | 127 ns | 118 ns | 0.93x | 54.2 ns | 2.35x | 84.0 ns | 1.52x | ### Tables -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| TableCreate | 5000 | 132.2 μs | 263.1 μs | 1.99x | 51.7 μs | 2.56x | 266.1 μs | 0.50x | -| TableInsert | 5000 | 540.7 μs | 1.7 ms | 3.20x | 64.6 μs | 8.37x | 382.7 μs | 1.41x | -| TableRemove | 5000 | 902.4 μs | 2.0 ms | 2.27x | 62.1 μs | 14.53x | 628.7 μs | 1.44x | -| TableConcat | 1000 | 393.5 μs | 324.5 μs | 0.82x | 29.6 μs | 13.28x | 135.2 μs | 2.91x | -| TableSort | 1000 | 368.5 μs | 152.7 μs | 0.41x | 100.2 μs | 3.68x | 158.2 μs | 2.33x | -| TableMove | 5000 | 231.5 μs | 336.7 μs | 1.45x | 98.5 μs | 2.35x | 533.8 μs | 0.43x | -| TablePack | 1 | 1.4 μs | 952 ns | 0.67x | 420 ns | 3.37x | 1.2 μs | 1.21x | -| HashInsert | 1000 | 570.9 μs | 402.9 μs | 0.71x | 82.5 μs | 6.92x | 316.6 μs | 1.80x | -| HashLookup | 1000 | 442.5 μs | 419.3 μs | 0.95x | 38.5 μs | 11.50x | 183.9 μs | 2.41x | -| NestedTable | 10000 | 2.5 ms | 10.0 ms | 3.95x | 798.1 μs | 3.17x | 5.6 ms | 0.45x | +| TableCreate | 5000 | 58.3 μs | 110.2 μs | 1.89x | 21.7 μs | 2.68x | 98.6 μs | 0.59x | +| TableInsert | 5000 | 172.0 μs | 210.4 μs | 1.22x | 24.8 μs | 6.93x | 130.2 μs | 1.32x | +| TableRemove | 5000 | 325.4 μs | 294.5 μs | 0.91x | 31.6 μs | 10.30x | 240.8 μs | 1.35x | +| TableConcat | 1000 | 112.8 μs | 59.3 μs | 0.53x | 15.9 μs | 7.09x | 44.7 μs | 2.53x | +| TableSort | 1000 | 180.5 μs | 71.8 μs | 0.40x | 48.2 μs | 3.75x | 65.2 μs | 2.77x | +| TableMove | 5000 | 99.8 μs | 156.1 μs | 1.56x | 47.6 μs | 2.10x | 207.1 μs | 0.48x | +| TablePack | 1 | 211 ns | 318 ns | 1.51x | 247 ns | 0.85x | 349 ns | 0.61x | +| HashInsert | 1000 | 174.3 μs | 97.5 μs | 0.56x | 32.9 μs | 5.29x | 125.1 μs | 1.39x | +| HashLookup | 1000 | 128.2 μs | 83.4 μs | 0.65x | 22.3 μs | 5.74x | 68.1 μs | 1.88x | +| NestedTable | 10000 | 880.3 μs | 2.61 ms | 2.97x | 331.9 μs | 2.65x | 2.12 ms | 0.41x | ### Math -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| MathTrig | 100000 | 28.8 ms | 65.7 ms | 2.28x | 9.1 ms | 3.15x | 18.6 ms | 1.55x | -| MathSqrt | 100000 | 7.5 ms | 20.7 ms | 2.78x | 322.6 μs | 23.13x | 4.8 ms | 1.54x | -| MathExpLog | 100000 | 25.7 ms | 69.6 ms | 2.71x | 5.4 ms | 4.75x | 12.9 ms | 2.00x | -| MathMinMax | 100000 | 34.6 ms | 103.4 ms | 2.99x | 4.6 ms | 7.50x | 17.5 ms | 1.97x | +| MathTrig | 100000 | 5.78 ms | 7.57 ms | 1.31x | 963.4 μs | 6.00x | 9.05 ms | 0.64x | +| MathSqrt | 100000 | 2.47 ms | 3.02 ms | 1.22x | 152.0 μs | 16.27x | 2.42 ms | 1.02x | +| MathExpLog | 100000 | 5.16 ms | 7.11 ms | 1.38x | 657.1 μs | 7.85x | 7.14 ms | 0.72x | +| MathMinMax | 100000 | 8.00 ms | 10.5 ms | 1.32x | 742.6 μs | 10.77x | 6.85 ms | 1.17x | ### Allocation -| Scenario | Args | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| Scenario | Args | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| TableChurn | 1000 | 587.6 μs | 324.2 μs | 0.55x | 39.5 μs | 14.88x | 314.6 μs | 1.87x | -| StringChurn | 1000 | 1.1 ms | 775.7 μs | 0.69x | 52.9 μs | 21.28x | 319.3 μs | 3.53x | -| MixedAlloc | 1000 | 1.1 ms | 766.8 μs | 0.68x | 68.6 μs | 16.33x | 398.8 μs | 2.81x | - +| TableChurn | 1000 | 161.3 μs | 90.7 μs | 0.56x | 21.3 μs | 7.56x | 110.6 μs | 1.46x | +| StringChurn | 1000 | 334.1 μs | 133.5 μs | 0.40x | 26.4 μs | 12.64x | 97.2 μs | 3.44x | +| MixedAlloc | 1000 | 315.7 μs | 176.3 μs | 0.56x | 36.3 μs | 8.70x | 153.5 μs | 2.06x | + +### NativeObject + +C++ host-side `NativeObject` hot-path operations (no Lua counterpart). + +| Benchmark | CPU Time | +|---|---:| +| `BM_NativeObjectSetInt` | 10.9 ns | +| `BM_NativeObjectGetInt` | 7.0 ns | +| `BM_NativeObjectSetString` | 13.6 ns | +| `BM_NativeObjectCreateDestroy` | 152 ns | +| `BM_NativeObjectSetObject` | 11.3 ns | +| `BM_NativeObjectDeepLeafWrite` | 11.6 ns | diff --git a/benchmark/README.zh.md b/benchmark/README.zh.md index 0ddb90af..db266d69 100644 --- a/benchmark/README.zh.md +++ b/benchmark/README.zh.md @@ -1,102 +1,116 @@ # 性能基准测试结果 -本文件记录 2026-11-30 在本机以 Release(`-O3 -DNDEBUG`)运行 `build/bin/bench_mark` 的 CPU 时间。旧文档里的「解释器没有尾调用优化」和「`string.gsub` 走 ECMAScript Boost.Regex」已经过时,下面的数字取代它们。 +本文件记录 2026-12-02 在本机以 Release(`-O3 -DNDEBUG`)运行 `bench_mark` 的 CPU 时间,覆盖模式引擎优化(PR #68)、跨后端原生调用快路径(PR #70)、`string.find` 零拷贝与首字节位图快扫(PR #71),以及 `MultiReturn`、`TablePack`、`ToString` 失真基准用例的修正。 ## 运行环境 -- 日期:2026-11-30 -- 机器:AMD EPYC 7551 32-Core Processor,16 vCPU,2.0 GHz -- 构建:GCC 16.2.0,Release `-O3 -DNDEBUG` -- Lua:5.4.7 -- 命令:`./build/bin/bench_mark --benchmark_min_time=0.2s --benchmark_repetitions=1` +- 日期:2026-12-02 +- 机器:Intel(R) Xeon(R) Processor,4 vCPU,2.4 GHz(`taskset -c 0` 绑核) +- 构建:GCC 13.3.0,Release `-O3 -DNDEBUG` +- Lua:5.4.8 +- 命令:`taskset -c 0 ./bench_mark --benchmark_min_time=0.2s --benchmark_repetitions=1` -每个场景取基准注册的最大参数。`INTERP/Lua` 是解释器耗时除以 Lua 耗时,大于 1 表示解释器更慢。`GCC/Lua` 和 `TCC/Lua` 是 Lua 耗时除以对应后端,大于 1 表示 FakeLua 更快。被编译器折叠掉的 C++ 空循环不拿来和 GCC 比。 +每个场景取基准注册的最大参数。`INTERP/Lua` 是解释器耗时除以 Lua 耗时,大于 1 表示解释器更慢、小于 1 表示解释器更快。`GCC/Lua` 和 `TCC/Lua` 是 Lua 耗时除以对应后端,大于 1 表示 FakeLua 更快。被编译器折叠掉的 C++ 空循环不拿来和 GCC 比。 ## 这次测量说明什么 -1. **命名调用和闭包已经接近 Lua。** EmptyCall 的解释器耗时是 Lua 的 1.67 倍,Closure 是 1.03 倍,Recursion 是 1.96 倍。旧文档里的 6–8 倍不再成立。调用点会缓存解释器原型,热路径不再每次查哈希表;创建少量 upvalue 的闭包也不再为 upvalue 指针数组做堆分配。 -2. **精确自尾调用会复用当前帧。** 套件里的 TailRecursion 基准已经删除,所以这里没有单独一行。非尾递归仍然更贵:Fibonacci n=32 的解释器耗时是 Lua 的 3.09 倍。变参调用是 4.21 倍,因为还要装箱成 `Multi`。 -3. **模式匹配是 Lua 5.4 pattern,不是 ECMAScript。** `StringGsub` 解释器耗时是 Lua 的 1.33 倍,GCC 也没有超过 Lua(0.78 倍)。`StringFindPattern` 仍慢,解释器 3.29 倍、GCC 只有 Lua 的 0.35 倍速度。下一步字符串热点应放在 pattern 引擎,而不是再挤 GCC 的 Fibonacci。 -4. **GCC 数值热点仍然领先,但倍数以这次为准。** Fibonacci 53.48 倍,FloatPoly 24.40 倍且与手写 C++ 持平。Sum 是 16.73 倍,不再沿用旧文档的 30 倍。 -5. **没有 GC 的分配场景解释器可以快过 Lua。** TableChurn、StringChurn、MixedAlloc 的解释器耗时都低于 Lua。 +1. **GCC 后端在 51 个对照 Lua 5.4.8 的基准场景中赢下 50 项。** 数值热点领先 **12x–53x**(`Recursion` 53.15x、`Fibonacci` 45.06x、`Popcount` 24.08x、`MathSqrt` 16.27x、`FloatPoly` 16.02x 且与手写 C++ 持平、`Sum` 13.17x、`Vector3` 12.00x)。GCC 唯一略慢于 Lua 的是单次调用 `TablePack`(`247 ns` vs `211 ns`,0.85x),该用例已修正为真实调用 10 参变参 `table.pack`。 +2. **字符串查找与 Lua 5.4 模式匹配在 GCC 上已全面反超 Lua。** 零拷贝 `string.find`、`memchr`+`memcmp` 纯串扫描、字面前缀快扫与首字节字符类位图将 `StringFind`(`plain=true`)拉升到 GCC **3.22x**(TCC **2.56x**)、`StringFindLiteral` 达 GCC **2.77x**(TCC **2.28x**,INTERP **0.42x**)、`StringGmatch` 达 GCC **1.65x**、`StringGsub` 达 GCC **1.12x**、`StringFindPattern` 达 GCC **1.06x**。TCC 将字节循环辅助切回 `-O3` 宿主实现后,`StringLower`/`StringUpper` 提升至 Lua 的 **7.58x** / **6.87x**。 +3. **原生函数调用点缓存显著收窄了解释器的原生调用开销。** 解释器缓存 `NativeFuncEntry` 并消除冗余变参装箱后,`MathTrig`/`MathSqrt`/`MathExpLog`/`MathMinMax` 收敛到 Lua 的 **1.22x–1.38x**,`TableInsert` 降至 **1.22x**,`Variadic` 降至 **2.45x**,`TableRemove`(**0.91x**)、`StringFormat`(**0.73x**)、`StringByte`(**0.74x**)、`ToString`(**0.93x**)已反超 Lua 5.4.8。 +4. **解释器剩余的 >2x 落差主要集中在表访问与循环派发。** 包括 `Vector3`(3.42x)、`NestedTable`(2.97x)、`Fibonacci`(2.82x)、`BubbleSort`(2.59x)、`InsertionSort`(2.35x)和 `BinarySearch`(2.21x)。 +5. **修正后的基准用例反映真实语义开销。** `MultiReturn` 现实际返回并解包 3 个值(`x, x * 2, x * 3`)而非在被调函数内直接求和(GCC 3.30x,INTERP 2.39x);`TablePack` 现真实调用 `table.pack(...)`;`BM_CPP_ToString` 现与 Lua/FakeLua 一致只转换一次(`5.4 ns`)。 +6. **无 GC 分配场景三后端均快于 Lua,`NativeObject` 字段热路径约 7–14 ns。** `TableChurn`、`StringChurn`、`MixedAlloc` 在解释器上为 Lua 的 0.40x–0.56x,GCC 领先 7.56x–12.64x。8 层深树叶子写入(`11.6 ns`)与浅层 `SetInt`(`10.9 ns`)持平。 ### 算法 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| Fibonacci | 32 | 290.1 ms | 896.3 ms | 3.09x | 5.4 ms | 53.48x | 222.4 ms | 1.30x | -| Sum | 5000000 | 33.8 ms | 76.6 ms | 2.27x | 2.0 ms | 16.73x | 16.2 ms | 2.08x | -| Popcount | 100000 | 17.5 ms | 58.6 ms | 3.35x | 1.0 ms | 16.91x | 3.2 ms | 5.55x | -| FloatPoly | 1000000 | 91.2 ms | 131.1 ms | 1.44x | 3.7 ms | 24.40x | 13.8 ms | 6.59x | -| BubbleSort | 200 | 1.5 ms | 4.2 ms | 2.73x | 159.7 μs | 9.60x | 1.5 ms | 1.04x | -| Sieve | 5000 | 334.1 μs | 828.2 μs | 2.48x | 62.9 μs | 5.31x | 467.2 μs | 0.72x | -| InsertionSort | 200 | 712.5 μs | 2.9 ms | 4.12x | 91.5 μs | 7.79x | 1.1 ms | 0.66x | -| BinarySearch | 1000 | 621.6 μs | 1.8 ms | 2.96x | 273.5 μs | 2.27x | 874.3 μs | 0.71x | -| Vector3 | 1000000 | 213.3 ms | 603.5 ms | 2.83x | 12.1 ms | 17.66x | 147.1 ms | 1.45x | -| MatMul | — | 4.4 μs | 7.5 μs | 1.71x | 1.5 μs | 2.92x | 4.0 μs | 1.10x | -| GCD | 832040/514229 | 551 ns | 1.8 μs | 3.23x | 354 ns | 1.56x | 806 ns | 0.68x | -| PowMod | 2/1000/1000000007 | 681 ns | 1.5 μs | 2.23x | 312 ns | 2.18x | 824 ns | 0.83x | -| FastPow | 2/1000/1000000007 | 753 ns | 1.5 μs | 2.05x | 322 ns | 2.34x | 541 ns | 1.39x | +| Fibonacci | 32 | 112.9 ms | 318.9 ms | 2.82x | 2.51 ms | 45.06x | 63.6 ms | 1.77x | +| Sum | 5000000 | 16.9 ms | 37.0 ms | 2.20x | 1.28 ms | 13.17x | 6.00 ms | 2.81x | +| Popcount | 100000 | 7.50 ms | 13.9 ms | 1.85x | 311.5 μs | 24.08x | 1.11 ms | 6.73x | +| FloatPoly | 1000000 | 24.5 ms | 38.4 ms | 1.57x | 1.53 ms | 16.02x | 22.3 ms | 1.10x | +| BubbleSort | 200 | 387.1 μs | 1.00 ms | 2.59x | 68.0 μs | 5.69x | 551.4 μs | 0.70x | +| Sieve | 5000 | 143.6 μs | 286.5 μs | 2.00x | 30.7 μs | 4.68x | 158.6 μs | 0.91x | +| InsertionSort | 200 | 273.8 μs | 642.2 μs | 2.35x | 39.5 μs | 6.93x | 426.7 μs | 0.64x | +| BinarySearch | 1000 | 210.0 μs | 464.8 μs | 2.21x | 90.1 μs | 2.33x | 356.9 μs | 0.59x | +| Vector3 | 1000000 | 43.6 ms | 149.2 ms | 3.42x | 3.63 ms | 12.00x | 81.3 ms | 0.54x | +| MatMul | — | 1.20 μs | 2.01 μs | 1.68x | 310 ns | 3.86x | 1.27 μs | 0.94x | +| GCD | 2147483647/1073741823 | 45.7 ns | 85.9 ns | 1.88x | 44.5 ns | 1.03x | 67.9 ns | 0.67x | +| PowMod | 1234567/7654321/1000000007 | 383 ns | 588 ns | 1.54x | 198 ns | 1.94x | 320 ns | 1.20x | +| FastPow | 1234567/7654321/1000000007 | 364 ns | 552 ns | 1.52x | 201 ns | 1.81x | 258 ns | 1.41x | ### 函数调用 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| EmptyCall | 100000 | 4.7 ms | 7.8 ms | 1.67x | 384.8 μs | 12.20x | 6.4 ms | 0.74x | -| Recursion | 25 | 15.7 ms | 30.9 ms | 1.96x | 176.4 μs | 89.22x | 8.4 ms | 1.88x | -| Closure | 1000 | 250.5 μs | 257.2 μs | 1.03x | 12.7 μs | 19.76x | 215.0 μs | 1.16x | -| MultiReturn | 10000 | 721.8 μs | 1.1 ms | 1.51x | 31.4 μs | 23.01x | 388.1 μs | 1.86x | -| Variadic | 1 | 661 ns | 2.8 μs | 4.21x | 267 ns | 2.48x | 771 ns | 0.86x | +| EmptyCall | 100000 | 2.23 ms | 3.22 ms | 1.45x | 127.6 μs | 17.45x | 2.59 ms | 0.86x | +| Recursion | 25 | 4.85 ms | 10.9 ms | 2.25x | 91.2 μs | 53.15x | 2.21 ms | 2.19x | +| Closure | 1000 | 89.8 μs | 97.0 μs | 1.08x | 6.26 μs | 14.34x | 79.9 μs | 1.12x | +| MultiReturn | 10000 | 277.3 μs | 663.8 μs | 2.39x | 83.9 μs | 3.30x | 984.7 μs | 0.28x | +| Variadic | 1 | 204 ns | 499 ns | 2.45x | 85.1 ns | 2.39x | 319 ns | 0.64x | ### 字符串 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| StringLen | 10000 | 2.4 μs | 1.0 μs | 0.44x | 964 ns | 2.45x | 1.0 μs | 2.31x | -| StringSub | 10000 | 3.7 μs | 2.0 μs | 0.53x | 1.9 μs | 1.95x | 1.9 μs | 1.96x | -| StringLower | 10000 | 15.9 μs | 2.9 μs | 0.18x | 2.2 μs | 7.08x | 50.5 μs | 0.31x | -| StringUpper | 10000 | 15.8 μs | 2.7 μs | 0.17x | 2.2 μs | 7.20x | 50.9 μs | 0.31x | -| StringFind | 10000 | 2.6 μs | 2.3 μs | 0.90x | 3.2 μs | 0.81x | 19.7 μs | 0.13x | -| StringGsub | 1000 | 43.6 μs | 57.8 μs | 1.33x | 55.7 μs | 0.78x | 55.8 μs | 0.78x | -| StringFindPattern | 1000 | 872.6 μs | 2.9 ms | 3.29x | 2.5 ms | 0.35x | 2.4 ms | 0.36x | -| StringGmatch | 1000 | 1.2 ms | 2.4 ms | 1.96x | 1.6 ms | 0.77x | 1.8 ms | 0.67x | -| StringFormat | 500 | 186.0 μs | 259.3 μs | 1.39x | 6.6 μs | 27.98x | 44.0 μs | 4.23x | -| StringRep | 1000 | 5.3 μs | 4.7 μs | 0.88x | 4.5 μs | 1.18x | 5.4 μs | 0.98x | -| StringReverse | 10000 | 12.8 μs | 11.2 μs | 0.87x | 8.2 μs | 1.56x | 44.2 μs | 0.29x | -| StringByte | 1000 | 751 ns | 1.0 μs | 1.36x | 455 ns | 1.65x | 540 ns | 1.39x | -| StringChar | 500 | 81.6 μs | 157.7 μs | 1.93x | 12.0 μs | 6.79x | 80.4 μs | 1.02x | -| ToNumber | 1 | 213 ns | 570 ns | 2.68x | 234 ns | 0.91x | 537 ns | 0.40x | -| ToString | 500 | 515 ns | 577 ns | 1.12x | 207 ns | 2.48x | 311 ns | 1.66x | +| StringLen | 10000 | 781 ns | 217 ns | 0.28x | 199 ns | 3.93x | 218 ns | 3.58x | +| StringSub | 10000 | 1.21 μs | 412 ns | 0.34x | 338 ns | 3.60x | 382 ns | 3.18x | +| StringLower | 10000 | 5.32 μs | 779 ns | 0.15x | 699 ns | 7.61x | 701 ns | 7.58x | +| StringUpper | 10000 | 5.27 μs | 770 ns | 0.15x | 709 ns | 7.42x | 767 ns | 6.87x | +| StringFind | 10000 | 785 ns | 330 ns | 0.42x | 244 ns | 3.22x | 306 ns | 2.56x | +| StringFindLiteral | 10000 | 793 ns | 337 ns | 0.42x | 287 ns | 2.77x | 348 ns | 2.28x | +| StringGsub | 1000 | 16.0 μs | 14.4 μs | 0.90x | 14.4 μs | 1.12x | 14.0 μs | 1.14x | +| StringFindPattern | 1000 | 311.1 μs | 441.6 μs | 1.42x | 294.5 μs | 1.06x | 463.0 μs | 0.67x | +| StringGmatch | 1000 | 429.6 μs | 523.1 μs | 1.22x | 260.3 μs | 1.65x | 352.2 μs | 1.22x | +| StringFormat | 500 | 48.0 μs | 35.2 μs | 0.73x | 3.29 μs | 14.56x | 21.4 μs | 2.25x | +| StringRep | 1000 | 2.70 μs | 1.41 μs | 0.52x | 2.18 μs | 1.24x | 3.40 μs | 0.80x | +| StringReverse | 10000 | 4.37 μs | 3.08 μs | 0.71x | 2.92 μs | 1.50x | 5.39 μs | 0.81x | +| StringByte | 1000 | 186 ns | 138 ns | 0.74x | 82.8 ns | 2.25x | 107 ns | 1.74x | +| StringChar | 500 | 27.3 μs | 29.7 μs | 1.09x | 5.67 μs | 4.82x | 31.8 μs | 0.86x | +| ToNumber | 1 | 69.6 ns | 101 ns | 1.45x | 68.0 ns | 1.02x | 119 ns | 0.59x | +| ToString | 500 | 127 ns | 118 ns | 0.93x | 54.2 ns | 2.35x | 84.0 ns | 1.52x | ### 表 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| TableCreate | 5000 | 132.2 μs | 263.1 μs | 1.99x | 51.7 μs | 2.56x | 266.1 μs | 0.50x | -| TableInsert | 5000 | 540.7 μs | 1.7 ms | 3.20x | 64.6 μs | 8.37x | 382.7 μs | 1.41x | -| TableRemove | 5000 | 902.4 μs | 2.0 ms | 2.27x | 62.1 μs | 14.53x | 628.7 μs | 1.44x | -| TableConcat | 1000 | 393.5 μs | 324.5 μs | 0.82x | 29.6 μs | 13.28x | 135.2 μs | 2.91x | -| TableSort | 1000 | 368.5 μs | 152.7 μs | 0.41x | 100.2 μs | 3.68x | 158.2 μs | 2.33x | -| TableMove | 5000 | 231.5 μs | 336.7 μs | 1.45x | 98.5 μs | 2.35x | 533.8 μs | 0.43x | -| TablePack | 1 | 1.4 μs | 952 ns | 0.67x | 420 ns | 3.37x | 1.2 μs | 1.21x | -| HashInsert | 1000 | 570.9 μs | 402.9 μs | 0.71x | 82.5 μs | 6.92x | 316.6 μs | 1.80x | -| HashLookup | 1000 | 442.5 μs | 419.3 μs | 0.95x | 38.5 μs | 11.50x | 183.9 μs | 2.41x | -| NestedTable | 10000 | 2.5 ms | 10.0 ms | 3.95x | 798.1 μs | 3.17x | 5.6 ms | 0.45x | +| TableCreate | 5000 | 58.3 μs | 110.2 μs | 1.89x | 21.7 μs | 2.68x | 98.6 μs | 0.59x | +| TableInsert | 5000 | 172.0 μs | 210.4 μs | 1.22x | 24.8 μs | 6.93x | 130.2 μs | 1.32x | +| TableRemove | 5000 | 325.4 μs | 294.5 μs | 0.91x | 31.6 μs | 10.30x | 240.8 μs | 1.35x | +| TableConcat | 1000 | 112.8 μs | 59.3 μs | 0.53x | 15.9 μs | 7.09x | 44.7 μs | 2.53x | +| TableSort | 1000 | 180.5 μs | 71.8 μs | 0.40x | 48.2 μs | 3.75x | 65.2 μs | 2.77x | +| TableMove | 5000 | 99.8 μs | 156.1 μs | 1.56x | 47.6 μs | 2.10x | 207.1 μs | 0.48x | +| TablePack | 1 | 211 ns | 318 ns | 1.51x | 247 ns | 0.85x | 349 ns | 0.61x | +| HashInsert | 1000 | 174.3 μs | 97.5 μs | 0.56x | 32.9 μs | 5.29x | 125.1 μs | 1.39x | +| HashLookup | 1000 | 128.2 μs | 83.4 μs | 0.65x | 22.3 μs | 5.74x | 68.1 μs | 1.88x | +| NestedTable | 10000 | 880.3 μs | 2.61 ms | 2.97x | 331.9 μs | 2.65x | 2.12 ms | 0.41x | ### 数学 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| MathTrig | 100000 | 28.8 ms | 65.7 ms | 2.28x | 9.1 ms | 3.15x | 18.6 ms | 1.55x | -| MathSqrt | 100000 | 7.5 ms | 20.7 ms | 2.78x | 322.6 μs | 23.13x | 4.8 ms | 1.54x | -| MathExpLog | 100000 | 25.7 ms | 69.6 ms | 2.71x | 5.4 ms | 4.75x | 12.9 ms | 2.00x | -| MathMinMax | 100000 | 34.6 ms | 103.4 ms | 2.99x | 4.6 ms | 7.50x | 17.5 ms | 1.97x | +| MathTrig | 100000 | 5.78 ms | 7.57 ms | 1.31x | 963.4 μs | 6.00x | 9.05 ms | 0.64x | +| MathSqrt | 100000 | 2.47 ms | 3.02 ms | 1.22x | 152.0 μs | 16.27x | 2.42 ms | 1.02x | +| MathExpLog | 100000 | 5.16 ms | 7.11 ms | 1.38x | 657.1 μs | 7.85x | 7.14 ms | 0.72x | +| MathMinMax | 100000 | 8.00 ms | 10.5 ms | 1.32x | 742.6 μs | 10.77x | 6.85 ms | 1.17x | ### 分配 -| 场景 | 参数 | Lua 5.4 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | +| 场景 | 参数 | Lua 5.4.8 | INTERP | INTERP/Lua | GCC | GCC/Lua | TCC | TCC/Lua | |---|---|---:|---:|---:|---:|---:|---:|---:| -| TableChurn | 1000 | 587.6 μs | 324.2 μs | 0.55x | 39.5 μs | 14.88x | 314.6 μs | 1.87x | -| StringChurn | 1000 | 1.1 ms | 775.7 μs | 0.69x | 52.9 μs | 21.28x | 319.3 μs | 3.53x | -| MixedAlloc | 1000 | 1.1 ms | 766.8 μs | 0.68x | 68.6 μs | 16.33x | 398.8 μs | 2.81x | - +| TableChurn | 1000 | 161.3 μs | 90.7 μs | 0.56x | 21.3 μs | 7.56x | 110.6 μs | 1.46x | +| StringChurn | 1000 | 334.1 μs | 133.5 μs | 0.40x | 26.4 μs | 12.64x | 97.2 μs | 3.44x | +| MixedAlloc | 1000 | 315.7 μs | 176.3 μs | 0.56x | 36.3 μs | 8.70x | 153.5 μs | 2.06x | + +### NativeObject + +C++ 宿主侧 `NativeObject` 热路径操作(无 Lua 对照项)。 + +| 基准项 | CPU 时间 | +|---|---:| +| `BM_NativeObjectSetInt` | 10.9 ns | +| `BM_NativeObjectGetInt` | 7.0 ns | +| `BM_NativeObjectSetString` | 13.6 ns | +| `BM_NativeObjectCreateDestroy` | 152 ns | +| `BM_NativeObjectSetObject` | 11.3 ns | +| `BM_NativeObjectDeepLeafWrite` | 11.6 ns | diff --git a/benchmark/benchmark_algo.cpp b/benchmark/benchmark_algo.cpp index a5b1b3b6..cbe97c45 100644 --- a/benchmark/benchmark_algo.cpp +++ b/benchmark/benchmark_algo.cpp @@ -1153,7 +1153,7 @@ 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); } } @@ -1161,7 +1161,7 @@ static void BM_CPP_FloatPoly(benchmark::State &state) { 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); } } diff --git a/benchmark/benchmark_function.cpp b/benchmark/benchmark_function.cpp index 8a71abb6..c5790250 100644 --- a/benchmark/benchmark_function.cpp +++ b/benchmark/benchmark_function.cpp @@ -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 )"; diff --git a/benchmark/benchmark_math.cpp b/benchmark/benchmark_math.cpp index 95e3fbfd..cbb513c6 100644 --- a/benchmark/benchmark_math.cpp +++ b/benchmark/benchmark_math.cpp @@ -121,7 +121,7 @@ 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); } } @@ -129,7 +129,7 @@ static void BM_CPP_MathTrig(benchmark::State &state) { 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); } } @@ -166,7 +166,7 @@ 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); } } @@ -174,7 +174,7 @@ static void BM_CPP_MathSqrt(benchmark::State &state) { 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); } } @@ -211,7 +211,7 @@ 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); } } @@ -219,7 +219,7 @@ static void BM_CPP_MathExpLog(benchmark::State &state) { 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); } } @@ -256,7 +256,7 @@ 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); } } @@ -264,7 +264,7 @@ static void BM_CPP_MathMinMax(benchmark::State &state) { 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); } } diff --git a/benchmark/benchmark_string.cpp b/benchmark/benchmark_string.cpp index 289c13a3..65a503bc 100644 --- a/benchmark/benchmark_string.cpp +++ b/benchmark/benchmark_string.cpp @@ -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); } } @@ -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); } } @@ -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"); } } @@ -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); } } diff --git a/benchmark/benchmark_table.cpp b/benchmark/benchmark_table.cpp index 3922e374..36c85a33 100644 --- a/benchmark/benchmark_table.cpp +++ b/benchmark/benchmark_table.cpp @@ -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 )"; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f9cd1ffb..8901d1d4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -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 @@ -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) @@ -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() diff --git a/src/native/README.md b/src/native/README.md index a8bc3687..f6228b17 100644 --- a/src/native/README.md +++ b/src/native/README.md @@ -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 | @@ -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 | --- @@ -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. @@ -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` @@ -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`) @@ -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}` @@ -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_"] = 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` @@ -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}` @@ -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 | |----------|------|-------------| @@ -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` diff --git a/src/native/README.zh.md b/src/native/README.zh.md index 02dc9933..15dbdf14 100644 --- a/src/native/README.zh.md +++ b/src/native/README.zh.md @@ -16,7 +16,7 @@ | utf8 | `utf8/` | UTF-8 编解码:`char`、`codepoint`、`codes`、`len`、`offset` | | io | `io/` | 文件 IO:open、close、read、write、seek、popen、标准流 | | net | `net/` | TCP/UDP 网络:服务端/客户端、帧协议、自定义解析器、异步事件分发 | -| http | `http/` | HTTP/1.1 客户端和服务端(Boost.Beast),由 `runtime.tick()` 驱动 | +| http | `http/` | HTTP/1.1 客户端和服务端(libevent),由 `runtime.tick()` 驱动 | | url | `url/` | URL 解析/拼接与百分号编解码(Boost.URL) | | timer | `timer/` | 定时器:一次性、周期心跳,由 `runtime.tick()` 驱动 | | runtime | `runtime/` | 统一事件泵:`runtime.tick()` 驱动所有需要周期推进的模块 | @@ -32,11 +32,12 @@ | xml | `xml/` | XML 解码/编码(pugixml) | | ini | `ini/` | INI 解码/编码(inih) | | mysql | `mysql/` | 异步 MySQL 客户端:直连 + 连接池 | -| redis | `redis/` | 异步 Redis 客户端(Boost.Redis) | +| redis | `redis/` | 异步 Redis 客户端(hiredis + libevent) | | sqlite | `sqlite/` | SQLite3 封装:exec、预处理语句、同步 | -| process | `process/` | 子进程(Boost.Process v2);不替换 `os.execute` | +| process | `process/` | 子进程(POSIX `fork`/`execve`,Windows `CreateProcessW`);不替换 `os.execute` | | serialize | `serialize/` | 二进制序列化:zigzag + varint 编码 + 字符串去重 | | protobuf | `protobuf/` | 运行时 .proto 解析、标准 protobuf3 wire 编码/解码 | +| log | `log/` | 每 `State` 日志:`trace`、`debug`、`info`、`warn`、`error`、`critical`、`set_level`、`set_file` | | object | `object/` | NativeObject Lua 侧 API:组管理、对象创建/查找 | --- @@ -54,8 +55,8 @@ native 层按这个前提组织:**所有可变状态都挂在 `State` 上**, - 定时器、事件监听、net/mysql/sqlite/io 的对象表、protobuf 的 .proto schema 注册表,都是每 `State` 一份,一个 `State` 里注册的东西不会泄漏到另一个; - 复用的临时缓冲区归它服务的那个对象:解包用的线性暂存区在 `CircularBuffer` 上 - (`HeaderScratch` / `PayloadScratch`)。WebSocket 走 Boost.Beast,握手与掩码由 - Beast 在连接上处理;低频随机数(生成临时文件名)直接用局部变量。 + (`HeaderScratch` / `PayloadScratch`)。WebSocket 基于 libevent(`bufferevent`),握手与掩码 + 由连接对象自行维护;低频随机数(生成临时文件名)直接用局部变量。 JIT 的错误边界链(`jit_error_boundary.h`)也挂在 `State` 上:链顶存在 `State::GetJitErrorBoundary()`,边界对象本身在 C++ 栈上。`RunWithJitErrorBoundary` / @@ -126,11 +127,11 @@ JIT 的错误边界链(`jit_error_boundary.h`)也挂在 `State` 上:链顶 | `math.ult(x, y)` | 2 | 无符号小于比较 | | `math.random(...)` | vararg | 随机数:0 参 [0,1),1 参 [1,u],2 参 [l,u] | | `math.randomseed(...)` | vararg | 设置随机种子 | -| `math.erf(x)` | 1 | 误差函数(Boost.Math) | +| `math.erf(x)` | 1 | 误差函数 | | `math.erfc(x)` | 1 | 余误差函数 | | `math.gamma(x)` | 1 | Gamma 函数 Γ(x) | | `math.lgamma(x)` | 1 | Log-gamma ln Γ(x) | -| `math.clamp(x, lo, hi)` | 3 | 将 `x` 限制在 `[lo, hi]`(Boost.Algorithm;三个参数都是整数则返回整数) | +| `math.clamp(x, lo, hi)` | 3 | 将 `x` 限制在 `[lo, hi]`(三个参数都是整数则返回整数) | **常量:** `math.pi`、`math.huge`、`math.maxinteger`、`math.mininteger` @@ -297,7 +298,7 @@ Windows 上 `io.open` / `loadfile` / `dofile` / `os.getenv` / `os.tmpname` 以 | `line` | 换行符分隔,自动去除 | | `fixed` | 固定长度(需 `fixed_len = N`) | | `raw` | 原始透传 | -| `websocket` / `ws` | RFC 6455 WebSocket(文本帧,Boost.Beast) | +| `websocket` / `ws` | RFC 6455 WebSocket(文本帧,libevent) | **自定义解析器:** `parser = "Package.func"`(Lua)或 `custom_parser_fn`/`custom_encoder_fn`(C++ `NetConfig`) @@ -329,7 +330,7 @@ Windows 上 `io.open` / `loadfile` / `dofile` / `os.getenv` / `os.tmpname` 以 **文件:** `http/native_http.h` · **注册:** `RegisterHttpLibraryApi` -基于 Boost.Beast 的 HTTP/1.1 客户端和服务端,复用每个 State 一份的 Asio `io_context`。URL 用 Boost.URL 解析。`https://` 走 TLS(OpenSSL);`http.get`/`http.post` 默认校验证书。完成回调由 `runtime.tick()` 驱动。 +基于 libevent(`bufferevent`)的 HTTP/1.1 客户端和服务端,复用每个 State 一份的 libevent `event_base`。URL 用 Boost.URL 解析。`https://` 走 TLS(OpenSSL);`http.get`/`http.post` 默认校验证书。完成回调由 `runtime.tick()` 驱动。 **`http.request` 配置:** `{method, url, headers, body, timeout_ms, version, tls_verify, tls_ca}` @@ -710,7 +711,7 @@ end **文件:** `redis/native_redis.h` · **注册:** `RegisterRedisLibraryApi` -基于 Boost.Redis 的异步客户端。关闭重连和健康检查,连接失败只回调一次。由 `runtime.tick()` 驱动。 +基于 hiredis(libevent 适配器,复用每个 State 的 `event_base`)的异步客户端。关闭重连和健康检查,连接失败只回调一次。由 `runtime.tick()` 驱动。 **`redis.connect` 配置:** `{host, port, user, password, db, timeout_ms}` @@ -752,7 +753,7 @@ end **文件:** `process/native_process.h` · **注册:** `RegisterProcessLibraryApi` -Boost.Process v2。**不**替换 `os.execute`(后者仍返回 Lua 的 `(status, how, code)` 三元组)。 +底层使用 POSIX `fork`/`execve`/`waitpid`(Windows 上为 Win32 `CreateProcessW`)。**不**替换 `os.execute`(后者仍返回 Lua 的 `(status, how, code)` 三元组)。 | 函数 | 参数 | 说明 | |------|------|------| @@ -799,6 +800,25 @@ Boost.Process v2。**不**替换 `os.execute`(后者仍返回 Lua 的 `(status --- +## Log(日志) + +**文件:** `log/native_log.h` · **注册:** `RegisterLogLibraryApi` + +每 `State` 独立配置的结构化日志,脚本侧统一 tag 为 `"script"`。多个参数按制表符拼接(与 `print` 风格一致)。日志级别对应 `LogLevel`:`0` Trace、`1` Debug、`2` Info、`3` Warn、`4` Error、`5` Critical。 + +| 函数 | 参数 | 说明 | +|------|------|------| +| `log.trace(msg, ...)` | vararg(≥1) | 输出 Trace 级别日志 | +| `log.debug(msg, ...)` | vararg(≥1) | 输出 Debug 级别日志 | +| `log.info(msg, ...)` | vararg(≥1) | 输出 Info 级别日志 | +| `log.warn(msg, ...)` | vararg(≥1) | 输出 Warn 级别日志 | +| `log.error(msg, ...)` | vararg(≥1) | 输出 Error 级别日志 | +| `log.critical(msg, ...)` | vararg(≥1) | 输出 Critical 级别日志 | +| `log.set_level(level)` | 1 | 设置当前 `State` 最低日志级别(整数 `0`–`5`) | +| `log.set_file(path)` | 1 | 设置当前 `State` 轮转日志文件路径(空串表示关闭文件输出,仅控制台) | + +--- + ## NativeObject(Lua 侧 API) **文件:** `object/native_object.h` · **注册:** `RegisterNativeObjectApi` diff --git a/src/util/string_util.cpp b/src/util/string_util.cpp index 54a2715e..320cb792 100644 --- a/src/util/string_util.cpp +++ b/src/util/string_util.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include namespace fakelua { @@ -126,14 +125,120 @@ std::string ReplaceEscapeChars(const std::string &str) { return result; } +namespace { + +bool IsAsciiDigit(char c) { + return c >= '0' && c <= '9'; +} + +bool IsAsciiHexDigit(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); +} + +}// namespace + bool IsNumber(const std::string_view &str) { - static const boost::regex re("^[+-]?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?$|^[+-]?0[xX][0-9a-fA-F]+(\\.[0-9a-fA-F]+)?([pP][+-]?[0-9]+)?$"); - return boost::regex_match(str.begin(), str.end(), re); + size_t i = 0; + const size_t n = str.size(); + if (i < n && (str[i] == '+' || str[i] == '-')) { + ++i; + } + if (i >= n) { + return false; + } + + if (i + 1 < n && str[i] == '0' && (str[i + 1] == 'x' || str[i + 1] == 'X')) { + i += 2; + const size_t int_start = i; + while (i < n && IsAsciiHexDigit(str[i])) { + ++i; + } + if (i == int_start) { + return false; + } + if (i < n && str[i] == '.') { + ++i; + const size_t frac_start = i; + while (i < n && IsAsciiHexDigit(str[i])) { + ++i; + } + if (i == frac_start) { + return false; + } + } + if (i < n && (str[i] == 'p' || str[i] == 'P')) { + ++i; + if (i < n && (str[i] == '+' || str[i] == '-')) { + ++i; + } + const size_t exp_start = i; + while (i < n && IsAsciiDigit(str[i])) { + ++i; + } + if (i == exp_start) { + return false; + } + } + return i == n; + } + + const size_t int_start = i; + while (i < n && IsAsciiDigit(str[i])) { + ++i; + } + if (i == int_start) { + return false; + } + if (i < n && str[i] == '.') { + ++i; + const size_t frac_start = i; + while (i < n && IsAsciiDigit(str[i])) { + ++i; + } + if (i == frac_start) { + return false; + } + } + if (i < n && (str[i] == 'e' || str[i] == 'E')) { + ++i; + if (i < n && (str[i] == '+' || str[i] == '-')) { + ++i; + } + const size_t exp_start = i; + while (i < n && IsAsciiDigit(str[i])) { + ++i; + } + if (i == exp_start) { + return false; + } + } + return i == n; } bool IsInteger(const std::string_view &str) { - static const boost::regex re("^[+-]?[0-9]+$|^[+-]?0[xX][0-9a-fA-F]+$"); - return boost::regex_match(str.begin(), str.end(), re); + size_t i = 0; + const size_t n = str.size(); + if (i < n && (str[i] == '+' || str[i] == '-')) { + ++i; + } + if (i >= n) { + return false; + } + + if (i + 1 < n && str[i] == '0' && (str[i + 1] == 'x' || str[i + 1] == 'X')) { + i += 2; + const size_t start = i; + while (i < n && IsAsciiHexDigit(str[i])) { + ++i; + } + return i > start && i == n; + } + + const size_t start = i; + while (i < n && IsAsciiDigit(str[i])) { + ++i; + } + return i > start && i == n; } namespace { diff --git a/test/test_common.cpp b/test/test_common.cpp index c054360d..d9d87e78 100644 --- a/test/test_common.cpp +++ b/test/test_common.cpp @@ -155,6 +155,7 @@ TEST(common, vi_sort) { } TEST(common, IsNumber) { + ASSERT_TRUE(IsNumber("0")); ASSERT_TRUE(IsNumber("123")); ASSERT_TRUE(IsNumber("-123")); ASSERT_TRUE(IsNumber("+123")); @@ -162,29 +163,80 @@ TEST(common, IsNumber) { ASSERT_TRUE(IsNumber("123.456")); ASSERT_TRUE(IsNumber("-123.456")); ASSERT_TRUE(IsNumber("+123.456")); + ASSERT_TRUE(IsNumber("0.0")); ASSERT_TRUE(IsNumber("123e456")); ASSERT_TRUE(IsNumber("-123e-456")); ASSERT_TRUE(IsNumber("+123E+456")); + ASSERT_TRUE(IsNumber("12.34e-5")); ASSERT_TRUE(IsNumber("0x123")); + ASSERT_TRUE(IsNumber("0x0")); + ASSERT_TRUE(IsNumber("0xabcdefABCDEF")); ASSERT_TRUE(IsNumber("-0X123")); ASSERT_TRUE(IsNumber("+0x123.456")); + ASSERT_TRUE(IsNumber("+0x1a.f0")); + ASSERT_TRUE(IsNumber("0x1p0")); + ASSERT_TRUE(IsNumber("0x1P-10")); ASSERT_TRUE(IsNumber("-0X123.456P+789")); + // Edge cases that must be rejected (exact parity with original regex) + ASSERT_FALSE(IsNumber("")); + ASSERT_FALSE(IsNumber("+")); + ASSERT_FALSE(IsNumber("-")); + ASSERT_FALSE(IsNumber(".")); + ASSERT_FALSE(IsNumber(".5")); + ASSERT_FALSE(IsNumber("5.")); + ASSERT_FALSE(IsNumber("1e")); + ASSERT_FALSE(IsNumber("1e+")); + ASSERT_FALSE(IsNumber("1e-")); + ASSERT_FALSE(IsNumber("1.e5")); + ASSERT_FALSE(IsNumber("1e2.3")); + ASSERT_FALSE(IsNumber("0x")); + ASSERT_FALSE(IsNumber("+0x")); + ASSERT_FALSE(IsNumber("-0X")); + ASSERT_FALSE(IsNumber("0x.1")); + ASSERT_FALSE(IsNumber("0x1.")); + ASSERT_FALSE(IsNumber("0x1p")); + ASSERT_FALSE(IsNumber("0x1p+")); + ASSERT_FALSE(IsNumber("0x1pA")); + ASSERT_FALSE(IsNumber("0x1g")); + ASSERT_FALSE(IsNumber(" 123")); + ASSERT_FALSE(IsNumber("123 ")); + ASSERT_FALSE(IsNumber("123\n")); + ASSERT_FALSE(IsNumber("++1")); + ASSERT_FALSE(IsNumber("--1")); + ASSERT_FALSE(IsNumber(std::string_view("123\0", 4))); ASSERT_FALSE(IsNumber("abc")); ASSERT_FALSE(IsNumber("123abc")); ASSERT_FALSE(IsNumber("123.456.789")); } TEST(common, IsInteger) { + ASSERT_TRUE(IsInteger("0")); + ASSERT_TRUE(IsInteger("00")); ASSERT_TRUE(IsInteger("123")); ASSERT_TRUE(IsInteger("-123")); ASSERT_TRUE(IsInteger("+123")); + ASSERT_TRUE(IsInteger("0x0")); ASSERT_TRUE(IsInteger("0x123")); + ASSERT_TRUE(IsInteger("+0xdeadBEEF")); ASSERT_TRUE(IsInteger("-0X123")); + // Edge cases that must be rejected (exact parity with original regex) + ASSERT_FALSE(IsInteger("")); + ASSERT_FALSE(IsInteger("+")); + ASSERT_FALSE(IsInteger("-")); + ASSERT_FALSE(IsInteger("0x")); + ASSERT_FALSE(IsInteger("+0x")); + ASSERT_FALSE(IsInteger("-0X")); + ASSERT_FALSE(IsInteger("0x1g")); + ASSERT_FALSE(IsInteger(" 123")); + ASSERT_FALSE(IsInteger("123 ")); + ASSERT_FALSE(IsInteger("123\n")); + ASSERT_FALSE(IsInteger("++1")); + ASSERT_FALSE(IsInteger(std::string_view("123\0", 4))); ASSERT_FALSE(IsInteger("123.456")); ASSERT_FALSE(IsInteger("-123.456")); ASSERT_FALSE(IsInteger("+123.456")); @@ -193,6 +245,7 @@ TEST(common, IsInteger) { ASSERT_FALSE(IsInteger("+123E+456")); ASSERT_FALSE(IsInteger("+0x123.456")); ASSERT_FALSE(IsInteger("-0X123.456P+789")); + ASSERT_FALSE(IsInteger("0x1p2")); ASSERT_FALSE(IsInteger("abc")); ASSERT_FALSE(IsInteger("123abc")); ASSERT_FALSE(IsInteger("123.456.789")); diff --git a/test/test_jitter.cpp b/test/test_jitter.cpp index f7ac4938..74287873 100644 --- a/test/test_jitter.cpp +++ b/test/test_jitter.cpp @@ -4051,7 +4051,9 @@ TEST(jitter, gcc_cache_dependency_and_compiler_invalidation) { std::filesystem::create_directory(entry.string() + ".tmp"); } const char mark = 'x'; - (void) write(ready[1], &mark, 1); + if (write(ready[1], &mark, 1) != 1) { + _exit(4); + } _exit(0); } catch (...) { _exit(3); diff --git a/test/test_net.cpp b/test/test_net.cpp index ed29b0ac..a104931d 100644 --- a/test/test_net.cpp +++ b/test/test_net.cpp @@ -750,8 +750,11 @@ TEST(test_net, websocket_fragmented_extended_frame_control_frame_and_close) { EXPECT_FALSE(HasNetEvent(server_events, net::EventKind::Recv)); ASSERT_TRUE(client.Send(frame.data() + 2, frame.size() - 2)); ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(server_events, net::EventKind::Recv); })); - for (const auto &event: server_events) - if (event.kind == net::EventKind::Recv) EXPECT_EQ(event.data, payload); + for (const auto &event: server_events) { + if (event.kind == net::EventKind::Recv) { + EXPECT_EQ(event.data, payload); + } + } ASSERT_TRUE(server.Send(0, payload.data(), payload.size())); ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { size_t bytes = 0;